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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 7,630 | 2.6875 | 3 | [] | no_license | package model;
import java.time.LocalDate;
public class TradeVO {
private int t_number; // 거래번호
private String f_number; // 제품코드
private int c_number; // 고객번호
private String c_name; // 고객명
private String c_phone; // 연락처
private String t_email; // 이메일
private int t_amount; // 총수량
private int t_price; // 총가격
private int t_deposit; // 선금
private int t_penalty; // 위약금
private int t_balance; // 잔금
private int t_receipt; // 수령액
private int t_unpaid; // 미납금
private String t_status; // 거래상태
private String t_registdate; // 거래일
private String t_address; // 배달주소
private String t_remarks; // 비고
private String f_f_sort; // 종류
private String f_f_name; // 제품명
private String f_f_color; // 색상
private String f_f_size; // 사이즈
private String f_f_weight; // 중량
private String f_f_price; // 가격
private String f_f_phone; // 담당자연락처
public TradeVO() {
super();
}
public TradeVO(String f_number, int c_number, String c_name, String c_phone, String t_email, int t_amount,
int t_price, String t_status, String t_address, String t_remarks, String f_f_sort, String f_f_name,
String f_f_color, String f_f_size, String f_f_weight, String f_f_price, String f_f_phone) {
super();
this.f_number = f_number;
this.c_number = c_number;
this.c_name = c_name;
this.c_phone = c_phone;
this.t_email = t_email;
this.t_amount = t_amount;
this.t_price = t_price;
this.t_status = t_status;
this.t_address = t_address;
this.t_remarks = t_remarks;
this.f_f_sort = f_f_sort;
this.f_f_name = f_f_name;
this.f_f_color = f_f_color;
this.f_f_size = f_f_size;
this.f_f_weight = f_f_weight;
this.f_f_price = f_f_price;
this.f_f_phone = f_f_phone;
}
public TradeVO(String f_number, int c_number, String c_name, String c_phone, String t_email, int t_amount,
int t_price, String t_address, String t_remarks, String f_f_sort, String f_f_name, String f_f_color,
String f_f_size, String f_f_weight, String f_f_price, String f_f_phone) {
super();
this.f_number = f_number;
this.c_number = c_number;
this.c_name = c_name;
this.c_phone = c_phone;
this.t_email = t_email;
this.t_amount = t_amount;
this.t_price = t_price;
this.t_address = t_address;
this.t_remarks = t_remarks;
this.f_f_sort = f_f_sort;
this.f_f_name = f_f_name;
this.f_f_color = f_f_color;
this.f_f_size = f_f_size;
this.f_f_weight = f_f_weight;
this.f_f_price = f_f_price;
this.f_f_phone = f_f_phone;
}
public TradeVO(int t_number, String f_number, int c_number, String c_name, String c_phone, String t_email,
int t_amount, int t_price, int t_deposit, int t_penalty, int t_balance, int t_receipt, int t_unpaid,
String t_status, String t_registdate, String t_address, String t_remarks, String f_f_sort, String f_f_name,
String f_f_color, String f_f_size, String f_f_weight, String f_f_price, String f_f_phone) {
super();
this.t_number = t_number;
this.f_number = f_number;
this.c_number = c_number;
this.c_name = c_name;
this.c_phone = c_phone;
this.t_email = t_email;
this.t_amount = t_amount;
this.t_price = t_price;
this.t_deposit = t_deposit;
this.t_penalty = t_penalty;
this.t_balance = t_balance;
this.t_receipt = t_receipt;
this.t_unpaid = t_unpaid;
this.t_status = t_status;
this.t_registdate = t_registdate;
this.t_address = t_address;
this.t_remarks = t_remarks;
this.f_f_sort = f_f_sort;
this.f_f_name = f_f_name;
this.f_f_color = f_f_color;
this.f_f_size = f_f_size;
this.f_f_weight = f_f_weight;
this.f_f_price = f_f_price;
this.f_f_phone = f_f_phone;
}
public TradeVO(int t_number, String f_number, int c_number, String c_name, String c_phone, String t_email,
int t_amount, int t_price, int t_deposit, int t_penalty, int t_balance, int t_receipt, int t_unpaid,
String t_status, String t_registdate, String t_address, String t_remarks) {
super();
this.t_number = t_number;
this.f_number = f_number;
this.c_number = c_number;
this.c_name = c_name;
this.c_phone = c_phone;
this.t_email = t_email;
this.t_amount = t_amount;
this.t_price = t_price;
this.t_deposit = t_deposit;
this.t_penalty = t_penalty;
this.t_balance = t_balance;
this.t_receipt = t_receipt;
this.t_unpaid = t_unpaid;
this.t_status = t_status;
this.t_registdate = t_registdate;
this.t_address = t_address;
this.t_remarks = t_remarks;
}
public int getT_number() {
return t_number;
}
public void setT_number(int t_number) {
this.t_number = t_number;
}
public String getF_number() {
return f_number;
}
public void setF_number(String f_number) {
this.f_number = f_number;
}
public int getC_number() {
return c_number;
}
public void setC_number(int c_number) {
this.c_number = c_number;
}
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getC_phone() {
return c_phone;
}
public void setC_phone(String c_phone) {
this.c_phone = c_phone;
}
public String getT_email() {
return t_email;
}
public void setT_email(String t_email) {
this.t_email = t_email;
}
public int getT_amount() {
return t_amount;
}
public void setT_amount(int t_amount) {
this.t_amount = t_amount;
}
public int getT_price() {
return t_price;
}
public void setT_price(int t_price) {
this.t_price = t_price;
}
public int getT_deposit() {
return t_deposit;
}
public void setT_deposit(int t_deposit) {
this.t_deposit = t_deposit;
}
public int getT_penalty() {
return t_penalty;
}
public void setT_penalty(int t_penalty) {
this.t_penalty = t_penalty;
}
public int getT_balance() {
return t_balance;
}
public void setT_balance(int t_balance) {
this.t_balance = t_balance;
}
public int getT_receipt() {
return t_receipt;
}
public void setT_receipt(int t_receipt) {
this.t_receipt = t_receipt;
}
public int getT_unpaid() {
return t_unpaid;
}
public void setT_unpaid(int t_unpaid) {
this.t_unpaid = t_unpaid;
}
public String getT_status() {
return t_status;
}
public void setT_status(String t_status) {
this.t_status = t_status;
}
public String getT_registdate() {
return t_registdate;
}
public void setT_registdate(String t_registdate) {
this.t_registdate = t_registdate;
}
public String getT_address() {
return t_address;
}
public void setT_address(String t_address) {
this.t_address = t_address;
}
public String getT_remarks() {
return t_remarks;
}
public void setT_remarks(String t_remarks) {
this.t_remarks = t_remarks;
}
public String getF_f_sort() {
return f_f_sort;
}
public void setF_f_sort(String f_f_sort) {
this.f_f_sort = f_f_sort;
}
public String getF_f_name() {
return f_f_name;
}
public void setF_f_name(String f_f_name) {
this.f_f_name = f_f_name;
}
public String getF_f_color() {
return f_f_color;
}
public void setF_f_color(String f_f_color) {
this.f_f_color = f_f_color;
}
public String getF_f_size() {
return f_f_size;
}
public void setF_f_size(String f_f_size) {
this.f_f_size = f_f_size;
}
public String getF_f_weight() {
return f_f_weight;
}
public void setF_f_weight(String f_f_weight) {
this.f_f_weight = f_f_weight;
}
public String getF_f_price() {
return f_f_price;
}
public void setF_f_price(String f_f_price) {
this.f_f_price = f_f_price;
}
public String getF_f_phone() {
return f_f_phone;
}
public void setF_f_phone(String f_f_phone) {
this.f_f_phone = f_f_phone;
}
}
|
PHP | UTF-8 | 2,756 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
/**
* FilterQuery.php
*
* @since 19/01/17
* @author gseidel
*/
namespace Enhavo\Bundle\AppBundle\Filter;
use Enhavo\Bundle\AppBundle\Controller\RequestConfiguration;
use Enhavo\Bundle\AppBundle\Exception\FilterException;
use Enhavo\Bundle\AppBundle\Type\CollectorInterface;
use Symfony\Component\HttpFoundation\Request;
class FilterQueryBuilder
{
/**
* @var CollectorInterface
*/
protected $collector;
/**
* AbstractRenderer constructor.
*
* @param CollectorInterface $collector
*/
public function __construct(CollectorInterface $collector)
{
$this->collector = $collector;
}
public function buildQueryFromRequestConfiguration(RequestConfiguration $requestConfiguration)
{
$request = $requestConfiguration->getRequest();
$filters = $requestConfiguration->getFilters();
$criteria = $requestConfiguration->getCriteria();
$sorting = $requestConfiguration->getSorting();
return $this->buildQueryFromRequest($request, $filters, $sorting, $criteria);
}
public function buildQueryFromRequest(Request $request, $filters, $sorting = [], $criteria = [])
{
$filterQuery = $this->createFilterQuery();
foreach($sorting as $property => $order) {
$filterQuery->addOrderBy($property, $order);
}
foreach($criteria as $property => $value) {
$filterQuery->addWhere($property, FilterQuery::OPERATOR_EQUALS, $value);
}
$requestFilters = $request->query->get('filters', null);
if($requestFilters === null) {
return $filterQuery;
}
$requestFilters = json_decode($requestFilters, true);
if(!is_array($requestFilters)) {
throw new FilterException('Filter was not a json array');
}
foreach($requestFilters as $filter) {
$name = $filter['name'];
$value = $filter['value'];
if(!array_key_exists($name, $filters)) {
throw new FilterException(sprintf('Filter was not defined'));
}
$filter = $filters[$name];
if(!array_key_exists('type', $filter)) {
throw new FilterException('Filter type was not defined');
}
$this->buildQuery($filter['type'], $value, $filter, $filterQuery);
}
return $filterQuery;
}
protected function buildQuery($type, $value, $options, FilterQuery $filterQuery)
{
/** @var FilterInterface $filter */
$filter = $this->collector->getType($type);
$filter->buildQuery($filterQuery, $options, $value);
}
protected function createFilterQuery()
{
return new FilterQuery();
}
} |
Python | UTF-8 | 114 | 2.890625 | 3 | [] | no_license | s,n=0,int(input())
for i in range(1,int(n**.5)+1):
if n%i==0:
s+=i
if i*i!=n:s+=n//i
print(s)
|
Markdown | UTF-8 | 3,243 | 3.625 | 4 | [] | no_license | # 843. Guess the Word
### hard
This problem is an interactive problem new to the LeetCode platform.
We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret.
You may call master.guess(word) to guess a word. The guessed word should have type string and must be from the original list with 6 lowercase letters.
This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1 instead.
For each test case, you have 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or less calls to master.guess and at least one of these guesses was the secret, you pass the testcase.
Besides the example test case below, there will be 5 additional test cases, each with 100 words in the word list. The letters of each word in those testcases were chosen independently at random from 'a' to 'z', such that every word in the given word lists is unique.
Example 1:
Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"]
Explanation:
master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.
master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.
master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.
master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.
master.guess("abcczz") returns 4, because "abcczz" has 4 matches.
We made 5 calls to master.guess and one of them was the secret, so we pass the test case.
Note: Any solutions that attempt to circumvent the judge will result in disqualification.
```java
/**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* interface Master {
* public int guess(String word) {}
* }
*/
class Solution {
// O n^2 time O n space, can pass all tests within 10 guesses
int match(String s1, String s2) {
int res = 0;
for (int i = 0; i < 6; i++) {
if (s1.charAt(i) == s2.charAt(i)) res++;
}
return res;
}
public void findSecretWord(String[] wordlist, Master master) {
for (int guess = 0; guess < 10; guess++) {
Map<String, Integer> count = new HashMap<>();
for (String w1: wordlist) {
for (String w2: wordlist) {
if (match(w1, w2) == 0) count.put(w1, count.getOrDefault(w1, 0) + 1);
}
}
int minZeroMatchCount = Integer.MAX_VALUE;
String minZeroMatch = "";
for (String w: wordlist) {
if (count.getOrDefault(w, 0) < minZeroMatchCount) {
minZeroMatchCount = count.getOrDefault(w, 0);
minZeroMatch = w;
}
}
int curGuess = master.guess(minZeroMatch);
List<String> list = new ArrayList<>();
for (String w: wordlist) {
if (match(w, minZeroMatch) == curGuess) list.add(w);
}
wordlist = list.toArray(new String[0]); // Create a certain type of Array
}
}
}
``` |
Java | UTF-8 | 494 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package org.gluu.casa.plugins.credentials.extensions;
import org.gluu.casa.extension.navigation.MenuType;
import org.gluu.casa.extension.navigation.NavigationMenu;
import org.pf4j.Extension;
/**
* @author madhumita
*
*/
@Extension
public class SampleMenu implements NavigationMenu {
public String getContentsUrl() {
return "menu.zul";
}
public MenuType menuType() {
return MenuType.USER;
}
public float getPriority() {
return 0.8f;
}
}
|
Shell | UTF-8 | 454 | 2.90625 | 3 | [] | no_license | #!/bin/sh
# MARKETING_VERSION="1.0"
# VERSION=${MARKETING_VERSION}"."${BUILD_NUMBER}
#
# if [[ "$TRAVIS_EVENT_TYPE" = "cron" ]]; then
# if [[ "$DEV" = "IOS" ]]; then
# echo "Beta build - set version"
# VERSION="5.0.1"
# fi
#
# if [[ "$DEV" = "ANDROID" ]]; then
# echo "UAT build - set version"
# VERSION=${VERSION}".UAT"
# fi
# fi
#
# cd ios && xcrun agvtool new-version -all ${VERSION}
# echo "set version number to ${VERSION}"
|
JavaScript | UTF-8 | 6,844 | 2.734375 | 3 | [] | no_license | import React, { Component } from 'react';
import './Seat.css'
import axios from 'axios'
class Seat extends Component {
constructor(props) {
super(props)
this.state = {
// craeting an empty array of objects
totalSeats: [...new Array(this.props.totalSeats)].map((item, index) => {
return {
seatNo: index + 1,
selected: false
}
}),
choosenSeat: [],
userData: {},
busData: this.props.busData,
travalDate: this.props.travalDate,
taxAmmount:this.props.serviceTax
}
}
handleChange = (e) => {
let userData = this.state.userData
userData[e.target.name] = e.target.value
this.setState({ userData })
console.log(this.state.userData)
}
isBooked(seatNo) {
return this.props.bookedSeats.includes(seatNo)
}
handleSelect(seatNo) {
const muteState = { ...this.state }
if (!this.isBooked(seatNo)) {
muteState.totalSeats[seatNo - 1].selected = !muteState.totalSeats[seatNo - 1].selected;
if (muteState.totalSeats[seatNo - 1].selected) {
muteState.choosenSeat.push(seatNo);
}
else {
muteState.choosenSeat.pop(seatNo)
}
this.setState({ totalSeats: muteState.totalSeats, choosenSeat: muteState.choosenSeat })
console.log(this.state.choosenSeat)
}
}
renderFillDetails(choosenSeat) {
return choosenSeat.map((item, index) => {
if (choosenSeat.includes(item)) {
return (
<div className="card">
<div className="card-body">
<h1 className="list-group-item text-center" >SeatNumber:{item}</h1>
<div className="row">
<div className="col-6">
<h4 className="badge badge-danger">Fare Ammount</h4>₹{this.state.busData[0]['fare']} <br />
<h4 className="badge badge-danger">Tax</h4> ₹{this.state.taxAmmount} <br />
<h4 className="badge badge-danger">TotalFare</h4>₹{parseInt(this.state.busData[0]['fare']) + parseInt(this.state.taxAmmount)}
</div>
<div className="col-6">
<input type="email" name="email" className="form-control" placeholder="Enter Email Id" onChange={e => this.handleChange(e)} />
<input type="text" name="user" placeholder="Enter Name" className="form-control" onChange={e => this.handleChange(e)} />
</div>
</div>
</div>
</div>
)
}
})
}
updateDB = async (busId) => {
// updating bookedSeat in db
let bookedSeat = [...this.state.busData[0]['bookedSeats'].map(item => item.toString())].concat(this.state.choosenSeat.map(item => item.toString()))
// updating available avaliable seat
const Avaliable = {
routeId: busId,
avaliable: this.state.busData[0]['avaliable'] - this.state.choosenSeat.length
}
// API Call
await axios.post('http://localhost:5050/buses/update', Avaliable)
.then(res => console.log('update avaliable ', res.data))
.catch(err => console.log(err))
// updating bookedSeat in db
await axios.post('http://localhost:5050/buses/update/seat', { routeId: busId, bookedSeat })
.then(res => console.log('updated bookedSeat', res.data))
.catch(err => console.log(err))
{this.sendData(this.state.choosenSeat,this.state.ticketId)} // callback to parent about seat
}
sendData=(choosenSeat,ticketId)=>{
const nextPayment='true'
this.props.paraentCallback(choosenSeat,ticketId,nextPayment)
}
bookingData = async () => {
const book = {
user: this.state.userData.user,
email: this.state.userData.email,
travalDate: this.props.travalDate,
busId: this.state.busData[0]['routeId'],
from: this.state.busData[0]['from'],
to: this.state.busData[0]['to'],
seatNumber: this.state.choosenSeat[0],
totalAmmount: this.state.busData[0]['fare']*this.state.choosenSeat.length + this.state.taxAmmount*this.state.choosenSeat.length
}
console.log('this.is book data', book)
// post request for booking seat
let url = `http://localhost:5050/booking/book`
await axios.post(url, book)
.then(res => this.setState({ticketId:res.data.ticketId}))
.catch(err => console.log(err))
{ this.updateDB(book.busId) } // calling func to update db
}
render() {
return (
<div>
<div className="card-body bg-dark">
<ul className="seat">
{this.props.bookedSeats ? (this.state.totalSeats.map((item, index) => <li
onClick={() => this.handleSelect(item.seatNo)}
key={item.seatNo}
className={this.isBooked(item.seatNo) ? 'bookedSeat' : item.selected ? 'selectedSeat' : ''}>{item.seatNo}</li>)) : ''}
</ul>
<div className="bg-info text-center">
<div className="card-header">
<div className="show-info">
<div className="info-selected"></div><br />Selected
<div className="info-empty"></div> <br />Empty
<div className="info-occ"></div> <br />Occupied
</div>
</div>
</div>
</div>
<div className="mt-2">
<div className="card-header text-center"><h1 className="alert-info">Fill Booking Details</h1></div>
<div className="card-body">
{this.state.choosenSeat.length ? this.renderFillDetails(this.state.choosenSeat) : ''}
{this.state.choosenSeat.length ? (<a href='#'><button style={{ width: '150px' }} className='btn btn-primary btn btn-lg float-right form-control' onClick={() => this.bookingData()}>Book</button></a>) : ''}
</div>
</div>
</div>
);
}
}
export default Seat; |
Ruby | UTF-8 | 5,370 | 2.515625 | 3 | [
"MIT"
] | permissive | require "scale"
describe Scale::Types do
before(:all) {
Scale::TypeRegistry.instance.load
}
it "can create a hard coded type" do
type = Scale::Types.get("Compact")
expect(type).to eq(Scale::Types::Compact)
type = Scale::Types.get("Hex")
expect(type).to eq(Scale::Types::Hex)
end
# Vec
it "can create a Vec" do
type = Scale::Types.get("Vec<Compact>")
expect(type).to eq(Scale::Types::Vec_Compact_)
end
it "can encode and decode a vec" do
type = Scale::Types.get("Vec<Compact>")
scale_bytes = Scale::Bytes.new("0x081501fc")
obj = type.decode(scale_bytes)
expect(obj.value.length).to eq(2)
expect(obj.value).to eq([
Scale::Types::Compact.new(69),
Scale::Types::Compact.new(63)
])
expect(obj.encode).to eq("081501fc")
end
# Option
it "can create a Option" do
type = Scale::Types.get("Option<Compact>")
expect(type).to eq(Scale::Types::Option_Compact_)
end
it "can encode and decode a option" do
type = Scale::Types.get("Option<Compact>")
scale_bytes = Scale::Bytes.new("0x00")
obj = type.decode(scale_bytes)
expect(obj.value).to eq(nil)
scale_bytes = Scale::Bytes.new("0x011501")
obj = type.decode(scale_bytes)
expect(obj.value).to eq(Scale::Types::Compact.new(69))
expect(obj.encode).to eq("011501")
end
# Fixed array
it "can create a fixed array" do
type = Scale::Types.get("[Compact; 2]")
expect(type).to eq(Scale::Types::Array_Compact_2_)
expect(type.name).to eq("Scale::Types::Array_Compact_2_")
end
it "can encode and decode a fixed array" do
type = Scale::Types.get("[Compact; 2]")
scale_bytes = Scale::Bytes.new("0x1501fc")
obj = type.decode(scale_bytes)
expect(obj.value).to eq([
Scale::Types::Compact.new(69),
Scale::Types::Compact.new(63)
])
expect(obj.encode).to eq("1501fc")
end
# Tuple
it "can create a tuple" do
type = Scale::Types.get("(Compact, U32)")
expect(type).to eq(Scale::Types::Tuple_Compact_U32_)
end
it "can encode and decode a tuple" do
type = Scale::Types.get("(Compact, U16, U8)")
scale_bytes = Scale::Bytes.new("0x15012efb45")
obj = type.decode(scale_bytes)
expect(obj.value).to eq([
Scale::Types::Compact.new(69),
Scale::Types::U16.new(64302),
Scale::Types::U8.new(69)
])
expect(obj.encode).to eq("15012efb45")
end
# Struct
it "can get a struct and then use it to decode and encode " do
type_def = {
"type" => "struct",
"type_mapping" => [
[
"size",
"Compact"
],
[
"balance",
"U16"
],
[
"balance2",
"U8"
]
]
}
type = Scale::Types.get(type_def)
expect(type).to eq(Scale::Types::Struct_SizeInCompact_BalanceInU16_Balance2InU8_)
scale_bytes = Scale::Bytes.new("0x15012efb45")
obj = type.decode(scale_bytes)
expect(obj.value).to eq({
"size" => Scale::Types::Compact.new(69),
"balance" => Scale::Types::U16.new(64302),
"balance2" => Scale::Types::U8.new(69)
})
expect(obj.encode).to eq("15012efb45")
end
it "should be different of two struct with different labels but same inner types" do
type_def = {
"type" => "struct",
"type_mapping" => [
[
"size",
"Compact"
],
[
"balance",
"U16"
],
[
"balance2",
"U8"
]
]
}
type1 = Scale::Types.get(type_def)
type_def = {
"type" => "struct",
"type_mapping" => [
[
"abc",
"Compact"
],
[
"balance",
"U16"
],
[
"balance2",
"U8"
]
]
}
type2 = Scale::Types.get(type_def)
expect(type1).not_to eq(type2)
end
it "should be equal of two struct with the same structure" do
type_def = {
"type" => "struct",
"type_mapping" => [
[
"size",
"Compact"
],
[
"balance",
"U16"
],
[
"balance2",
"U8"
]
]
}
type1 = Scale::Types.get(type_def)
type_def = {
"type" => "struct",
"type_mapping" => [
[
"size",
"Compact"
],
[
"balance",
"U16"
],
[
"balance2",
"U8"
]
]
}
type2 = Scale::Types.get(type_def)
expect(type1).to eq(type2)
end
# Enum
it "can get a enum and then use it to decode and encode " do
type_def = {
"type" => "enum",
"type_mapping" => [
[
"RingBalance",
"Balance"
],
[
"KtonBalance",
"Balance"
]
]
}
type = Scale::Types.get(type_def)
expect(type).to eq(Scale::Types::Enum_RingBalanceInU128_KtonBalanceInU128_)
type_def = {
"type" => "enum",
"type_mapping" => [
[
"eth_abc",
"[U8; 20]"
],
[
"Tron",
"[U8; 20]"
]
]
}
type = Scale::Types.get(type_def)
expect(type).to eq(Scale::Types::Enum_EthAbcInArray_U8_20__TronInArray_U8_20__)
end
it "" do
end
end
|
PHP | UTF-8 | 3,418 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
//Este es una nueva forma de guardar la imagen
//Si el usuario no selecciona el archivo ya yo tengo uno por defecto
$nombreArchivo = 'user_default.jpg';
//Aquí les dejo una forma de guardar la imagen
$request = request();
//dd($request);
$imagen = $request->file('avatar');
//dd($imagen);
//Aquí atrapo creo el nombre de mi archivo con uniqid() y dispongo la extensión con la función extension()
$nombreArchivo = uniqid('img-') . '.' . $imagen->extension();
//Aquí guardo la imagen en el servidor carpeta store/public/avatars
$imagen->storePubliclyAs("public/avatars", $nombreArchivo);
//--------------------------------------------------
//Anteriormente como se hacia el mismo código Versión de Laravel 5.5
//dd($data);
// $nombreArchivo = 'user_default.jpg';
//debemos tener en cuenta que si hay un archivo, lo subimos y le guardamos la ruta
//if(isset($data['avatar'])){
//Al archivo que el usuario seleccione lo voy a guardar en el filesystem de laravel
//$rutaArchivo = $data['avatar']->store('public/avatars');
//Aquí es donde logro atrapar el nombre del archivo usando la función de PHP basename
//$nombreArchivo = basename($rutaArchivo);
//}
//--------------------------------------------------
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'provincia' => $data['provincia'],
'municipio' => $data['municipio'],
'password' => Hash::make($data['password']),
'avatar' => $nombreArchivo,
'role' => 1,
]);
}
}
|
PHP | UTF-8 | 3,039 | 2.625 | 3 | [] | no_license | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Tools extends CI_Controller {
private $sql_backup_params;
function __construct()
{
parent::__construct();
$this->sql_backup_params = array(
'tables' => array(), // Array of tables to backup.
'ignore' => array('historique','historique_tickets','system_sessions'), // List of tables to omit from the backup
'format' => 'gzip', // gzip, zip, txt
'filename' => 'ewatch_'.date("y-m-d").'.sql.gz', // File name - NEEDED ONLY WITH ZIP FILES
'add_drop' => FALSE, // Whether to add DROP TABLE statements to backup file
'add_insert' => TRUE, // Whether to add INSERT data to backup file
'newline' => "\n" // Newline character used in backup file
);
}
public function index()
{
$this->load->view('toolsview');
}
public function dump()
{
$this->backupDB(true);
}
public function upgrade()
{
//upgradable ?
if (!APP_UPGRADABLE) {echo 'UPGRADE DISABLED ON THIS SERVER !'; exit;}
//check if valid update submited
ini_set("memory_limit","1200M");
if (isset($_FILES["upgrade_file"]) and ($_FILES["upgrade_file"]['error'] === UPLOAD_ERR_OK) and (isset($_FILES["upgrade_file"]['name']))) {
$filename = $_FILES["upgrade_file"]["name"];
$source = $_FILES["upgrade_file"]["tmp_name"];
$target_path = "./upgrade/".$filename; // change this to the correct site path
$name = explode(".", $filename);
if (strtolower($name[1]) != 'a37') {
echo 'ERROR : Not a valid upgrade file'; exit;}
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
//perform a db backup before !
$this->backupDB();
//extract upgrade
$zip->extractTo("..");
$zip->close();
$message = "SUCCESS : Your upgrade was uploaded and installed successfully.";
}
else $message = "ERROR : Impossible to run upgrade..";
}
else $message = "ERROR : upload failed, check permission and try again..";
}
else $message = "ERROR : no file recieved, try again..";
echo $message;
exit;
}
private function backupDB($download=false,$filename=false)
{
if (!$filename) $filename = APP.'_'.date("y-m-d").'.sql.gz';
// Load the DB utility class
$this->load->dbutil();
// Backup your entire database and assign it to a variable
$backup =& $this->dbutil->backup($this->sql_backup_params);
// Load the file helper and write the file to your server
$this->load->helper('file');
write_file('./backup/'.$filename, $backup);
// Load the download helper and send the file to your desktop
if ($download)
{
$this->load->helper('download');
force_download($filename, $backup);
redirect('tools');
}
}
}
|
JavaScript | UTF-8 | 1,790 | 2.625 | 3 | [] | no_license | import { GET_ALL_ATTRIBUTES, SELECT_ATTRIBUTE, ADD_VALUE, REMOVE_VALUE } from '../actions/types';
export default function(
state = {
attributes: [],
selectedAttributeId: '',
},
action
) {
switch (action.type) {
case GET_ALL_ATTRIBUTES:
return {
...state,
attributes: action.payload,
};
case SELECT_ATTRIBUTE:
return {
...state,
selectedAttributeId: state.attributes.find(attribute => attribute.id === action.id).id,
};
case ADD_VALUE:
return {
...state,
attributes: state.attributes.map(attribute => {
if (attribute.id === action.payload.attributeId) {
const newValue = { id: action.payload.value.id, name: action.payload.value.name };
return {
...attribute,
values: [...attribute.values, newValue],
};
} else {
return attribute;
}
}),
};
case REMOVE_VALUE:
return {
...state,
attributes: state.attributes.map(attribute => {
if (attribute.id === action.payload.attributeId) {
return {
...attribute,
values: attribute.values.filter(value => value.id !== action.payload.value.id),
};
} else {
return attribute;
}
}),
};
default:
return state;
}
}
|
PHP | UTF-8 | 1,985 | 2.765625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
/**
* @author Amidasd
* @copyright 2014
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Crud extends CI_Model
{
var $table = ''; //Имя таблиці
var $idkey = ''; //Ключ ID
var $add_rules = array(); //Правила валидации для добавления
var $edit_rules = array(); //Правила валидации для редактирования
//Конструктор
function __construct()
{
parent::__construct();
}
function get($id)
{
$this->db->where($this->idkey, $id);
if (!empty($this->sel)) {
$this->db->select($this->sel);
}
$query = $this->db->get($this->table);
return $query->row_array();
}
function add()
{
$this->form_validation->set_data($_POST);
$this->form_validation->set_rules($this->add_rules);
if ($this->form_validation->run()) {
$data = array();
foreach ($this->add_rules as $one) {
$f = $one['field'];
$data[$f] = $this->input->post($f);
}
$this->db->insert($this->table, $data);
return $this->db->insert_id(); //возвращает номер добавленного поля
} else {
return false;
}
}
/**
* Функция для редактирования
*/
function edit($id)
{
$this->form_validation->set_rules($this->edit_rules);
if ($this->form_validation->run()) {
$data = array();
foreach ($this->edit_rules as $one) {
$f = $one['field'];
$data[$f] = $this->input->post($f);
}
$this->db->where($this->idkey, $id);
$this->db->update($this->table, $data);
return true; // Возвращает истинно
} else {
return false;
}
}
}
|
Shell | UTF-8 | 1,503 | 3.328125 | 3 | [] | no_license | #!/bin/bash
#set variables
read -p "Enter the name for the NIC adapter " nic
read -p "Enter the name for the WiFi adapter " wifi
read -p "Enter the WiFi password: " wifipass
#install unzip and wpa_supplicant, start and enable wpa_supplicant
apt install unzip wpasupplicant lm-sensors -y
systemctl start wpa_supplicant
systemctl enable wpa_supplicant
#change settings so laptop lid does not turn off or sleep laptop
sed -i 's/#HandleLidSwitch=suspend/HandleLidSwitch=ignore/' /etc/systemd/logind.conf
sed -i 's/#HandleLidSwitchExternalPower=suspend/HandleLidSitchExternalPower=ignore/' /etc/systemd/logind.conf
sed -i 's/#HandleLidSwitchDocked=ignore/HandleLidSwitchDocked=ignore/' /etc/systemd/logind.conf
#add line to sshd conf for root login
sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
#remove all of cloud-init
echo 'datasource_list: [ None ]' | sudo -s tee /etc/cloud/cloud.cfg.d/90_dpkg.cfg
apt purge cloud-init -y
rm -rf /etc/cloud/ && rm -rf /var/lib/cloud/
#backup netplan file and create new one with correct network data
mv /etc/netplan/00-installer-config.yaml /etc/netplan/00-installer-config.yaml.bak
#create new netplan file
cat > /etc/netplan/00-installer-config.yaml <<EOF
network:
version: 2
ethernets:
$nic:
dhcp4: true
optional: true
wifis:
$wifi:
dhcp4: true
optional: true
access-points:
"green":
password: "$wifipass"
EOF
sudo netplan apply
#reboot system
reboot now
|
Java | UTF-8 | 9,694 | 2.234375 | 2 | [] | no_license | package lambda_test;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 任务表
*
* @author liyuzhen
* @version 1.0
* @date 2019-08-06 14:37
*/
@Data
@Builder
@ApiModel
public class Task {
@ApiModelProperty("任务id")
private String taskId;
@ApiModelProperty("用户id")
private String userId;
@ApiModelProperty("状态:0,为完成;1,已完成")
private Integer status;
public static List<Task> getTaskList() {
List<Task> taskList = new ArrayList<>();
taskList.add(Task.builder().taskId("6fa88c6d-5bea-487c-a302-ca3e27c53a02").userId("b60dba9e-5f5d-4a56-a841-25d054fd334b").status(1).build());
taskList.add(Task.builder().taskId("3ed30535-3b17-4e97-9936-eaf459a9a787").userId("b60dba9e-5f5d-4a56-a841-25d054fd334b").status(0).build());
taskList.add(Task.builder().taskId("1780c8fc-2381-426d-8814-73d8ec341744").userId("b60dba9e-5f5d-4a56-a841-25d054fd334b").status(0).build());
taskList.add(Task.builder().taskId("522e7984-191f-4dc2-b064-57d7d200f2e2").userId("b60dba9e-5f5d-4a56-a841-25d054fd334b").status(1).build());
taskList.add(Task.builder().taskId("8d8ac82b-0e1c-4e96-8ae1-dc68cf311804").userId("b60dba9e-5f5d-4a56-a841-25d054fd334b").status(0).build());
taskList.add(Task.builder().taskId("5e3ffb0e-6a15-4865-95b9-c3dd3c09f831").userId("b60dba9e-5f5d-4a56-a841-25d054fd334b").status(0).build());
taskList.add(Task.builder().taskId("d8d4bfec-74b3-4510-adaa-42f567d9cc70").userId("132ebbc0-838d-40ea-ad14-36c68eb403c0").status(1).build());
taskList.add(Task.builder().taskId("de131441-da18-4ccb-aef8-704b10719ab8").userId("132ebbc0-838d-40ea-ad14-36c68eb403c0").status(0).build());
taskList.add(Task.builder().taskId("3834fdd5-c21c-44e1-8d57-04f35ab7d6d3").userId("132ebbc0-838d-40ea-ad14-36c68eb403c0").status(1).build());
taskList.add(Task.builder().taskId("9fc4f28b-ac27-4654-a603-70f655b0dabb").userId("132ebbc0-838d-40ea-ad14-36c68eb403c0").status(1).build());
taskList.add(Task.builder().taskId("55e246d5-716b-4e60-a386-95f1ab18d2cc").userId("132ebbc0-838d-40ea-ad14-36c68eb403c0").status(1).build());
taskList.add(Task.builder().taskId("052e0ae6-dc87-4de7-b72e-3bcfc2f77bd1").userId("132ebbc0-838d-40ea-ad14-36c68eb403c0").status(1).build());
taskList.add(Task.builder().taskId("9b8fce25-8641-4c69-ae7f-13950ecf0f6a").userId("5260c4cf-04dd-411a-8785-4894406cf5d3").status(1).build());
taskList.add(Task.builder().taskId("d68ac6bb-bf9f-4d49-b367-ed518f60e43c").userId("5260c4cf-04dd-411a-8785-4894406cf5d3").status(1).build());
taskList.add(Task.builder().taskId("daa204f4-1310-4a48-8f24-e75cdd270e02").userId("5260c4cf-04dd-411a-8785-4894406cf5d3").status(0).build());
taskList.add(Task.builder().taskId("a474956a-5fc3-4982-9ff4-c0fe97fd1e28").userId("5260c4cf-04dd-411a-8785-4894406cf5d3").status(0).build());
taskList.add(Task.builder().taskId("565715f8-c95c-4a1a-8b25-e89b1704fc96").userId("5260c4cf-04dd-411a-8785-4894406cf5d3").status(1).build());
taskList.add(Task.builder().taskId("5462dd27-3d59-4d04-9f01-accbe1a35287").userId("5260c4cf-04dd-411a-8785-4894406cf5d3").status(0).build());
taskList.add(Task.builder().taskId("53b14bc9-6d0d-47b3-930a-68fc25f68a82").userId("a1f3478d-fe61-4e4b-95c6-acdf6254a9fb").status(1).build());
taskList.add(Task.builder().taskId("ef7cf03c-f8f6-46a3-8bfb-405f2ea2097f").userId("a1f3478d-fe61-4e4b-95c6-acdf6254a9fb").status(0).build());
taskList.add(Task.builder().taskId("2a70d404-8bb1-411c-a7f1-567d82cfa04d").userId("a1f3478d-fe61-4e4b-95c6-acdf6254a9fb").status(1).build());
taskList.add(Task.builder().taskId("b4cb8064-e7cf-42b3-8843-7081fa4f6954").userId("a1f3478d-fe61-4e4b-95c6-acdf6254a9fb").status(1).build());
taskList.add(Task.builder().taskId("d4e688a6-5d38-4bbb-b34d-751bab3c94cd").userId("a1f3478d-fe61-4e4b-95c6-acdf6254a9fb").status(1).build());
taskList.add(Task.builder().taskId("836be91b-8bd2-40cc-8cc3-a1184b0c0e32").userId("a1f3478d-fe61-4e4b-95c6-acdf6254a9fb").status(0).build());
taskList.add(Task.builder().taskId("a0adc44b-9610-4dd9-b8c7-eb4e0d818eab").userId("948ca9c4-d015-4baf-b65b-d5dd3fb7b542").status(0).build());
taskList.add(Task.builder().taskId("890d1fa1-a624-4a85-b082-b696d3e790d8").userId("948ca9c4-d015-4baf-b65b-d5dd3fb7b542").status(0).build());
taskList.add(Task.builder().taskId("ce1c56d3-174e-44a9-a4bb-4a441e1bd224").userId("948ca9c4-d015-4baf-b65b-d5dd3fb7b542").status(0).build());
taskList.add(Task.builder().taskId("5860afc3-0ce4-4fc6-8d99-e8daddb770ad").userId("948ca9c4-d015-4baf-b65b-d5dd3fb7b542").status(1).build());
taskList.add(Task.builder().taskId("2e72f7d2-abb4-4044-9eca-829a29f3c8ac").userId("948ca9c4-d015-4baf-b65b-d5dd3fb7b542").status(1).build());
taskList.add(Task.builder().taskId("56f8e07e-8453-4d1b-b44f-e2dfd5d24967").userId("948ca9c4-d015-4baf-b65b-d5dd3fb7b542").status(0).build());
taskList.add(Task.builder().taskId("1a8729ff-1619-4410-ad4d-5bd796253aba").userId("7b95787e-167c-4ac4-9a56-c9e55fbb2c3b").status(1).build());
taskList.add(Task.builder().taskId("b6f4051b-c7e6-4271-a181-9fde81079f29").userId("7b95787e-167c-4ac4-9a56-c9e55fbb2c3b").status(1).build());
taskList.add(Task.builder().taskId("75457bb5-0347-4069-b94d-7149cca014a6").userId("7b95787e-167c-4ac4-9a56-c9e55fbb2c3b").status(1).build());
taskList.add(Task.builder().taskId("f17bb92a-6a31-4ed9-a75f-b9200e821cfa").userId("7b95787e-167c-4ac4-9a56-c9e55fbb2c3b").status(1).build());
taskList.add(Task.builder().taskId("ddedabad-d585-4cdc-8dc4-347883d5794c").userId("7b95787e-167c-4ac4-9a56-c9e55fbb2c3b").status(0).build());
taskList.add(Task.builder().taskId("6759ce8a-2970-452e-afbe-e52faddb579e").userId("7b95787e-167c-4ac4-9a56-c9e55fbb2c3b").status(1).build());
taskList.add(Task.builder().taskId("fcf93dc9-2545-40c9-b5bc-f01f55f6ffb6").userId("89989bd5-f335-4c55-92d5-f6c1f4593592").status(1).build());
taskList.add(Task.builder().taskId("d8b5a91f-6e17-43cc-b2b5-049fc3d2ff3f").userId("89989bd5-f335-4c55-92d5-f6c1f4593592").status(1).build());
taskList.add(Task.builder().taskId("aca50726-ef0a-49b5-baa5-7153ab26b3d9").userId("89989bd5-f335-4c55-92d5-f6c1f4593592").status(0).build());
taskList.add(Task.builder().taskId("f397d3b9-6cfe-4bc6-8366-87e6e4a49c55").userId("89989bd5-f335-4c55-92d5-f6c1f4593592").status(0).build());
taskList.add(Task.builder().taskId("3a086b20-2d33-4400-b639-d45c0f6f3fa2").userId("89989bd5-f335-4c55-92d5-f6c1f4593592").status(1).build());
taskList.add(Task.builder().taskId("bd9e216f-1724-4bd6-a2fd-74afffe9d33a").userId("89989bd5-f335-4c55-92d5-f6c1f4593592").status(1).build());
taskList.add(Task.builder().taskId("b0871264-efb6-4bd5-9fbc-ca5bfbdc0c75").userId("b02fbf2d-b60e-4b06-bbea-4a7d7264d9db").status(0).build());
taskList.add(Task.builder().taskId("5bfe2906-c2d1-4995-bb82-8d7d177de16f").userId("b02fbf2d-b60e-4b06-bbea-4a7d7264d9db").status(0).build());
taskList.add(Task.builder().taskId("e9ad6f7b-42f4-44a8-8ae4-878e5ea71929").userId("b02fbf2d-b60e-4b06-bbea-4a7d7264d9db").status(0).build());
taskList.add(Task.builder().taskId("5a84c7c9-a61e-4577-a167-d8736e7eef41").userId("b02fbf2d-b60e-4b06-bbea-4a7d7264d9db").status(0).build());
taskList.add(Task.builder().taskId("91c91aab-3a78-4b6b-ac16-0274a737a139").userId("b02fbf2d-b60e-4b06-bbea-4a7d7264d9db").status(0).build());
taskList.add(Task.builder().taskId("85073970-eb31-4478-b7fb-924e3e5749aa").userId("b02fbf2d-b60e-4b06-bbea-4a7d7264d9db").status(1).build());
taskList.add(Task.builder().taskId("34fbc9a0-1881-4c1e-ba54-a72d6101827e").userId("f6239b01-1d2f-4197-a197-d9d139c7fe08").status(0).build());
taskList.add(Task.builder().taskId("5b2f1cb9-b227-4d11-9c8f-e6c05d911ac0").userId("f6239b01-1d2f-4197-a197-d9d139c7fe08").status(1).build());
taskList.add(Task.builder().taskId("64cb32fb-3dc5-42c1-aeaf-79ff924ee0ee").userId("f6239b01-1d2f-4197-a197-d9d139c7fe08").status(1).build());
taskList.add(Task.builder().taskId("d4e6f049-1b13-4335-b49c-d7a93d6793a0").userId("f6239b01-1d2f-4197-a197-d9d139c7fe08").status(0).build());
taskList.add(Task.builder().taskId("2dbd2257-9c65-4e3a-81ae-d59b36cbf3e1").userId("f6239b01-1d2f-4197-a197-d9d139c7fe08").status(0).build());
taskList.add(Task.builder().taskId("7e3d6176-2faa-4547-86cb-e48a1caaf637").userId("f6239b01-1d2f-4197-a197-d9d139c7fe08").status(1).build());
taskList.add(Task.builder().taskId("16d84392-0d75-4eb1-8650-5bd34c607129").userId("d33c9ea4-cd6f-4596-a6c6-0e5c0b9a68ed").status(1).build());
taskList.add(Task.builder().taskId("cacc2213-67cc-40e1-95e7-416363241949").userId("d33c9ea4-cd6f-4596-a6c6-0e5c0b9a68ed").status(0).build());
taskList.add(Task.builder().taskId("4c538677-eb52-4344-9847-ab18eabe89e4").userId("d33c9ea4-cd6f-4596-a6c6-0e5c0b9a68ed").status(1).build());
taskList.add(Task.builder().taskId("72098a6d-c2bf-4226-9c29-cf3401b55fed").userId("d33c9ea4-cd6f-4596-a6c6-0e5c0b9a68ed").status(0).build());
taskList.add(Task.builder().taskId("fbc1a30a-6165-48e7-a3c0-52c5f223480d").userId("d33c9ea4-cd6f-4596-a6c6-0e5c0b9a68ed").status(1).build());
taskList.add(Task.builder().taskId("589da8a2-857f-497d-b55f-52c9fffb026c").userId("d33c9ea4-cd6f-4596-a6c6-0e5c0b9a68ed").status(1).build());
return taskList;
}
}
|
Markdown | UTF-8 | 1,917 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | # V1StatusDetails
StatusDetails is a set of additional properties that MAY be set by the server to provide additional information about a response. The Reason field of a Status object defines what attributes will be set. Clients must ignore fields that do not match the defined type of each attribute, and should assume that any attribute may be empty, invalid, or under defined.
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**causes** | [**list[V1StatusCause]**](V1StatusCause.md) | The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. | [optional]
**group** | **str** | The group attribute of the resource associated with the status StatusReason. | [optional]
**kind** | **str** | The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | [optional]
**name** | **str** | The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). | [optional]
**retry_after_seconds** | **int** | If specified, the time in seconds before the operation should be retried. Some errors may indicate the kubernetes.client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. | [optional]
**uid** | **str** | UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
PHP | UTF-8 | 2,779 | 3.59375 | 4 | [] | no_license | <?php
echo '<p>Лабораторная работа №5, часть 1(практикум)</p>';
// Переменные различных типов
$Boolean = true;
$Integer = 10;
$Float = 0.001;
$String = 'Text';
$a = 5;
$b = 5;
$c = $a + $b;
echo "<p>a = 5, b = 5, a + b = $c<p>";
$a = ($b = 4) + 5;
echo "<p> a = (b = 4) + 5 = $a</p>";
$String = 't';
$String .= 'he';
echo "<p>Операции со строками $String</p>";
define('TEST', 123);
echo "<p>TEST</p>";
//Условные операторы
// if
$a = 1;
$b = 6;
echo "Условный оператор if: ";
if($a === $b) echo 'A равно Б </p>';
elseif ($b == 6) echo 'Б = 6</p>';
else echo 'A не равно Б</p>';
// switch case
$test = 40;
echo "Условный оператор switch case: ";
switch($test){
case 30:
echo "30";
break;
case 10:
echo "10";
break;
default:
echo "Все нормально";
break;
}
echo '<p></p>';
// Массивы
echo "Операции с массивами: ";
$Array[0] = 'Кобра';
$Array[1] = 'Питон';
$Array[2] = 'Гадюка';
echo "<p>$Array[0]</p>";
$Array = array('Фрукт1' => 'Апельсин', 'Фрукт2' => 'Лимон', 'Фрукт3' => 'Яблоко');
unset($Array['Фрукт2']);
var_dump($Array);
echo '<p></p>';
$Array['Человек'] = array('имя' => 'Вася');
echo $Array['Человек']['имя'];
echo '<p></p>';
// Циклы
//while
$i = 1;
echo "Цикл while:";
while ($i <= 10) {
echo "$i";
$i++;
}
echo '<p></p>';
//dowhile
$i = 1;
echo "Цикл do while:";
do {
echo "$i";
$i++;
} while ($i <= 5);
echo '<p></p>';
//for
echo "Цикл for:";
for ($x=0; $x<10; $x++) {
if ($x == 5) continue;
echo $x;
}
echo '<p></p>';
//foreach
echo "Цикл foreach:";
$capitals["Россия"] = "Москва";
$capitals["Украина"] = "Киев";
$capitals["Беларусь"] = "Минск";
$capitals["Казахстан"] = "Астана";
foreach ($capitals as $key => $value) {
echo "<p>$value - $key</p>";
}
echo '<p></p>';
// Пользовательские функции
echo "Пользовательские функции: ";
function Test1($pl = '.') {
echo "Привет$pl";
}
Test1('!');
function Test2() {
return true;
}
if (Test2()) echo '123';
$a = 100;
function Test3() {
global $a;
if ($a == 100) return true;
else return false;
}
if (Test3()) echo '123';
echo '<p></p>';
// Сессия
session_start();
$_SESSION['Язык'] = 'PHP';
$_SESSION['Я'] = 'Человек';
unset($_SESSION['Я']);
echo $_SESSION['Язык'];
?> |
Python | UTF-8 | 5,845 | 4.03125 | 4 | [] | no_license | """
Author: Patrick Sullivan
A class to support the members of a family tree
"""
class Person:
def __init__(self, name, parent1, parent2):
"""
A constructor for the Person class. If the person has no parents,
the parent arguments should be None.
:param name: String
:param parent1: Person
:param parent2: Person
"""
self.name = name # String
self.spouses = list() # List of Strings
self.parent1 = parent1 # Person
self.parent2 = parent2 # Person
self.children = list() # List of Strings
def get_name(self):
return self.name
def get_spouses(self):
return self.spouses
def get_parent1(self):
return self.parent1
def get_parent2(self):
return self.parent2
def get_children(self):
return self.children
def set_name(self, name):
self.name = name
def add_spouse(self, spouse):
self.spouses.append(spouse.get_name())
self.spouses.sort()
def set_parent1(self, parent):
self.parent1 = parent
def set_parent2(self, parent):
self.parent2 = parent
def add_child(self, child):
self.children.append(child.get_name())
self.children.sort()
def get_ancestors(self):
"""
Recurse through the parents of the person, and gather the list
of direct ancestors.
:return: A list of strings of ancestors' names.
"""
ancestors = list()
if self.parent1 is None or self.parent2 is None:
return ancestors
else:
ancestors.append(self.parent1.get_name())
ancestors.append(self.parent2.get_name())
for person in self.parent1.get_ancestors():
ancestors.append(person)
for person in self.parent2.get_ancestors():
ancestors.append(person)
ancestors.sort()
return ancestors
def get_siblings(self):
"""
Gather the list of children for each parent, and add them to a list of
siblings for the current person. Removes the person themselves from the list.
:return: A list of strings of siblings' names.
"""
siblings = list()
if self.parent1 is not None:
for child in self.parent1.get_children():
siblings.append(child)
if self.parent2 is not None:
for child in self.parent2.get_children():
if child not in siblings:
siblings.append(child)
siblings.remove(self.name)
siblings.sort()
return siblings
def is_child(self, person2):
"""
Check if this person is a direct child of the given person
:param person2: Person
:return: Boolean
"""
if self.parent1 is None or self.parent2 is None:
return False
return self.parent1.equals(person2) or self.parent2.equals(person2)
def is_spouse(self, person2):
"""
Check if this person is the spouse of the given person,
including ex-spouses
:param person2: Person
:return: Boolean
"""
return person2.get_name() in self.spouses
def is_sibling(self, person2):
"""
Check if this person is a sibling of the given person,
including half-siblings
:param person2: Person
:return: Boolean
"""
if self.equals(person2):
return False
elif person2.get_parent1() is None or person2.get_parent2() is None:
return False
elif self.parent1 is not None \
and (self.parent1.equals(person2.get_parent1())
or self.parent1.equals(person2.get_parent2())):
return True
elif self.parent2 is not None \
and (self.parent2.equals(person2.get_parent1())
or self.parent2.equals(person2.get_parent2())):
return True
else:
return False
def is_ancestor(self, person2):
"""
Check if this person is the ancestor of the given person
:param person2: Person
:return: Boolean
"""
return self.name in person2.get_ancestors()
def is_cousin(self, person2):
"""
Check if this person and the given person share a common ancestor
but are not direct ancestors
:param person2: Person
:return: Boolean
"""
if self.equals(person2):
return False
elif self.is_child(person2) or person2.is_child(self):
return False
else:
ancestors1 = self.get_ancestors()
ancestors2 = person2.get_ancestors()
if person2.get_name() in ancestors1 or self.name in ancestors2:
return False
for anc in ancestors1:
if anc in ancestors2:
return True
return False
def is_unrelated(self, person2):
"""
Check if this person and the given person are not related at all.
:param person2: Person
:return: Boolean
"""
if self.equals(person2):
return True
elif self.is_child(person2) or person2.is_child(self):
return False
elif self.is_sibling(person2):
return False
elif self.is_cousin(person2):
return False
elif self.is_ancestor(person2) or person2.is_ancestor(self):
return False
else:
return True
def equals(self, person2):
"""
If this person and the given person share a name, they are considered equal.
:param person2: Person
:return: Boolean
"""
return self.name == person2.get_name()
|
Python | UTF-8 | 1,676 | 3.1875 | 3 | [] | no_license | import math
import numpy as np
from prettytable import PrettyTable
def euclidean_distance(coord1,coord2):
x_dist = math.pow((coord1[0] - coord2[0]),2)
y_dist = math.pow((coord1[1] - coord2[1]),2)
return math.sqrt(x_dist + y_dist)
def make_same_len(c,d):
l = max(len(c),len(d))
if(len(c) < l):
c = c.zfill(l)
else:
d = d.zfill(l)
return c,d
def prefix_match(a,b):
c = str(hex(a))[2:]
d = str(hex(b))[2:]
c,d = make_same_len(c,d)
count = 0
for i in range(len(c)):
if c[i] != d[i]:
break
else:
count+=1
return count-1
def get_digit_at(number, n):
a = str(hex(number))[2:]
return int(a[n],16)
def compare_tables(table_1 = [],table_2 = [], node = None):
for i in range(len(table_2)):
for j in range(len(table_2[i])):
if table_2[i][j] is not None and table_2[i][j] != node.ide:
if table_1[i][j] is None:
table_1[i][j] = table_2[i][j]
else:
val = abs(node.ide - table_1[i][j]) < abs(node.ide - table_2[i][j])
if not val:
table_1[i][j] = table_2[i][j]
return table_1
def insort(l,node):
i = 0
while i<len(l) and node.ide > l[i].ide:
i+=1
l.insert(i,node)
return l
def print_list(l=[],id=0,name=""):
print("Printing the " + name + " of the node with id "+ str(id))
p = [i.ide for i in l]
print(p)
def print_table(t = [], id = 0, name =""):
print("Printing the " + name + " of the node with id "+ str(id))
p = PrettyTable()
for i in t:
p.add_row(i)
print(p) |
Python | UTF-8 | 1,412 | 4.1875 | 4 | [] | no_license | # Problem: https://www.hackerrank.com/challenges/between-two-sets
# Solved by: Edgardo (Elijah) Gutierrez
# Date: 2/24/17
# Algorithm
# 1) Find smallest element of 16, this is the upper bound to possible x.
# 2) For all possible values of x, find the valid conditions.
# 3) Increment counter when valid value of x is found.
def main():
# Get input
ab = [int(x) for x in raw_input().split(" ")] # Get list lengths.
A = [int(x) for x in raw_input().split(" ")] # Get 'A' list elements.
B = [int(x) for x in raw_input().split(" ")] # Get 'B' list elements.
# General instantiations.
counter = 0
smallest = 100
# Find smallest element in B list.
for b in B:
if (smallest > b):
smallest = b
# Loop through all possible values of x in the range [1 - b].
for x in range(1, smallest + 1):
bFactor = True
# Loop through all values of B to confirm x is a factor of b.
for b in B:
if (b % x != 0):
bFactor = False
if (bFactor):
aFactor = True
# Loop through all values of A to confirm a is a factor of x.
for a in A:
if (x % a != 0):
aFactor = False
# a is a factor of x and x is a factor of b.
if (aFactor):
counter += 1
print(counter)
if __name__ == "__main__":
main()
|
Shell | UTF-8 | 343 | 3.71875 | 4 | [] | no_license | #!/bin/sh
# Usage: $0 [grep args]
curtrack(){
mpc | head -1
}
playing(){
curtrack | grep "$@" > /dev/null
return $?
}
sleep_on_mpd(){
mpc idle player >/dev/null
}
if test $# -eq 0
then
now=`curtrack`
if test -n "$now"
then
while playing -F "$now"
do sleep_on_mpd
done
fi
else
while ! playing "$@"
do sleep_on_mpd
done
fi
|
Java | UTF-8 | 1,315 | 3.25 | 3 | [] | no_license | package de.emeraldmc.chatsystem;
public class ChatMessageQueue {
private static final int size = 10; // Main.getInstance().getConfig().getInt("Config.messageCheckSize");
private ChatMessageLight[] chatMessages = new ChatMessageLight[size];
private int head = 0;
private int tail = 0;
public ChatMessageQueue() {
}
/**
* Removes the last entry (fifo = first in first out)
*/
private void removeLast() {
head = (head + 1) % size;
}
/**
* Puts a new Object at the end of the queue
* @param message the object to put in the queue
*/
public void put(ChatMessageLight message) {
boolean overflow = (tail + 1) % size == head;
if (overflow) removeLast();
chatMessages[tail] = message;
tail = (tail + 1) % size;
}
/**
* Get the first element of the queue
* @return the first element of the queue
* @throws IndexOutOfBoundsException
*/
public ChatMessageLight getFirst() throws IndexOutOfBoundsException {
if (tail == 0) return chatMessages[size-1];
return chatMessages[tail-1];
}
/**
* Get the ChatCommands array
* @return the ChatCommands array
*/
public ChatMessageLight[] getChatMessages() {
return chatMessages;
}
}
|
Python | UTF-8 | 281 | 3.390625 | 3 | [] | no_license | n = 100
a = []
for i in range(0, n+1): a.append(True)
for i in range(2, n+1):
if i*i > n:
break
if a[i]:
j = i*i
while j < n+1:
a[j] = False
j = j + i
for i in range(2, n + 1):
if a[i]:
print(i) |
Markdown | UTF-8 | 14,585 | 2.734375 | 3 | [
"MIT"
] | permissive | MovieLens 1M Dataset
================
Roberto Preste
2019-01-13
From the book (chapter 14.2):
> [GroupLens Research](http://www.grouplens.org/node/73) provides a number of collections of movie ratings data collected from users of MovieLens in the late 1990s and early 2000s. The data provide movie ratings, movie metadata (genres and year), and demographic data about the users (age, zip code, gender identification, and occupation). \[...\] The MovieLens 1M dataset contains 1 million ratings collected from 6,000 users on 4,000 movies.
------------------------------------------------------------------------
``` r
library(tidyverse)
library(magrittr)
```
------------------------------------------------------------------------
Loading the data
----------------
This dataset is split over 3 files, containing different information. The `movies` dataset contains movies information, the `users` dataset contains voting users information and the `ratings` dataset contains movie ratings.
To my knowledge, no `R` package is capable of reading a file with double characters as column delimiter, as is in this case, where each column in the files is delimited using `::`. For this reason, we are first going to read in the entire raw files, replace occurrences of `::` with `_`, and then parse the datasets using a classic `read_delim`. Any other delimiter can be used instead of `_`, as long as it is not already present in the file (otherwise you will have issues when trying to load the data).
``` r
users <- read_file("../datasets/movielens/users.dat") %>%
str_replace_all("::", "_") %>%
read_delim(delim = "_", col_names = c("user_id", "gender", "age", "occupation", "zip"))
ratings <- read_file("../datasets/movielens/ratings.dat") %>%
str_replace_all("::", "_") %>%
read_delim(delim = "_", col_names = c("user_id", "movie_id", "rating", "timestamp"))
movies <- read_file("../datasets/movielens/movies.dat") %>%
str_replace_all("::", "_") %>%
read_delim(delim = "_", col_names = c("movie_id", "title", "genres"))
```
In order to access these data easily, we will merge them into a single dataframe instead of having data spread across 3 different tables.
``` r
mov_data <- ratings %>%
full_join(users, by = "user_id") %>%
full_join(movies, by = "movie_id")
```
``` r
mov_data
```
## # A tibble: 1,000,386 x 10
## user_id movie_id rating timestamp gender age occupation zip title
## <int> <int> <int> <int> <chr> <int> <int> <chr> <chr>
## 1 1 1193 5 978300760 F 1 10 48067 One …
## 2 1 661 3 978302109 F 1 10 48067 Jame…
## 3 1 914 3 978301968 F 1 10 48067 My F…
## 4 1 3408 4 978300275 F 1 10 48067 Erin…
## 5 1 2355 5 978824291 F 1 10 48067 Bug'…
## 6 1 1197 3 978302268 F 1 10 48067 Prin…
## 7 1 1287 5 978302039 F 1 10 48067 Ben-…
## 8 1 2804 5 978300719 F 1 10 48067 Chri…
## 9 1 594 4 978302268 F 1 10 48067 Snow…
## 10 1 919 4 978301368 F 1 10 48067 Wiza…
## # ... with 1,000,376 more rows, and 1 more variable: genres <chr>
Let's check the average rating for each movie grouped by gender of voting users.
``` r
mean_ratings <- mov_data %>%
group_by(title, gender) %>%
summarise(mean_rating = mean(rating)) %>%
spread(gender, mean_rating, fill = 0) %>%
select(-`<NA>`)
```
``` r
mean_ratings
```
## # A tibble: 3,883 x 3
## # Groups: title [3,883]
## title F M
## <chr> <dbl> <dbl>
## 1 ...And Justice for All (1979) 3.83 3.69
## 2 'burbs, The (1989) 2.79 2.96
## 3 'Night Mother (1986) 3.39 3.35
## 4 'Til There Was You (1997) 2.68 2.73
## 5 $1,000,000 Duck (1971) 3.38 2.76
## 6 1-900 (1994) 2 3
## 7 10 Things I Hate About You (1999) 3.65 3.31
## 8 101 Dalmatians (1961) 3.79 3.5
## 9 101 Dalmatians (1996) 3.24 2.91
## 10 12 Angry Men (1957) 4.18 4.33
## # ... with 3,873 more rows
We may want to filter this dataframe to keep only movies that were rated by at least 250 users. So let's get the total number of users that rated each movie.
``` r
ratings_by_title <- mov_data %>%
group_by(title) %>%
summarise(voting_users = n())
```
``` r
ratings_by_title
```
## # A tibble: 3,883 x 2
## title voting_users
## <chr> <int>
## 1 ...And Justice for All (1979) 199
## 2 'burbs, The (1989) 303
## 3 'Night Mother (1986) 70
## 4 'Til There Was You (1997) 52
## 5 $1,000,000 Duck (1971) 37
## 6 1-900 (1994) 2
## 7 10 Things I Hate About You (1999) 700
## 8 101 Dalmatians (1961) 565
## 9 101 Dalmatians (1996) 364
## 10 12 Angry Men (1957) 616
## # ... with 3,873 more rows
``` r
active_titles <- ratings_by_title %>%
filter(voting_users >= 250)
```
``` r
active_titles
```
## # A tibble: 1,216 x 2
## title voting_users
## <chr> <int>
## 1 'burbs, The (1989) 303
## 2 10 Things I Hate About You (1999) 700
## 3 101 Dalmatians (1961) 565
## 4 101 Dalmatians (1996) 364
## 5 12 Angry Men (1957) 616
## 6 13th Warrior, The (1999) 750
## 7 2 Days in the Valley (1996) 286
## 8 20,000 Leagues Under the Sea (1954) 575
## 9 2001: A Space Odyssey (1968) 1716
## 10 2010 (1984) 470
## # ... with 1,206 more rows
Now we can get the mean rating for this new subset of movies.
``` r
active_mean_ratings <- mean_ratings %>%
filter(title %in% active_titles$title)
```
Let's view the top rated movies across men and women voters.
``` r
top_male_ratings <- active_mean_ratings %>%
arrange(desc(M))
```
``` r
top_male_ratings[1:10, ]
```
## # A tibble: 10 x 3
## # Groups: title [10]
## title F M
## <chr> <dbl> <dbl>
## 1 Godfather, The (1972) 4.31 4.58
## 2 Seven Samurai (The Magnificent Seven) (Shichinin no samura… 4.48 4.58
## 3 Shawshank Redemption, The (1994) 4.54 4.56
## 4 Raiders of the Lost Ark (1981) 4.33 4.52
## 5 Usual Suspects, The (1995) 4.51 4.52
## 6 Star Wars: Episode IV - A New Hope (1977) 4.30 4.50
## 7 Schindler's List (1993) 4.56 4.49
## 8 Wrong Trousers, The (1993) 4.59 4.48
## 9 Close Shave, A (1995) 4.64 4.47
## 10 Rear Window (1954) 4.48 4.47
``` r
top_female_ratings <- active_mean_ratings %>%
arrange(desc(F))
```
``` r
top_female_ratings[1:10, ]
```
## # A tibble: 10 x 3
## # Groups: title [10]
## title F M
## <chr> <dbl> <dbl>
## 1 Close Shave, A (1995) 4.64 4.47
## 2 Wrong Trousers, The (1993) 4.59 4.48
## 3 Sunset Blvd. (a.k.a. Sunset Boulevard) (1950) 4.57 4.46
## 4 Wallace & Gromit: The Best of Aardman Animation (1996) 4.56 4.39
## 5 Schindler's List (1993) 4.56 4.49
## 6 Shawshank Redemption, The (1994) 4.54 4.56
## 7 Grand Day Out, A (1992) 4.54 4.29
## 8 To Kill a Mockingbird (1962) 4.54 4.37
## 9 Creature Comforts (1990) 4.51 4.27
## 10 Usual Suspects, The (1995) 4.51 4.52
Measuring rating disagreement
-----------------------------
If we want to find movies that are most divisive between male and female viewers, we can add a new `mean_diff` column to the `mean_ratings` dataset, showing the difference in mean rating across both genders.
``` r
active_mean_ratings %<>%
mutate(mean_diff = M - F)
```
Sorting the dataset by this new column in ascending order will return movies that were rated higher by women, while sorting in descending order will return movies rated higher by men.
``` r
high_ratings_male <- active_mean_ratings %>%
arrange(desc(mean_diff))
```
``` r
high_ratings_male
```
## # A tibble: 1,216 x 4
## # Groups: title [1,216]
## title F M mean_diff
## <chr> <dbl> <dbl> <dbl>
## 1 Good, The Bad and The Ugly, The (1966) 3.49 4.22 0.726
## 2 Kentucky Fried Movie, The (1977) 2.88 3.56 0.676
## 3 Dumb & Dumber (1994) 2.70 3.34 0.639
## 4 Longest Day, The (1962) 3.41 4.03 0.620
## 5 Cable Guy, The (1996) 2.25 2.86 0.614
## 6 Evil Dead II (Dead By Dawn) (1987) 3.30 3.91 0.612
## 7 Hidden, The (1987) 3.14 3.75 0.607
## 8 Rocky III (1982) 2.36 2.94 0.582
## 9 Caddyshack (1980) 3.40 3.97 0.574
## 10 For a Few Dollars More (1965) 3.41 3.95 0.545
## # ... with 1,206 more rows
``` r
high_ratings_female <- active_mean_ratings %>%
arrange(mean_diff)
```
``` r
high_ratings_female
```
## # A tibble: 1,216 x 4
## # Groups: title [1,216]
## title F M mean_diff
## <chr> <dbl> <dbl> <dbl>
## 1 Dirty Dancing (1987) 3.79 2.96 -0.831
## 2 Jumpin' Jack Flash (1986) 3.25 2.58 -0.676
## 3 Grease (1978) 3.98 3.37 -0.608
## 4 Little Women (1994) 3.87 3.32 -0.549
## 5 Steel Magnolias (1989) 3.90 3.37 -0.536
## 6 Anastasia (1997) 3.8 3.28 -0.518
## 7 Rocky Horror Picture Show, The (1975) 3.67 3.16 -0.513
## 8 Color Purple, The (1985) 4.16 3.66 -0.499
## 9 Age of Innocence, The (1993) 3.83 3.34 -0.488
## 10 Free Willy (1993) 2.92 2.44 -0.483
## # ... with 1,206 more rows
Movies that elicited the most disagreement among all viewers (both male and female) can be found by exploiting the standard deviation of ratings.
``` r
rating_std_by_title <- mov_data %>%
group_by(title) %>%
summarise(std = sd(rating))
```
We will only keep movies that were rated at least 250 times, as before, and sort the data to find the most controverse titles.
``` r
rating_std_by_title %<>%
filter(title %in% active_mean_ratings$title) %>%
arrange(desc(std))
```
``` r
rating_std_by_title[1:10, ]
```
## # A tibble: 10 x 2
## title std
## <chr> <dbl>
## 1 Dumb & Dumber (1994) 1.32
## 2 Blair Witch Project, The (1999) 1.32
## 3 Natural Born Killers (1994) 1.31
## 4 Tank Girl (1995) 1.28
## 5 Rocky Horror Picture Show, The (1975) 1.26
## 6 Eyes Wide Shut (1999) 1.26
## 7 Evita (1996) 1.25
## 8 Billy Madison (1995) 1.25
## 9 Fear and Loathing in Las Vegas (1998) 1.25
## 10 Bicentennial Man (1999) 1.25
------------------------------------------------------------------------
``` r
sessionInfo()
```
## R version 3.5.1 (2018-07-02)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS 10.14.2
##
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
##
## locale:
## [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] bindrcpp_0.2.2 magrittr_1.5 forcats_0.3.0 stringr_1.3.1
## [5] dplyr_0.7.7 purrr_0.2.5 readr_1.1.1 tidyr_0.8.1
## [9] tibble_1.4.2 ggplot2_3.1.0 tidyverse_1.2.1
##
## loaded via a namespace (and not attached):
## [1] Rcpp_1.0.0 cellranger_1.1.0 pillar_1.3.0 compiler_3.5.1
## [5] plyr_1.8.4 bindr_0.1.1 tools_3.5.1 digest_0.6.18
## [9] lubridate_1.7.4 jsonlite_1.5 evaluate_0.11 nlme_3.1-137
## [13] gtable_0.2.0 lattice_0.20-35 pkgconfig_2.0.2 rlang_0.3.0.1
## [17] cli_1.0.0 rstudioapi_0.8 yaml_2.2.0 haven_1.1.2
## [21] withr_2.1.2 xml2_1.2.0 httr_1.3.1 knitr_1.20
## [25] hms_0.4.2 rprojroot_1.3-2 grid_3.5.1 tidyselect_0.2.5
## [29] glue_1.3.0 R6_2.3.0 fansi_0.3.0 readxl_1.1.0
## [33] rmarkdown_1.10 modelr_0.1.2 backports_1.1.2 scales_1.0.0
## [37] htmltools_0.3.6 rvest_0.3.2 assertthat_0.2.0 colorspace_1.3-2
## [41] utf8_1.1.4 stringi_1.2.4 lazyeval_0.2.1 munsell_0.5.0
## [45] broom_0.5.0 crayon_1.3.4
|
C++ | UTF-8 | 460 | 2.625 | 3 | [] | no_license | #include "stdafx.h"
#include "CM.h"
#include "Init.h"
CM::CM():commands(std::vector<ACommand*>()) {
lock = false;
}
CM::~CM() {
for (ACommand* cmd : commands)
delete cmd;
}
void CM::registry(ACommand* c) {
if (lock)
return;
else {
commands.push_back(c);
}
}
void CM::undo() {
if (commands.size() > 1) {
commands.pop_back();
lock = true;
for (ACommand* cmd : commands)
cmd->execute();
lock = false;
}
}
|
Python | UTF-8 | 7,018 | 3.015625 | 3 | [
"MIT"
] | permissive | from ..util import getopt, zeros
from ..vol import Vol
from math import exp, tanh, log
# Helper functions
def relu(x):
return max(0, x)
def sigmoid(x):
try:
return 1.0 / (1 + exp(-x))
except:
return 0
class ReluLayer(object):
"""
Implements ReLU nonlinearity elementwise
x -> max(0, x)
the output is in [0, inf)
"""
def __init__(self, opt={}):
self.out_sx = opt['in_sx']
self.out_sy = opt['in_sy']
self.out_depth = opt['in_depth']
self.layer_type = 'relu'
def forward(self, V, is_training=False):
self.in_act = V
V2 = V.clone()
V2.w = map(relu, V.w)
self.out_act = V2
return self.out_act
def backward(self):
V = self.in_act
V2 = self.out_act
N = len(V.w)
V.dw = zeros(N) # zero out gradient wrt data
for i in xrange(N):
if V2.w[i] <= 0: # threshold
V.dw[i] = 0
else:
V.dw[i] = V2.dw[i]
def getParamsAndGrads(self):
return []
def toJSON(self):
return {
'out_depth' : self.out_depth,
'out_sx' : self.out_sx,
'out_sy' : self.out_sy,
'layer_type': self.layer_type
}
def fromJSON(self, json):
self.out_depth = json['out_depth']
self.out_sx = json['out_sx']
self.out_sy = json['out_sy']
self.layer_type = json['layer_type']
class SigmoidLayer(object):
"""
Implements Sigmoid nnonlinearity elementwise
x -> 1/(1+e^(-x))
so the output is between 0 and 1
"""
def __init__(self, opt={}):
self.out_sx = opt['in_sx']
self.out_sy = opt['in_sy']
self.out_depth = opt['in_depth']
self.layer_type = 'sigmoid'
def forward(self, V, is_training):
self.in_act = V
V2 = V.cloneAndZero()
V2.w = map(sigmoid, V.w)
self.out_act = V2
return self.out_act
def backward(self):
V = self.in_act
V2 = self.out_act
N = len(V.w)
V.dw = zeros(N) # zero out gradient wrt data
for i in xrange(N):
v2wi = V2.w[i]
V.dw[i] = v2wi * (1.0 - v2wi) * V2.dw[i]
def getParamsAndGrads(self):
return []
def toJSON(self):
return {
'out_depth' : self.out_depth,
'out_sx' : self.out_sx,
'out_sy' : self.out_sy,
'layer_type': self.layer_type
}
def fromJSON(self, json):
self.out_depth = json['out_depth']
self.out_sx = json['out_sx']
self.out_sy = json['out_sy']
self.layer_type = json['layer_type']
class MaxoutLayer(object):
"""
Implements Maxout nnonlinearity that computes:
x -> max(x)
where x is a vector of size group_size. Ideally of course,
the input size should be exactly divisible by group_size.
"""
def __init__(self, opt={}):
self.group_size = getopt(opt, 'group_size', 2)
self.out_sx = opt['in_sx']
self.out_sy = opt['in_sy']
self.out_depth = opt['in_depth'] / self.group_size
self.layer_type = 'maxout'
self.switches = zeros(self.out_sx * self.out_sy * self.out_depth)
def forward(self, V, is_training):
self.in_act = V
N = self.out_depth
V2 = Vol(self.out_sx, self.out_sy, self.out_depth, 0.0)
if self.out_sx == 1 and self.out_sy == 1:
for i in xrange(N):
offset = i * self.group_size
m = max(V.w[offset:])
index = V.w[offset:].index(m)
V2.w[i] = m
self.switches[i] = offset + index
else:
switch_counter = 0
for x in xrange(V.sx):
for y in xrange(V.sy):
for i in xrange(N):
ix = i * self.group_size
elem = V.get(x, y, ix)
elem_i = 0
for j in range(1, self.group_size):
elem2 = V.get(x, y, ix + j)
if elem2 > elem:
elem = elem2
elem_i = j
V2.set(x, y, i, elem)
self.switches[i] = ix + elem_i
switch_counter += 1
self.out_act = V2
return self.out_act
def backward(self):
V = self.in_act
V2 = self.out_act
N = self.out_depth
V.dw = zeros(len(V.w)) # zero out gradient wrt data
# pass the gradient through the appropriate switch
if self.sx == 1 and self.sy == 1:
for i in range(N):
chain_grad = V2.dw[i]
V.dw[self.switches[i]] = chain_grad
else:
switch_counter = 0
for x in xrange(V2.sx):
for y in xrange(V2.sy):
for i in xrange(N):
chain_grad = V2.get_grad(x,y,i)
V.set_grad(x, y, self.switches[n], chain_grad)
switch_counter += 1
def getParamsAndGrads(self):
return []
def toJSON(self):
return {
'out_depth' : self.out_depth,
'out_sx' : self.out_sx,
'out_sy' : self.out_sy,
'layer_type': self.layer_type,
'group_size': self.group_size
}
def fromJSON(self, json):
self.out_depth = json['out_depth']
self.out_sx = json['out_sx']
self.out_sy = json['out_sy']
self.layer_type = json['layer_type']
self.group_size = json['group_size']
self.switches = zeros(self.group_size)
class TanhLayer(object):
"""
Implements Tanh nnonlinearity elementwise
x -> tanh(x)
so the output is between -1 and 1.
"""
def __init__(self, opt={}):
self.out_sx = opt['in_sx']
self.out_sy = opt['in_sy']
self.out_depth = opt['in_depth']
self.layer_type = 'tanh'
def forward(self, V, is_training):
self.in_act = V
V2 = V.cloneAndZero()
V2.w = map(tanh, V.w)
self.out_act = V2
return self.out_act
def backward(self):
V = self.in_act
V2 = self.out_act
N = len(V.w)
V.dw = zeros(N) # zero out gradient wrt data
for i in xrange(N):
v2wi = V2.w[i]
V.dw[i] = (1.0 - v2wi * v2wi) * V2.dw[i]
def getParamsAndGrads(self):
return []
def toJSON(self):
return {
'out_depth' : self.out_depth,
'out_sx' : self.out_sx,
'out_sy' : self.out_sy,
'layer_type': self.layer_type
}
def fromJSON(self, json):
self.out_depth = json['out_depth']
self.out_sx = json['out_sx']
self.out_sy = json['out_sy']
self.layer_type = json['layer_type'] |
JavaScript | UTF-8 | 1,316 | 2.703125 | 3 | [] | no_license | import preloadImages from '../client/src/helpers/preloadImages';
import exampleData from '../ExampleActivityData';
describe('Images should be preloaded through link tabs in the head of the HTML document', () => {
test('HTML should not have any link tags before preloadImages is run', () => {
const links = document.querySelectorAll('link');
expect(links.length).toBe(0);
});
test('preloadImages should preload for each image of a particular activity page', () => {
const { photos } = exampleData;
preloadImages(photos);
const links = document.querySelectorAll('link');
expect(links.length).toBe(photos.length + 1); // Account for preconnect link
});
test('link tags should include the preconnect attribute', () => {
const { photos } = exampleData;
preloadImages([photos[0]]);
const link = document.querySelector('link');
const attr = link.getAttribute('rel');
expect(attr).toBe('preconnect');
});
test('link tags should include the url of the target content', () => {
const { photos } = exampleData;
preloadImages([photos[0]]);
const link = Array.from(document.querySelectorAll('link'))[1];
const href = link.getAttribute('href');
const isUrlPresent = href.indexOf(photos[0].link) !== -1;
expect(isUrlPresent).toBe(true);
});
});
|
Python | UTF-8 | 9,195 | 2.75 | 3 | [] | no_license | ##BlitzKrieg v.1.1
#Copyright Maya Pharis 2017
#GENERAL BOT STUFF
#Imports and Bot Command definition
import asyncio
import discord
import logging
import math
import os
import random
import sys
from discord import utils
from discord.ext.commands import Bot
logging.basicConfig(level = logging.INFO)
#Definition of BlitzKrieg's prefix.
my_bot = Bot(command_prefix = "%")
#Bot Startup
@my_bot.event
async def on_read():
print("Deleting C:\\Windows\\System32\\...")
#I have a feeling I'm gonna get straight up slugged for this.
#COMMANDS
#Command: Hello
@my_bot.command()
async def hello(*args):
return await my_bot.say("Qu'est-ce que sup, my dude?")
#Command: Ping
@my_bot.command()
async def ping(*args):
return await my_bot.say("A game released in 1972 by Atari.")
#RAINBOW SIX SIEGE
#Command: Random Operator (Rainbow Six Siege) - Attack
@my_bot.command()
async def attack():
attk = random.choice(open("data/attackers.txt",encoding='UTF-8').readlines())
await my_bot.say("You will be playing as " + attk)
#Command: Random Operator (Rainbow Six Siege) - Defense
@my_bot.command()
async def defense():
defen = random.choice(open("data/defenders.txt",encoding='UTF-8').readlines())
await my_bot.say("You will be playing as " + defen)
#OVERWATCH
'''
#Command: Overwatch Team Comp
@my_bot.command()
async def comp():
if message.content.startswith('%comp'):
await my_bot.send_message(message.channel, 'How many offense heroes do you want?')
i == 1
if i == 1:
msg = await my_bot.wait_for_message(author=message.author)
offen = msg
i = i + 1
await my_bot.send_message(message.channel, "How many defense heroes do you want?")
if i == 2:
msg = await my_bot.wait_for_message(author=message.author)
defen = msg
i = i + 1
await my_bot.send_message(message.channel, "How many tanks do you want?")
if i == 3:
msg = await my_bot.wait_for_message(author=message.author)
tan = msg
i = i + 1
await my_bot.send_message(message.channel, "How many supports do you want?")
if i == 4:
msg = await my_bot.wait_for_message(author=message.author)
supp = msg
offense = ["Genji", "McCree", "Soldier: 76", "Reaper", "Sombra", "Tracer"]
defense = ["Bastion", "Hanzo", "Junkrat", "Widowmaker", "Mei", "Torb"]
tank = ["D.Va", "Orisa", "Roadhog", "Reinhardt", "Winston", "Zarya"]
support = ["Mercy", "Lucio", "Ana", "Symmetra", "Zenyatta"]
random.shuffle(offense)
random.shuffle(defense)
random.shuffle(tank)
random.shuffle(support)
await my_bot.send_message(message.channel, "Offense Heroes: " + offense[0:(int(offen))])
'''
#Overwatch Random: DPS
@my_bot.command()
async def herodps():
dps = random.choice(open("data/dps.txt",encoding='UTF-8').readlines())
await my_bot.say("You will be playing " + dps)
#Overwatch Random: Tank
@my_bot.command()
async def herotank():
tank = random.choice(open("data/tank.txt",encoding='UTF-8').readlines())
await my_bot.say("You will be playing " + tank)
#Overwatch Random: Healer
@my_bot.command()
async def heroheal():
heal = random.choice(open("data/healer.txt",encoding='UTF-8').readlines())
await my_bot.say("You will be playing " + heal)
#Overwatch Random: Defense
@my_bot.command()
async def herodef():
herodef = random.choice(open("data/def.txt",encoding='UTF-8').readlines())
await my_bot.say("You will be playing " + herodef)
#Comp Points Rewards checker
@my_bot.command()
async def comppoints():
await my_bot.say("Please specify a rank. Use %bronze, %silver, %gold, %platinum, %master, %grandmaster or %top500.")
async def bronze():
await my_bot.say("You will recieve 100 competitive points at the end of the season. Try harder next season.")
@my_bot.command()
async def silver():
await my_bot.say("You will recieve 200 competitive points at the end of the season. A decent rank, but you can do better.")
@my_bot.command()
async def gold():
await my_bot.say("You will recieve 400 competitive points at the end of the season. Respectable rank. Can you do better?")
@my_bot.command()
async def platinum():
await my_bot.say("You will recieve 800 competitive points at the end of the season. You're probably here because of decay, aren't you?")
@my_bot.command()
async def diamond():
await my_bot.say("You will recieve 1200 competitive points at the end of the season. Impressive. Get to Master. I dare you.")
@my_bot.command()
async def master():
await my_bot.say("You will recieve 2000 competitive points at the end of the season. One step away from glory. Do it.")
@my_bot.command()
async def grandmaster():
await my_bot.say("You will recieve 3000 competitive points at the end of the season. You've done it. I saulte you, you no-life nerd.")
@my_bot.command()
async def top500():
await my_bot.say("Hats off to you, my good man. You truly are a respectable Overwatch player.")
#Command: Random Hero (Overwatch)
@my_bot.command()
async def hero():
hero = random.choice(open("data/heroes.txt",encoding='UTF-8').readlines())
await my_bot.say("You will be playing " + hero)
#IN A NUTSHELL QUOTES
#Command Set: In a Nutshell quotes
@my_bot.command()
#Blake
@my_bot.command()
async def blake():
await my_bot.say(random.choice(open("data/nutshell_quotes/Blake.txt",encoding='UTF-8').readlines()))
#Brandon
@my_bot.command()
async def brandon():
await my_bot.say(random.choice(open("data/nutshell_quotes/Brandon.txt",encoding='UTF-8').readlines()))
#Josh
@my_bot.command()
async def josh():
await my_bot.say(random.choice(open("data/nutshell_quotes/Josh.txt",encoding='UTF-8').readlines()))
#Jake
@my_bot.command()
async def jake():
await my_bot.say(random.choice(open("data/nutshell_quotes/Jake.txt",encoding='UTF-8').readlines()))
#Maya
@my_bot.command()
async def maya():
await my_bot.say(random.choice(open("data/nutshell_quotes/Maya.txt",encoding='UTF-8').readlines()))
#Gui
@my_bot.command()
async def ray():
await my_bot.say(random.choice(open("data/nutshell_quotes/Gui.txt",encoding='UTF-8').readlines()))
#Xavier
@my_bot.command()
async def xavier():
await my_bot.say(random.choice(open("data/nutshell_quotes/Xavier.txt",encoding='UTF-8').readlines()))
#Leah
@my_bot.command()
async def leah():
await my_bot.say(random.choice(open("data/nutshell_quotes/Leah.txt",encoding='UTF-8').readlines()))
#Max
@my_bot.command()
async def max():
await my_bot.say(random.choice(open("data/nutshell_quotes/Max.txt",encoding='UTF-8').readlines()))
#Laura
@my_bot.command()
async def laura():
await my_bot.say(random.choice(open("data/nutshell_quotes/Laura.txt",encoding='UTF-8').readlines()))
#British Josh
@my_bot.command()
async def britjosh():
await my_bot.say(random.choice(open("data/nutshell_quotes/British_Josh.txt",encoding='UTF-8').readlines()))
#Nelson
@my_bot.command()
async def nelson():
await my_bot.say(random.choice(open("data/nutshell_quotes/Laura.txt",encoding='UTF-8').readlines()))
#MISC
#Command: Magic 8-Ball
@my_bot.command()
async def eightball():
ball = random.choice(open("data/8ball.txt",encoding='UTF-8').readlines())
await my_bot.say(ball)
#Command: Game Selector
#Sometimes I just can't decide what game to play. Hopefully, this will help with that.
@my_bot.command()
async def game():
game = random.choice(open('data/games.txt',encoding='UTF-8').readlines())
await my_bot.say("You should play " + game)
#Command: Dad Joke
#Yes, I did.
@my_bot.command()
async def dad():
joke = random.choice(open("data/dadjokes.txt",encoding='UTF-8').readlines())
await my_bot.say(joke)
#Info
@my_bot.command()
async def info():
await my_bot.say("Welcome to BlitzKrieg's informational menu. For info on specific commands, type any of the following.")
await my_bot.say("```%info_rainbow\n%info_overwatch\n%info_nutshell\n%info_misc```")
#Info: Rainbow Six
@my_bot.command()
async def info_rainbow():
await my_bot.say("Commands for Rainbow Six Siege.")
await my_bot.say("```%attack = Chooses a random operator on the attacking side for you to play.\n%defense - Chooses a random operator from the defending side for you to play.```")
#Info: Overwatch
@my_bot.command()
async def info_overwatch():
await my_bot.say("Commands for Overwatch.")
await my_bot.say("```%hero - Chooses a random hero for you to play.\n%herodps - Chooses a random DPS hero for you to play.\n%herotank - Chooses a random tank for you to play.\n%heroheal - Chooses a random healer for you to play.\n%herodef - Chooses a random defnese hero for you to play.\n%(rank) - Tells you how many competitive points you will recieve as an end-of-season reward.```")
#Info: In-A-Nutshell
@my_bot.command()
async def info_nutshell():
await my_bot.say("Available \"In a Nutshell\" commands.")
await my_bot.say("```%maya\t%josh\n%blake\t%brandon\n%jake\t%gui\n%xavier\t%leah\n%max\t%laura\n%britjosh\t%gui```")
#Info: Misc
@my_bot.command()
async def info_misc():
await my_bot.say("Available misc. commands.")
await my_bot.say("```%eightball - Gives you a Magic Eight Ball response to a question.\n%game = Game Selector. Gives you a random game to play.```")
my_bot.run(token)
|
Java | UTF-8 | 537 | 3.015625 | 3 | [] | no_license | /*
* UCF COP3330 Summer 2021 Assignment 2 Solution
* Copyright 2021 Ivy Nguyen
*/
package oop.assignment2.ex35.base;
import java.util.ArrayList;
import java.util.Random;
public class Winner {
private ArrayList<String> nameList;
private static final Random rand = new Random();
public String setWinner(ArrayList<String> arrayList){
this.nameList = arrayList;
return getWinner();
}
private String getWinner() {
int n = rand.nextInt(nameList.size());
return nameList.get(n);
}
}
|
Markdown | UTF-8 | 16,131 | 2.71875 | 3 | [] | no_license | ---
layout: default
title: "Moving 3 Ways Part I"
---
_____
## Part 3 - Background Tiles
_____
### Drawing Tiles
_____
{% assign num = 1 %}
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{:start="{{ num }}"}
{{ num }}. Lets right click on **Sprite** and create a new one called `sBackground `. Click on the size icon and set it to `64` wide by `32` high and make sure the Maintin Aspect Ratio is **unchecked**. Press Apply.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/sBackgroundSpriteCreate.jpg" class= "img-fluid" alt="Create new sprite with button">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Select the second brush size. Select a light blue color. Select the line tool. Go to `32` on the `x` and start to draw a straight line across the top.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/StartDrawingLine.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Tilesets require a single sprite that is blank. So we leave a 32 by 32 blank piece. Select the second brush size. Select a light blue color. Select the line tool. Go to `32` on the `x` and `1` on the `y` start to draw a straight line across the top.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/StartDrawingLine.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Start drawing second line before the halfway point so that Pac-Man can fit.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/StartDrawingSecondLine.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Finish drawing second line before the halfway point so that Pac-Man can fit.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinishDrawingSecondLine.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Right click **Tile Set** to create a new tile set.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/CreateTileSet.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Call **Tileset** `tBackground` and select the **Sprite** you just created.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/tBackgroundTilesetCreate.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Click **Tile Set Properties** button:
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/TileSetProperties.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Set properties to `32` by `32` for width and height.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/32by32Tiles.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Set properties to `32` by `32` for width and height.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/32by32Tiles.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Select the Tile Brush. This is where we will place these pieces and rotate them without wasting more game space. Press the shape on the left and place it on the right hand side. Leave a blank tile between brushes so that it only picks up one at a time in the room.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/BushBuilderStraightLineA.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Do this for all four angles and finish the brush.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/BushBuilderStraightLineB.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Go into the room and place th elines along the fourth row on the top:
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/DrawTopLine.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Test it in game and make sure it works!
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/TopLineInGame.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Draw 8 vertical corner rows on each side.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/VerticalTopLines.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Test it in game and make sure it lines up:
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/VerticalTopLinesInGame.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Draw the tunnel portion.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/CornersHalfDone.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Test it in game:
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/CornersHalfDoneInGame.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Finish the rest of the edges.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/CornersDone.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Test it in game.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/CornersDoneInGame.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Click the sprite and add some more tiles. Make it `96` x `32`.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/96WideBackgroundSprite.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Draw the corner turn in the Sprite.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/DoubleCurve.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Add it to the brush with all 4 rotations.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/NewBrushWithDoubleCurve.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Place in the room to fill in edges.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinishRoomOutsideCurves.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Add another `32` pixels to sprite. Make a near turn with pixel in corner.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/SingleLineDotInCorner.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Use the circle tool to complete the turn.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/SingleLineDotInCornerB.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Add four rotations to brush.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/BrushSingleLineDotInCorner.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Fill them in room to complete the corners.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinishOutsideCurves.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Make **Sprite** `128` wide to add more artwork.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/Add32PixelsToSprite.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Make straight line at 12 pixels.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/StraightLineSprite.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Add to brush in 4 angles.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/StraightLineBrush.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Draw the first row of lines in room.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/StraightLineRoom.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Test in game:
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/StraightLineGame.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Make **Sprite** width `256` pixels wide to add the final tiles.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinalSpriteSize.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Add 6 last remaining shapes to the **Sprite** sheet.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinalSprite.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Make all of the brushes with 4 directions except for pink door.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinalBrush.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. This is the final room layout.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinalRoom.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. This is the final layout in game.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinalGame.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. We no longer need the debug so we can comment it out. Go to `oGrid` and comment out the code in the draw script.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/CommentOutGrid.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Go to `oPacMan` draw event and comment out the square but keep the `draw_self()`.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/CommentOutPacSquare.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<div class = "row">
<div class="col-12 col-lg-4 col align-self-center">
<div markdown = "1">
{% assign num = num | plus: 1 %}
{:start="{{ num }}"}
{{ num }}. Play the game and move around the maze, this should be the final layout.
</div>
</div>
<div class="col-12 col-lg-8">
<img src="images/FinalGameNoDebug.jpg" class= "img-fluid" alt="Create new sprite with menu">
</div>
</div>
_____
<br />
<br />
[<- Previous](PacManStyleGame_4.html) [Home](../../index.html) [Continue ->](PacManStyleGame_6.html)
<br />
<br />
<br />
<br /> |
Shell | UTF-8 | 1,032 | 2.515625 | 3 | [] | no_license | #
# ~/.bashrc
#
# If not running interactively, don't do anything
[[ $- != *i* ]] && return
#Aliases
alias ls='ls --color=auto'
alias vi='vim'
alias ll='ls -l --color=auto'
alias s='ssh -XY'
alias grep='grep --color=auto'
alias sudo='sudo '
alias pcmn='sudo pacman '
alias vi=vim
alias feh='feh -.'
#Auto cd
shopt -s autocd
export EDITOR=subl
#Prompt
#PS1='[\u@\h \W]\$ 'export PS1="[\[$(tput sgr0)\]\[\033[38;5;40m\]\u\[$(tput sgr0)\]\[\033[38;5;15m\]@\[$(tput sgr0)\]\[\033[38;5;40m\]\h\[$(tput sgr0)\]\[\033[38;5;15m\] \[$(tput bold)\]\[$(tput sgr0)\]\[\033[38;5;39m\]\W\[$(tput sgr0)\]\[$(tput sgr0)\]\[\033[38;5;15m\]]\\$ \[$(tput sgr0)\]"
PS1="\[\033[38;5;6m\][\[$(tput bold)\]\[$(tput sgr0)\]\[\033[38;5;44m\]\A\[$(tput sgr0)\]\[$(tput sgr0)\]\[\033[38;5;15m\] \[$(tput sgr0)\]\[\033[38;5;6m\]\h\[$(tput sgr0)\]\[\033[38;5;15m\] \[$(tput bold)\]\[$(tput sgr0)\]\[\033[38;5;44m\]\W\[$(tput sgr0)\]\[$(tput sgr0)\]\[\033[38;5;6m\]]\\$\[$(tput sgr0)\]\[\033[38;5;15m\] \[$(tput sgr0)\]"
source <(kubectl completion bash)
|
Python | UTF-8 | 115 | 2.515625 | 3 | [] | no_license | l=[i for i in range(50)]
m=[i**2 for i in range(51)]
#n=[("a"+i)*i+1 for i in range(26)]
print(l , m , sep=("\n"))
|
Python | UTF-8 | 1,201 | 3.0625 | 3 | [] | no_license | import sys
import pygame
colors = []
for x in range(9):
colors.append(pygame.Color(0,0,0,0))
pygame.init()
dwidth = 256
dheight = 256
runGame = True
rects = []
for y in range(3):
for x in range(3):
rects.append(pygame.Rect(y*(dheight/3)+4,x*(dheight/3)+4,dwidth/3-8,dheight/3-8))
displaySurface = pygame.display.set_mode((dwidth,dheight),pygame.DOUBLEBUF)
fpsClock = pygame.time.Clock()
def draw():
for i in range(9):
displaySurface.fill(colors[i],rects[i])
print(colors[i])
pygame.display.flip()
def hexToColor(hexDigits):
vals = [hexDigits[x:x+2] for x in range(1,6,2)]
color = []
for val in vals:
color.append(int(val,16))
return pygame.Color(color[0],color[1],color[2])
while(runGame):
command = sys.stdin.readline()
if command == ':u\n':
print('update')
draw()
else:
target = int(command[1])
color = hexToColor(command[1:])
colors[target] = color
pygame.display.update()
#Handle window messages to prevent freezing
events = pygame.event.get()
for e in events:
if (e.type == pygame.QUIT):
runGame = False
|
Python | UTF-8 | 2,026 | 2.765625 | 3 | [] | no_license | try:
from matching.chamfer import chamfer_matching
except ImportError:
chamfer_matching = lambda: None
try:
from matching.blob import blob_matching
except ImportError:
blob_matching = lambda: None
import sys
import os
from PySide import QtGui
from gui.preview import KeyFramePreview
class MainWindow(QtGui.QMainWindow):
def __init__(self, data, obj):
super().__init__()
self.tabs = QtGui.QTabWidget(self)
for label, keyframe in sorted(data.items()):
self.tabs.addTab(KeyFramePreview(keyframe, obj, self.tabs), label)
self.tabs.setMovable(True)
self.setMinimumSize(960, 540)
def call_matching(function, args):
image_address = QtGui.QFileDialog.getOpenFileName(*args)
if not image_address:
print("Input cancelled", file=sys.stderr)
return
new_key_frame = function(data, image_address, obj)
name_args = [args[0],
"New keyframe",
"How would like to call the new keyframe?"]
name = QtGui.QInputDialog.getText(*name_args)[0]
self.tabs.addTab(KeyFramePreview(new_key_frame, obj, self.tabs),
name)
args = [self.tabs,
"Open Image",
os.getcwd(),
"Image Files (*.png *.jpg *.bmp)"]
self.menu_bar = QtGui.QMenuBar(self)
self.menu_bar.addAction("Blob matching",
lambda: call_matching(blob_matching, args))
self.menu_bar.addAction("Chamfer matching",
lambda: call_matching(chamfer_matching, args))
def resizeEvent(self, event): # noqa
width, height = event.size().width(), event.size().height()
menu_bar_height = 20
self.menu_bar.setGeometry(0, 0, width, menu_bar_height)
self.tabs.setGeometry(0, menu_bar_height + 1, width,
height - menu_bar_height - 1)
|
Python | UTF-8 | 816 | 3.5625 | 4 | [] | no_license | # http://stackoverflow.com/questions/214359/converting-hex-color-to-rgb-and-vice-versa
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
def rgb_string_to_hex(rgb_string):
#"rgb(153,153,153)"
rgb_list = rgb_string[4:-1].split(',')
for i in range(len(rgb_list)):
rgb_list[i] = int(rgb_list[i])
rgb_tuple = tuple( rgb_list )
return rgb_to_hex(rgb_tuple)
# Unit tests
#hex_to_rgb("#ffffff") #==> (255, 255, 255)
#hex_to_rgb("#ffffffffffff") #==> (65535, 65535, 65535)
#rgb_to_hex((255, 255, 255)) #==> '#ffffff'
#rgb_to_hex((65535, 65535, 65535)) #==> '#ffffffffffff'
#rgb_string_to_hex("rgb(247,252,185)") #==> '#' |
Java | UTF-8 | 2,109 | 3.1875 | 3 | [] | no_license | import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SortTest {
@Test
public void testEmptyArray() {
int[] arr = new int[]{};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{} );
}
@Test
public void testOneRowArray(){
int[] arr = new int[]{1};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{1} );
}
@Test
public void testTwoRowArray(){
int[] arr = new int[]{7,3};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{3,7} );
}
@Test
public void testThreeRowArray(){
int[] arr = new int[]{7, 3, 8};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{3,7, 8} );
}
@Test
public void testSevenRowArray(){
int[] arr = new int[]{7, 3, 1, 2, 6, 4, 5};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{1, 2, 3, 4, 5, 6, 7} );
}
@Test
public void testTwentyRowArray(){
int[] arr = new int[]{1, 19, 2 ,18, 3, 17, 4 ,5 ,16, 15 ,10, 6 ,8 ,9 ,7 , 14 ,13 ,12 ,11, 0};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19} );
}
@Test
public void testSixRowArrayFilledWithOneAndTwo(){
int[] arr = new int[]{1, 2, 1, 2, 1, 2};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{1, 1, 1, 2, 2, 2} );
}
@Test
public void testSixRowArrayFilledWithOne(){
int[] arr = new int[]{1, 1, 1, 1, 1, 1};
int[] sortedArr = Quicksort.sortArray( arr, 0, arr.length - 1);
assertArrayEquals( sortedArr, new int[]{1, 1, 1, 1, 1, 1} );
}
}
|
C# | UTF-8 | 509 | 2.578125 | 3 | [] | no_license | static void Main(string[] args)
{
DataTable resultsSystemA;
DataTable resultsSystemB;
DataTable resultsSystemC;
Employee e = new Employee();
var a = Task.Run(() => { resultsSystemA = e.EmployeeSearch_SystemA(); });
var b = Task.Run(() => { resultsSystemB = e.EmployeeSearch_SystemB(); });
var c = Task.Run(() => { resultsSystemC = e.EmployeeSearch_SystemC(); });
Task.WaitAll(a, b, c);
// use the datatables.
}
|
JavaScript | UTF-8 | 1,020 | 2.59375 | 3 | [] | no_license | const path = require("path");
const http = require("http");
const url = require("url");
const fs = require('fs');
const users = require('./users.json');
const port = 3000;
const publicDirectory = path.join(__dirname, '../public');
const server = http.createServer((req, res) => {
if (req.method === "GET") {
if (req.url=== "/") {
res.writeHead(200, {'Content-Type': 'text/html'})
fs.readFile('./src/index.html',null, function(error, data){
if (error){
res.writeHead(404);
res.write('File not found');
}else {
res.write(data);
}
res.end();
})
}
else if (req.url === "/raw-html") {
res.writeHead(200, {'Content-Type': 'text/html'})
res.end("<h1>welcom<h1>");
}
else if (req.url === '/users') {
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(JSON.stringify(users));
}
}
})
server.listen(port, () => {
console.log("server run at port" + port)
})
|
PHP | UTF-8 | 628 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | <?php
declare(strict_types=1);
namespace icePHP\Frame\Table;
use function icePHP\Frame\Config\configDefault;
/**
* 生成一个标准表对象
* 这是一个STable的快捷入口
* @param string $name 表的别名
* @param string 缓存类型
* @return Table 表对象
*/
function table(string $name = '', ?string $cacheType = null): Table
{
//如果未提供表名,使用默认表
if (!$name) {
$name = configDefault('','Database', '_defaultTable');
if(!$name){
trigger_error('未指明表名',E_USER_ERROR);
}
}
return Table::getInstance(trim($name), $cacheType);
} |
Java | UTF-8 | 5,171 | 1.671875 | 2 | [] | no_license | /*
* (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.ecm.core.convert.plugins.tests;
import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
import org.nuxeo.ecm.core.convert.api.ConversionService;
import org.nuxeo.runtime.api.Framework;
public class TestConverters extends BaseConverterTest {
public void testHTMLConverter() throws Exception {
doTestTextConverter("text/html", "html2text", "hello.html");
}
public void testHTMLConverter2() throws Exception {
String srcMT = "text/html";
String converter = "html2text";
String fileName = "strange.html";
ConversionService cs = Framework.getLocalService(ConversionService.class);
String converterName = cs.getConverterName(srcMT, "text/plain");
assertEquals(converter, converterName);
BlobHolder hg = getBlobFromPath("test-docs/" + fileName);
BlobHolder result = cs.convert(converterName, hg, null);
assertNotNull(result);
String textResult = result.getBlob().getString().trim();
//System.out.print(textResult);
assertTrue(textResult.contains("Nuxeo propose aux organisations"));
assertTrue(textResult.contains("\u00c9v\u00e9nements \u00e0 venir"));
// System.out.println(result.getBlob().getString());
}
public void testXMLConverter() throws Exception {
doTestTextConverter("text/xml", "xml2text", "hello.xml");
}
public void testXlConverter() throws Exception {
doTestTextConverter("application/vnd.ms-excel", "xl2text", "hello.xls");
}
public void testOOWriterConverter() throws Exception {
doTestTextConverter("application/vnd.sun.xml.writer", "oo2text", "hello.sxw");
String textContent = doTestTextConverter("application/vnd.oasis.opendocument.text", "oo2text", "hello.odt");
assertTrue(textContent.contains(" first "));
assertTrue(textContent.contains(" second "));
assertTrue(textContent.contains(" third "));
assertTrue(textContent.contains("d\u00e9j\u00e0"));
}
public void testOOWriterArabicConverter() throws Exception {
doTestArabicTextConverter("application/vnd.oasis.opendocument.text", "oo2text", "wikipedia-internet-ar.odt");
}
public void testOOCalcConverter() throws Exception {
doTestTextConverter("application/vnd.sun.xml.calc", "oo2text", "hello.sxc");
doTestTextConverter("application/vnd.oasis.opendocument.spreadsheet", "oo2text", "hello.ods");
}
public void testOOPrezConverter() throws Exception {
doTestTextConverter("application/vnd.sun.xml.impress", "oo2text", "hello.sxi");
doTestTextConverter("application/vnd.oasis.opendocument.presentation", "oo2text", "hello.odp");
}
public void testPDFConverter() throws Exception {
String textContent = doTestTextConverter("application/pdf", "pdf2text", "hello.pdf");
assertTrue(textContent.contains(" first "));
assertTrue(textContent.contains(" second "));
assertTrue(textContent.contains(" third "));
assertTrue(textContent.contains("d\u00e9j\u00e0"));
}
// disabled: need to upgrade to version > 0.7.3 version of PDFBox with fix for:
// https://issues.apache.org/jira/browse/PDFBOX-377
public void disabledTestPDFArabicConverter() throws Exception {
doTestArabicTextConverter("application/pdf", "pdf2text", "wikipedia-internet-ar.pdf");
}
public void testAnyToTextConverter() throws Exception {
doTestAny2TextConverter("text/html", "any2text", "hello.html");
doTestAny2TextConverter("text/xml", "any2text", "hello.xml");
doTestAny2TextConverter("application/vnd.ms-excel", "any2text", "hello.xls");
doTestAny2TextConverter("application/vnd.sun.xml.writer", "any2text", "hello.sxw");
doTestAny2TextConverter("application/vnd.oasis.opendocument.text", "any2text", "hello.odt");
doTestAny2TextConverter("application/vnd.sun.xml.calc", "any2text", "hello.sxc");
doTestAny2TextConverter("application/vnd.oasis.opendocument.spreadsheet", "any2text", "hello.ods");
doTestAny2TextConverter("application/vnd.sun.xml.impress", "any2text", "hello.sxi");
doTestAny2TextConverter("application/vnd.oasis.opendocument.presentation", "any2text", "hello.odp");
doTestAny2TextConverter("application/pdf", "any2text", "hello.pdf");
}
}
|
Python | UTF-8 | 2,289 | 2.765625 | 3 | [
"MIT"
] | permissive | # author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2022.03.11
# [javascript - Selenium Python: Cannot click on class="mv-button-base mv-hyperlink-button" - Stack Overflow](https://stackoverflow.com/questions/71442966/selenium-python-cannot-click-on-class-mv-button-base-mv-hyperlink-button/71443746#71443746)
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
#from webdriver_manager.firefox import GeckoDriverManager
url = 'https://www.eex.com/de/marktdaten/strom/futures#%7B%22snippetpicker%22%3A%22EEX%20German%20Power%20Future%22%7D'
##driver = webdriver.Chrome(executable_path=r'C:\bin\chromedriver.exe')
#driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())
#driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver = webdriver.Firefox()
driver.get(url)
time.sleep(3)
abrechnungspreis = driver.find_element(By.XPATH, '//div[@id="snippet-8"]//table[1]//tr[1]/td[4]')
price = abrechnungspreis.text
header = driver.find_element(By.XPATH, '//div[@id="symbolheader_pfpde"]')
input_date = header.find_element(By.XPATH, './/input')
date = input_date.get_attribute('value')
print(f'Tages Abrechnungspreis vom {date} ist {price}')
# delete old date and put yesterday
input_date.send_keys(Keys.BACKSPACE*5)
input_date.send_keys("03-09")
input_date.send_keys(Keys.ENTER)
#input_date.clear()
#input_date.send_keys("2022-03-01")
#input_date.send_keys(Keys.ENTER)
time.sleep(3) # javascript may need time to update HTML
# find again after updating HTML
abrechnungspreis = driver.find_element(By.XPATH, '//div[@id="snippet-8"]//table[1]//tr[1]/td[4]')
price = abrechnungspreis.text
date = input_date.get_attribute('value')
print(f'Tages Abrechnungspreis vom {date} ist {price}')
# --- Jahr ---
button_Jahr = header.find_element(By.XPATH, './/div[text()="Jahr"]')
driver.execute_script('arguments[0].click()', button_Jahr)
time.sleep(3) # javascript may need time to update HTML
# find again after updating HTML
abrechnungspreis = driver.find_element(By.XPATH, '//div[@id="snippet-8"]//table[1]//tr[1]/td[4]')
price = abrechnungspreis.text
print(f'Jahres Abrechnungspreis vom {date} ist {price}')
time.sleep(10)
#driver.quit()
|
JavaScript | UTF-8 | 189 | 3.0625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | let id = 0;
const obj = {
get x() {
console.log("x", id++);
},
};
let { x, y, ...z } = { ...obj, x: 1, y: 2, a: 3, b: 4 };
console.log(x);
console.log(y);
console.log(z);
|
Java | UTF-8 | 8,275 | 1.976563 | 2 | [] | no_license | package com.fafu.kongshu.zhengxianyou.pinke;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.fafu.kongshu.zhengxianyou.pinke.config.Config;
import com.fafu.kongshu.zhengxianyou.pinke.fragment.DisplayFragment;
import com.fafu.kongshu.zhengxianyou.pinke.fragment.MapFragment;
import com.fafu.kongshu.zhengxianyou.pinke.fragment.MyContentFragment;
public class DisplayActivity extends FragmentActivity implements View.OnClickListener {
private Button btn_all, btn_map, btn_mine;
public static LinearLayout ll_btn;
private MyContentFragment mContentFragment = MyContentFragment.newInstance();
//声明AMapLocationClient类对象
public AMapLocationClient mLocationClient = null;
//声明定位回调监听器
public AMapLocationListener mLocationListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (amapLocation != null) {
if (amapLocation.getErrorCode() == 0) {
double latitude = amapLocation.getLatitude();
double longitude = amapLocation.getLongitude();
String tempLocation = amapLocation.getCity() + amapLocation.getDistrict() + amapLocation.getStreet();
Config.setLatitude(latitude);
Config.setLongitude(longitude);
Config.setTempLocation(tempLocation);
Log.e("GAODE", tempLocation);
//可在其中解析amapLocation获取相应内容。
} else {
//定位失败时,可通过ErrCode(错误码)信息来确定失败的原因,errInfo是错误信息,详见错误码表。
Log.e("AmapError", "location Error, ErrCode:"
+ amapLocation.getErrorCode() + ", errInfo:"
+ amapLocation.getErrorInfo());
}
}
}
};
//声明AMapLocationClientOption对象
public AMapLocationClientOption mLocationOption = null;
/**
* 接受fragment传递过来的用于更改UI的信息
*/
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
setLlVisibility(); //隐藏导航栏
break;
case 1:
ll_btn.setVisibility(View.VISIBLE); //显示 导航栏
break;
case 2:
btn_all.setTextColor(0xffff4081);
btn_mine.setTextColor(0xffffffff);
btn_map.setTextColor(0xffffffff);
break;
case 3:
btn_mine.setTextColor(0xffFF4081);
btn_all.setTextColor(0xffffffff);
btn_map.setTextColor(0xffffffff);
break;
case 4:
btn_map.setTextColor(0xffFF4081);
btn_all.setTextColor(0xffffffff);
btn_mine.setTextColor(0xffffffff);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_display);
Config.setIsRefresh(true); //设置需要刷新
Config.setIsDisplayFragmentAlive(true); //设置DisplayFragment的生命状态为激活
Config.setIsMyContentFragmentAlive(false); //设置MyContentFragment的生命状态为未激活
Config.setIsMapFragmentAlive(false); //设置MapFragment的生命状态为未激活
//初始化定位
mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
mLocationOption = new AMapLocationClientOption();
//设置定位模式为AMapLocationMode.Battery_Saving,低功耗模式。
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//设置退出时是否杀死service
mLocationOption.setKillProcess(true);
//设置是否返回地址信息(默认返回地址信息)
mLocationOption.setNeedAddress(true);
//获取是否单次定位
mLocationOption.setOnceLocation(true);
//给定位客户端对象设置定位参数
mLocationClient.setLocationOption(mLocationOption);
//启动定位
mLocationClient.startLocation();
String name = getIntent().getStringExtra("name");
String icon = getIntent().getStringExtra("icon");
String nickName = getIntent().getStringExtra("nickName");
Config.setName(name); //用户名
Config.setMyIcon(icon);
Config.setNickName(nickName);
//new LoginActivity().finish();
addFragment();
initView();
}
@Override
protected void onResume() {
super.onResume();
}
/**
* 填充Fragment
*/
private void addFragment() {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, DisplayFragment.newInstance())
.commit();
}
/**
* 初始化View
*/
private void initView() {
ll_btn = (LinearLayout) findViewById(R.id.ll_btn);
btn_all = (Button) findViewById(R.id.btn_all);
btn_all.setOnClickListener(this);
btn_map = (Button) findViewById(R.id.btn_map);
btn_map.setOnClickListener(this);
btn_mine = (Button) findViewById(R.id.btn_mine);
btn_mine.setOnClickListener(this);
}
//隐藏导航栏
public static void setLlVisibility() {
ll_btn.setVisibility(View.GONE);
}
/**
* 点击事件相关逻辑
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_all:
addDisplayFragment();
break;
case R.id.btn_map:
addMapFragment();
break;
case R.id.btn_mine:
addMyContentFragment();
break;
}
}
/**
* 跳转到地图模式界面
*/
private void addMapFragment() {
if (!Config.isMapFragmentAlive()) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, MapFragment.newInstance(), null)
.commit();
}
}
/**
* 首界面
*/
private void addDisplayFragment() {
if (!Config.isDisplayFragmentAlive()) { //如果当前界面就是DisplayFragment则点击无效否则有效
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, DisplayFragment.newInstance(), null)
.commit();
}
}
/**
* 我的发布界面
*/
private void addMyContentFragment() {
if (!Config.isMyContentFragmentAlive()) { //仅当DisplayFragment存活才可跳转
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, mContentFragment, null)
.commit();
}
}
/**
* 接受fragment的信息,更改UI
*/
public void setHandler(int i) {
Message msg = handler.obtainMessage();
msg.what = i;
handler.sendMessage(msg);
}
}
|
Python | UTF-8 | 3,517 | 3.71875 | 4 | [
"MIT",
"BSD-2-Clause"
] | permissive | # sort values
class LinkedList():
def __init__(self) :
self._head = None
self._tail = None
self._size = 0
def add_node(self, e):
newest = Node(e, self._head)
if self.is_empty():
self._head = newest
self._tail = newest
else:
newest._next = self._head
self._head = newest
self._size += 1
def add_new_tail(self,e):
newest = Node(e)
self._tail._next = newest
self._tail = newest
self._size += 1
def remove_first(self):
if not self.is_empty():
self._head = self._next
self._size -= 1
def is_empty(self):
return self._size == 0
def top(self):
if not self.is_empty():
return self._head._element
def pop(self):
if not self.is_empty():
answer = self._head._element
self._head = self._head._next
self._size -= 1
return answer
def remove_node(self,e):
node = self._head
if node._element == e:
self._head = self._head._next
else:
while not node._next == None:
if node._next._element == e:
node._next = node._next._next
break
node = node._next
def show_elements(self):
if self.is_empty():
return ''
node = self._head
elements = str(node._element) + '->'
while not node._next == None:
node = node._next
elements += str(node._element) + '->'
return elements
def remove_repeated_without_buffer(self):
elements = []
node = self._head
elements.append(node._element)
while not node._next == None:
node = node._next
if node._element in elements:
self.remove_node(node._element)
else:
elements.append(node._element)
def remove_repeated_with_buffer(self):
node = self._head
while not node._next == None:
node_aux = node._next
while True:
if node_aux._element == node._element:
self.remove_node(node._element)
if not node_aux._next == None:
node_aux = node_aux._next
else:
break
node = node._next
def find_last_n(self,n):
node = self._head
i = 1
elements = []
while not node == None:
elements.append(node._element)
node = node._next
return elements[n-1:]
'''Add elements in descendent ord from head '''
def add_sort(self,e):
if self.is_empty():
self.add_node(e)
return self.show_elements()
elif e > self._head._element:
newest = Node(e)
newest._next = self._head
self._head = newest
return self.show_elements()
else:
node = self._head._next
prev = self._head
while node != None:
if e >= node._element:
newest = Node(e)
newest._next = node
prev._next = newest
return self.show_elements()
prev = node
node = node._next
newest = Node(e)
self._tail._next = newest
self._element = newest
return self.show_elements()
'''Add elements in ascedent ord from head '''
def add_sort2(self,e):
if self.is_empty():
self.add_node(e)
return self.show_elements()
elif e < self._head._element:
newest = Node(e)
newest._next = self._head
self._head = newest
return self.show_elements()
else:
node = self._head._next
prev = self._head
while node != None:
if e <= node._element:
newest = Node(e)
newest._next = node
prev._next = newest
return self.show_elements()
prev = node
node = node._next
newest = Node(e)
self._tail._next = newest
self._element = newest
return self.show_elements()
class Node():
__slots__ = '_element,', '_next'
def __init__(self, e, next = None):
self._element = e
self._next = next
|
PHP | UTF-8 | 1,305 | 2.515625 | 3 | [] | no_license | <?php
//export.php
$connect = mysqli_connect("localhost", "root", "", "tutorial");
$output = '';
if(isset($_POST["export"]))
{
$query = "SELECT * FROM users";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<table class="table" bordered="1">
<tr>
<th>First Name:</th>
<th>Department</th>
<th>Semester</th>
<th>Date of Birth</th>
<th>University Number</th>
<th>Phone number</th>
<th>Address</th>
<th>Email address</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["fname"].'</td>
<td>'.$row["dept"].'</td>
<td>'.$row["sem"].'</td>
<td>'.$row["dob"].'</td>
<td>'.$row["uninumber"].'</td>
<td>'.$row["phnum"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["email"].'</td>
</tr>
';
}
$output .= '</table>';
header('Content-Type: application/xls');
header('Content-Disposition: attachment; filename=download.xls');
echo $output;
}
}
?> |
Java | UTF-8 | 865 | 3.921875 | 4 | [] | no_license | package basics;
//By using constructors copy the values of one object to another object.
public class ConstructorDemo7 {
//instance variables
String username,password;
ConstructorDemo7(String username, String password){
//assigning local values to instance variables
this.username=username;
this.password=password;
}
ConstructorDemo7(ConstructorDemo7 con){
this.username=con.username;
this.password=con.password;
//display();
}
void display(){
//printing instance variable values
System.out.println("User Name is: "+username);
System.out.println("Password is: "+password);
}
public static void main(String[] args) {
ConstructorDemo7 obj1 = new ConstructorDemo7("testuser@gmail.com","abcd1234");
ConstructorDemo7 obj2 = new ConstructorDemo7(obj1);
obj1.display();
obj2.display();
}
}
|
Java | UTF-8 | 1,179 | 2.671875 | 3 | [] | no_license | package Assignment4;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class GUISimulator
{
public Button btnArrive, btnLeave, btnClockUp, btnStats;
public TextField txtClock, txtCustServed, txtNumCustWaiting;
public TextArea txtStats;
public Simulation guiSim = new Simulation();
public void buttonArrive(ActionEvent actionEvent) {
guiSim.arrival();
txtCustServed.setText(String.valueOf(guiSim.currCustomer()));
txtNumCustWaiting.setText(String.valueOf(guiSim.currWaiting()));
}
public void buttonLeave(ActionEvent actionEvent) {
guiSim.leave();
txtNumCustWaiting.setText(String.valueOf(guiSim.currWaiting()));
}
public void buttonClockUp(ActionEvent actionEvent) {
guiSim.clockUpdate(1);
txtClock.setText(String.valueOf(guiSim.returnTime()));
}
public void buttonStatistics(ActionEvent actionEvent) {
txtNumCustWaiting.setText(String.valueOf(guiSim.currWaiting()));
txtClock.setText(String.valueOf(guiSim.returnTime()));
txtStats.setText(guiSim.printStatistics());
}
}
|
Python | UTF-8 | 381 | 3.15625 | 3 | [] | no_license | import datetime
current_date_time = datetime.datetime.utcnow()
print(current_date_time)
#asian time
current_date_time = datetime.datetime.now()
print(current_date_time)
from dateutil.relativedelta import relativedelta
#relative delta
current_date_time += relativedelta(days = 30)
print(current_date_time)
current_date_time -= relativedelta(years = 1)
print(current_date_time) |
Markdown | UTF-8 | 1,480 | 2.90625 | 3 | [] | no_license | # URL博客
## URL内容(统一资源定位符)
*URL包含了协议+域名或者ip+端口号+路径+查询字符+锚点
*锚点是不到服务器上的
## DNS作用:
1. 将域名解析为IP 地址,客户端向DNS服务器发送域名查询请求。
2. nslookup命令:用来查询服务器和ip地址。
## IP作用:
1. 用来定位一台设备。
2. 约定了如何封装数据报文,以跟其他设备交流。
3. ping命令:用来查询一个域名对应的ip,但是不同地区可能会有不同ip(比如华中、北、东、南)。
## 域名:
域名(Domain names)是互联网基础架构的关键部分。它们为互联网上任何可用的网页服务器提供了方便人类理解的地址。
任何连上互联网的电脑都可以通过一个公共IP地址访问到,对于IPv4地址来说,这个地址有32位(它们通常写成四个范围在0~255以内,由点分隔的数字组成,比如173.194.121.32),而对于IPv6来说,这个地址有128位,通常写成八组由冒号分隔的四个十六进制数(e.g., 2027:0da8:8b73:0000:0000:8a2e:0370:1337). 计算机可以很容易地处理这些IP地址, 但是对一个人来说很难找出谁在操控这些服务器以及这些网站提供什么服务。IP 地址很难记忆而且可能会随着时间的推移发生改变 。为了解决这些问题,我们使用方便记忆的地址,称作域名。
(以上来自mdn)
域名其实也就是ip或者.com等等结尾的字符串。
|
JavaScript | UTF-8 | 412 | 3.078125 | 3 | [] | no_license | const login = document.getElementById("button")
login.addEventListener("click", function (event) {
event.preventDefault()
const nama = document.getElementById("name")
const pass = document.getElementById("password")
if(nama.value === "admin" && pass.value === "admin"){
window.location.href = "homepage.html"
}else{
alert(`Username dan Password salah`)
}
}) |
Java | UTF-8 | 5,930 | 3.078125 | 3 | [] | no_license | package hiho;
/**
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
给定一个1-N的排列A1, A2, ... AN,每次操作小Hi可以选择一个数,把它放到数组的最左边。
请计算小Hi最少进行几次操作就能使得新数组是递增排列的。
输入
第一行包含一个整数N。
第二行包含N个两两不同整数A1, A2, ... AN。(1 <= Ai <= N)
对于60%的数据 1 <= N <= 20
对于100%的数据 1 <= N <= 100000
输出
一个整数代表答案
样例输入
5
2 3 1 4 5
样例输出
1
*/
/**
* @author zxwtry
* @email zxwtry@qq.com
* @project OJ
* @package hiho
* @file 训练17_题目1_F1Score.java
* @type 训练17_题目1_F1Score
* @date 2017年5月21日 下午12:00:03
* @details
*/
import java.util.Scanner;
public class 训练17_题目2_数组重排2 {
static class TA extends Thread {
boolean[] a;
public TA(boolean[] b) {
a = b;
}
@Override
public void run() {
System.out.println("fuck");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.run();
a[0] = true;
}
}
public static void main(String[] args) throws InterruptedException {
// int[] arr = tools.Random随机生成器.A_生成一个不重复随机数据(20, 1, 20);
// tools.Utils.printArray(arr, arr.length);
// solve();
// solve2();
// int[] ar = {1};
// int[] br = {};
// System.arraycopy(ar, 1, br, 0, 0);
// System.out.println("done");
boolean[] a = {true};
TA t = new TA(a);
a[0] = false;
t.start();
t.join();
Thread.sleep(2000);
t.start();
// Scanner sc = new Scanner(System.in);
//
// int n = sc.nextInt();
// int[][] t = new int[2][n];
// int[] a = t[0];
// int max = 0;
// int ans = 0;
// for (int i = 0; i < n; i ++)
// a[i] = sc.nextInt();
// int[] b = t[1];
//
//
// while (true) {
// int thisCount = 0;
// int bi = 0;
// max = 0;
// for (int i = 0 ;i < n; i ++) {
//
// int v = a[i];
// max = Math.max(max, v);
// if (v < max) {
// thisCount ++;
// } else {
// b[bi ++] = v;
// }
// }
// n = bi;
//
// int[]tt = t[0];
// t[0] = t[1];
// t[1] = tt;
//
// a = t[0];
// b = t[1];
//
// ans += thisCount;
// if (thisCount == 0) break;
// }
//
//
// System.out.println(ans);
// a[i] =sc.nextInt();
// sc.close();
}
static void solve2() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
int[] is = new int[n];
for (int i = 0; i < n; i ++) {
a[i] = sc.nextInt() - 1;
is[a[i]] = i;
}
int ans = 0;
int left = n-1;
for (int i = n-1; i > -1; i --) {
if (left >= is[i] - 1) {
ans += left - is[i];
left = is[i] - 1;
if (left < 0) break;
}
}
System.out.println(ans);
sc.close();
}
static void solve() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] t = new int[2][n];
int[] a = t[0];
int max = 0;
int ans = 0;
int[] b = t[1];
int bi = 0;
for (int i = 0; i < n; i ++) {
a[i] = sc.nextInt();
if (a[i] < max) {
ans ++;
} else if (a[i] > max) {
b[bi ++] = a[i];
} else {
//a[i] == max
}
max = Math.max(max, a[i]);
}
swap(t);
while (true) {
a = t[0];
b = t[1];
int i = 0;
int an = bi;
bi = 0;
max = 0;
int count = 0;
for (i = 0; i < an; i ++) {
if (a[i] < max) {
count ++;
} else if (a[i] > max) {
b[bi ++] = a[i];
} else {
}
}
ans += count;
if (count == 0) break;
swap(t);
}
System.out.println(ans);
sc.close();
}
static void swap(int[][] t) {
int[] tt = t[0];
t[0] = t[1];
t[1] = tt;
}
/**
#include <stdio.h>
#include <stdlib.h>
long a[100001];
int main()
{
long n,i,g=0,s,maxs;
scanf("%ld",&n);
s=0;
maxs=0;
for (i=1;i<=n;i++)
{
scanf("%ld",&s);
if (s>maxs)
maxs=s;
else if (s>g)
g=s;
}
printf("%ld\n",g);
return 0;
}
/*
find 3 ,largest number that previous number biggert than it
2 4 3 1 5 6
3 2 4 1 5 6
2 3 4 1 5 6
1 2 3 4 5 6
*/
}
|
Python | UTF-8 | 168 | 3.09375 | 3 | [] | no_license | #Link: https://edabit.com/challenge/pHp9qkjY53JNTGCG4
from math import ceil
def century_from_year(year):
return ceil(year/100)
print(century_from_year(1901)) |
Python | UTF-8 | 123 | 2.734375 | 3 | [] | no_license | def x_test(l,typein):
for x,y in enumerate(l):
if y==typein:
break
return x
x_test("Soul","o") |
Markdown | UTF-8 | 1,373 | 2.84375 | 3 | [] | no_license | ---
date: 2020-09-05 12:00
description: 本周的由于其他琐事的原因,每天能够用于开发的时间基本上只能保证 2-3 个小时,所以进展不大。不过好在我也没有明确的进度指标。
tags: SwiftUI, 健康笔记
title: 健康笔记 2.0 开发随笔(三)
---
由于家属突发疾病,最近每天都要出入医院,因此最近用于开发的时间很有限。
目前 app 已经完成了笔记、条目、数据的创建、编辑、显示、删除全部逻辑。如果不考虑图表、数据导入导出、交叉比对等功能,app 的基本功能已经完成了。
在本次开发中,我着重调整了表单的开发方式,目前表单无论从响应,判断等方便都比上一版有了很大的提高。
本次我将以前分散的输入源(source of truth)统一到了一起,不仅更便于代码管理,同时也方便实现了很多以前无法或实现起来非常困难的功能。
关于表单的处理,可以参看我的文章 [如何在 SwiftUI 中创建一个实时响应的 Form](/posts/swiftui-input-form/)。
另外,由于我的 app 对于 sheet 的使用量也很多,所以也对 sheet 的响应做出了统一的管理,这方面我记录在另一篇文章中 [在 SwiftUI 中,根据需求弹出不同的 Sheet](/posts/swiftui-multiSheet/)。
时间有限,随便记录一点。
|
Java | UTF-8 | 3,069 | 1.976563 | 2 | [
"Apache-2.0"
] | permissive | /*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.gradle.versions.lockstate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableSet;
import com.palantir.gradle.versions.GradleComparators;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import org.gradle.api.artifacts.VersionConstraint;
import org.gradle.api.artifacts.component.ComponentIdentifier;
import org.junit.jupiter.api.Test;
class LockStatesTest {
@Test
void modules_like_grpc_should_have_its_square_bracket_version_stripped() {
ComponentIdentifier grpcApi = componentIdentifier("io.grpc:grpc-api");
ComponentIdentifier grpcCore = componentIdentifier("io.grpc:grpc-core");
ComponentIdentifier grpcNetty = componentIdentifier("io.grpc:grpc-netty");
ComponentIdentifier somethingElse = componentIdentifier("something:else");
VersionConstraint squareBracketConstraint = versionConstraint("[1.27.1]");
VersionConstraint normalConstraint = versionConstraint("1.27.1");
NavigableMap<ComponentIdentifier, Set<VersionConstraint>> dependents =
new TreeMap<>(GradleComparators.COMPONENT_IDENTIFIER_COMPARATOR);
dependents.put(grpcApi, ImmutableSet.of(squareBracketConstraint));
dependents.put(grpcCore, ImmutableSet.of(normalConstraint));
dependents.put(grpcNetty, ImmutableSet.of(squareBracketConstraint, normalConstraint));
dependents.put(somethingElse, ImmutableSet.of(squareBracketConstraint));
assertThat(LockStates.prettyPrintConstraints(Dependents.of(dependents)))
.containsExactly(
"io.grpc:grpc-api -> 1.27.1",
"io.grpc:grpc-core -> 1.27.1",
"io.grpc:grpc-netty -> {1.27.1, 1.27.1}",
"something:else -> 1.27.1");
}
private ComponentIdentifier componentIdentifier(String componentIdentifier) {
ComponentIdentifier grpcApi = mock(ComponentIdentifier.class);
when(grpcApi.getDisplayName()).thenReturn(componentIdentifier);
return grpcApi;
}
private VersionConstraint versionConstraint(String version) {
VersionConstraint constraint = mock(VersionConstraint.class);
when(constraint.toString()).thenReturn(version);
return constraint;
}
}
|
C++ | UTF-8 | 7,726 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#define MAX_SIZE 256
#define FILLER 0
typedef struct TTree {
unsigned char sym;
unsigned int freq;
struct TTree* left;
struct TTree* right;
} Tree;
typedef struct TStack{
Tree* root;
struct TStack* next;
} Stack;
typedef struct TCode {
unsigned char* sym;
int size;
} Code;
typedef struct TBitStream {
unsigned char byte;
int size;
} BitStream;
Stack* newStack(Tree* node) {
Stack* tmp = (Stack*)malloc(sizeof(Stack));
assert(tmp);
tmp->next = NULL;
tmp->root = node;
return tmp;
}
Tree* newTree(unsigned char sym, int freq) {
Tree* tmp = (Tree*)malloc(sizeof(Tree));
assert(tmp);
tmp->freq = freq;
tmp->sym = sym;
tmp->left = NULL;
tmp->right = NULL;
return tmp;
}
Code* newCode(unsigned char* sym, int size) {
Code* tmp = (Code*)malloc(sizeof(Code));
assert(tmp);
tmp->sym = sym;
tmp->size = size;
return tmp;
}
BitStream* newBitStream() {
BitStream* tmp = (BitStream*)malloc(sizeof(BitStream));
assert(tmp);
tmp->byte = 0;
tmp->size = 0;
return tmp;
}
void countFreq(int* freqTable, FILE* in) {
int c;
while ((c = fgetc(in)) != EOF) {
freqTable[c]++;
}
}
void push(Stack** sortedStack, Tree* node) {
int val = node->freq;
Stack* tmp = newStack(node);
if (!(*sortedStack) || (*sortedStack)->root->freq >= val) {
tmp->next = *sortedStack;
*sortedStack = tmp;
return;
}
Stack* cur = *sortedStack;
while (cur->next && val > cur->next->root->freq) {
cur = cur->next;
}
tmp->next = cur->next;
cur->next = tmp;
}
Tree* pop(Stack** stack) {
Stack* tmp = *stack;
Tree* sym = tmp->root;
*stack = (*stack)->next;
free(tmp);
return sym;
}
void buildBase(Stack** stack, int* freqTable) {
for (int i = 0; i < MAX_SIZE; i++) {
if (freqTable[i]) {
push(stack, newTree(i, freqTable[i]));
}
}
}
Tree* merge(Tree* first, Tree* second) {
Tree* tmp = newTree(FILLER, first->freq + second->freq);
tmp->left = second;
tmp->right = first;
return tmp;
}
Tree* buildCodeTree(Stack** stack) {
if (!(*stack)) {
return NULL;
}
while ((*stack)->next) {
push(stack, merge(pop(stack), pop(stack)));
}
return pop(stack);
}
void resizeBuffer(Code* buffer) {
buffer->size++;
int isOverflow = buffer->size % CHAR_BIT;
if (isOverflow == 1) {
int bytes = buffer->size / CHAR_BIT + 1;
buffer->sym = (unsigned char*)realloc(buffer->sym, bytes);
buffer->sym[bytes - 1] = 0;
}
}
unsigned char* copyCode(Code* buffer) {
int bytes = (buffer->size - 1) / CHAR_BIT + 1;
unsigned char* newSym = (unsigned char*)malloc(bytes);
assert(newSym);
for (int i = 0; i < bytes; i++) {
newSym[i] = buffer->sym[i];
}
return newSym;
}
void addBit(Code* buffer, int bit) {
int pos = (buffer->size - 1) / CHAR_BIT;
buffer->sym[pos] = (buffer->sym[pos] << 1) + bit;
}
void buildCodeTable(Code** codeTable, Tree* codeTree, Code* buffer) {
if (!codeTree) {
return;
}
if (!codeTree->left) {
if (!buffer->sym) {
resizeBuffer(buffer);
}
codeTable[codeTree->sym] = buffer;
}
else {
resizeBuffer(buffer);
Code* newBuff = newCode(copyCode(buffer), buffer->size);
addBit(buffer, 0);
addBit(newBuff, 1);
buildCodeTable(codeTable, codeTree->left, buffer);
buildCodeTable(codeTable, codeTree->right, newBuff);
}
}
void writeBits(unsigned char bits, int count, BitStream* bitStream, FILE* out) {
if (!count) {
return;
}
int shift = CHAR_BIT - bitStream->size;
if (shift >= count) {
bitStream->size += count;
bitStream->byte <<= count;
unsigned char mask = (1 << count) - 1;
bitStream->byte += bits & mask;
if (bitStream->size == CHAR_BIT) {
fputc(bitStream->byte, out);
bitStream->size = 0;
bitStream->byte = 0;
}
return;
}
writeBits(bits >> (count - shift), shift, bitStream, out);
writeBits(bits, count - shift, bitStream, out);
}
void writeTree(Tree* codeTree, BitStream* bitStream, FILE* out) {
if (!codeTree) {
return;
}
if (!codeTree->left) {
writeBits(0, 1, bitStream, out);
writeBits(codeTree->sym, CHAR_BIT, bitStream, out);
return;
}
writeBits(1, 1, bitStream, out);
writeTree(codeTree->left, bitStream, out);
writeTree(codeTree->right, bitStream, out);
}
void codeText(FILE* in, FILE* out, Code** codeTable, BitStream* bitStream) {
int c, i;
while ((c = fgetc(in)) != EOF) {
for (i = 0; i < codeTable[c]->size / CHAR_BIT; i++) {
writeBits(codeTable[c]->sym[i], CHAR_BIT, bitStream, out);
}
writeBits(codeTable[c]->sym[i], codeTable[c]->size % CHAR_BIT, bitStream, out);
}
if (bitStream->size) {
fputc(bitStream->byte << (CHAR_BIT - bitStream->size), out);
}
}
void writeSize(unsigned int size, FILE* out) {
fwrite(&size, sizeof(unsigned int), 1, out);
}
void freeCodeTable(Code** codeTable) {
for (int i = 0; i < MAX_SIZE; i++) {
if (codeTable[i]) {
free(codeTable[i]->sym);
free(codeTable[i]);
}
}
}
void freeTree(Tree* tree) {
if (!tree) {
return;
}
if (tree->left) {
freeTree(tree->left);
}
if (tree->right) {
freeTree(tree->right);
}
free(tree);
}
void code(FILE* in, FILE* out) {
int freqTable[MAX_SIZE];
Stack* stack = NULL;
Code* codeTable[MAX_SIZE];
Tree* codeTree = NULL;
BitStream* bitStream = newBitStream();
memset(freqTable, 0, sizeof(int) * MAX_SIZE);
memset(codeTable, NULL, sizeof(Code*) * MAX_SIZE);
countFreq(freqTable, in);
buildBase(&stack, freqTable);
codeTree = buildCodeTree(&stack);
if (codeTree) {
writeSize(codeTree->freq, out);
}
writeTree(codeTree, bitStream, out);
buildCodeTable(codeTable, codeTree, newCode(NULL, 0));
fseek(in, 3, SEEK_SET);
codeText(in, out, codeTable, bitStream);
free(bitStream);
freeCodeTable(codeTable);
freeTree(codeTree);
}
unsigned char getBit(BitStream* bitStream, FILE* in) {
if (!bitStream->size) {
bitStream->byte = fgetc(in);
bitStream->size = CHAR_BIT;
}
unsigned char bit = bitStream->byte >> 7;
bitStream->size--;
bitStream->byte <<= 1;
return bit;
}
Tree* getCodeTree(FILE* in, BitStream* bitStream) {
Tree* codeTree = NULL;
if (getBit(bitStream, in)) {
codeTree = newTree(FILLER, FILLER);
codeTree->left = getCodeTree(in, bitStream);
codeTree->right = getCodeTree(in, bitStream);
}
else {
unsigned char sym = 0;
for (int i = 0; i < CHAR_BIT; i++) {
sym = (sym << 1) + getBit(bitStream, in);
}
codeTree = newTree(sym, FILLER);
}
return codeTree;
}
int readSize(FILE* in, unsigned int* size) {
return fread(size, sizeof(unsigned int), 1, in);
}
void decodeText(Tree* codeTree, FILE* in, FILE* out, unsigned int size, BitStream* bitStream) {
Tree* tmpCodeTree;
for (unsigned int i = 0; i < size; i++) {
tmpCodeTree = codeTree;
while (tmpCodeTree->left) {
if (getBit(bitStream, in)) {
tmpCodeTree = tmpCodeTree->right;
}
else {
tmpCodeTree = tmpCodeTree->left;
}
}
fputc(tmpCodeTree->sym, out);
}
}
void decode(FILE* in, FILE* out) {
unsigned int size;
if (!readSize(in, &size)) {
return;
}
BitStream* bitStream = newBitStream();
Tree* codeTree = getCodeTree(in, bitStream);
decodeText(codeTree, in, out, size, bitStream);
free(bitStream);
freeTree(codeTree);
}
int main() {
FILE* in = fopen("in.txt", "rb");
FILE* out = fopen("out.txt", "wb");
assert(in);
assert(out);
unsigned char mode = fgetc(in);
fseek(in, 3, SEEK_SET);
if (mode == 'c') {
code(in, out);
}
else if (mode == 'd') {
decode(in, out);
}
fclose(in);
fclose(out);
return 0;
}
|
C# | UTF-8 | 8,351 | 3.0625 | 3 | [] | no_license | using System;
using System.Threading;
using System.Threading.Tasks;
namespace chancies.adventofcode
{
public class Computer
: IDisposable
{
private readonly ManualResetEvent _mre;
private readonly ILog _log;
private readonly string _id;
private Pipeline _inputPipeline;
private Pipeline _outputPipeline;
public Computer(ILog logger, string id)
{
_log = logger;
_id = id;
_mre = new ManualResetEvent(false);
_inputPipeline = new Pipeline();
_outputPipeline = new Pipeline();
}
public event EventHandler<int> OutputData;
public async Task RunAsync(int[] program)
{
await Task.Run(() => Run(program));
}
public void Run(int[] program)
{
TraceMsg("Starting int computer");
var opPointer = 0;
while (true)
{
var opCode = program[opPointer].ToString("D5");
var operation = int.Parse(opCode.Substring(3));
var parameterModes = opCode.Substring(0, 3);
switch (operation)
{
case 1:
Add(program, ref opPointer, parameterModes);
break;
case 2:
Multiply(program, ref opPointer, parameterModes);
break;
case 3:
Input(program, ref opPointer);
break;
case 4:
Output(program, ref opPointer, parameterModes);
break;
case 5:
Jump(program, ref opPointer, parameterModes, JumpMode.JumpIfTrue);
break;
case 6:
Jump(program, ref opPointer, parameterModes, JumpMode.JumpIfFalse);
break;
case 7:
SetIfSize(program, ref opPointer, parameterModes, SetMode.LessThan);
break;
case 8:
SetIfSize(program, ref opPointer, parameterModes, SetMode.Equals);
break;
case 99:
TraceDebug("HALT");
TraceMsg("int computer exiting");
return;
default:
throw new InvalidOperationException($"Invalid op code {program[opPointer]}");
}
}
}
public void AddDataToInputPipeline(params int[] data)
{
foreach (var datum in data)
{
_inputPipeline.Write(datum);
}
_mre.Set();
}
private void Run(object o)
{
var program = (int[]) o;
Run(program);
}
private int GetValue(int[] program, int opPointer, int parameterNumber, string parameterModes)
{
var modeIndex = 3 - parameterNumber;
if (parameterModes[modeIndex] == '0')
{
// Position mode
return program[program[opPointer + parameterNumber]];
}
else
{
// Immediate mode
return program[opPointer + parameterNumber];
}
}
private void Add(int[] program, ref int opPointer, string parameterModes)
{
var param1 = GetValue(program, opPointer, 1, parameterModes);
var param2 = GetValue(program, opPointer, 2, parameterModes);
var resultPointer = program[opPointer + 3];
program[resultPointer] = param1 + param2;
TraceDebug($"ADD p[{resultPointer}] = {param1} + {param2}");
opPointer += 4;
}
private void Multiply(int[] program, ref int opPointer, string parameterModes)
{
var param1 = GetValue(program, opPointer, 1, parameterModes);
var param2 = GetValue(program, opPointer, 2, parameterModes);
var resultPointer = program[opPointer + 3];
program[resultPointer] = param1 * param2;
TraceDebug($"MULTIPLY p[{resultPointer}] = {param1} x {param2}");
opPointer += 4;
}
private void Input(int[] program, ref int opPointer)
{
var value = ReadInputFromPipeline();
var resultPointer = program[opPointer + 1];
program[resultPointer] = value;
TraceDebug($"INPUT p[{resultPointer}] = {value}");
opPointer += 2;
}
private int ReadInputFromPipeline()
{
if (!_inputPipeline.CanRead)
{
_mre.WaitOne();
}
var result = _inputPipeline.Read();
if (!_inputPipeline.CanRead)
{
_mre.Reset();
}
return result;
}
private void Output(int[] program, ref int opPointer, string parameterModes)
{
var result = GetValue(program, opPointer, 1, parameterModes);
TraceDebug($"OUTPUT {result}");
_outputPipeline.Write(result);
OutputData?.Invoke(this, result);
opPointer += 2;
}
private void Jump(int[] program, ref int opPointer, string parameterModes, JumpMode mode)
{
var param1 = GetValue(program, opPointer, 1, parameterModes);
var param2 = GetValue(program, opPointer, 2, parameterModes);
switch (mode)
{
case JumpMode.JumpIfTrue:
TraceDebug($"JUMP-IFTRUE {param1} == {param2}");
if (param1 != 0)
{
opPointer = param2;
}
else
{
opPointer += 3;
}
break;
case JumpMode.JumpIfFalse:
TraceDebug($"JUMP-IFFALSE{param1} != {param2}");
if (param1 == 0)
{
opPointer = param2;
}
else
{
opPointer += 3;
}
break;
}
}
private void SetIfSize(int[] program, ref int opPointer, string parameterModes, SetMode mode)
{
var param1 = GetValue(program, opPointer, 1, parameterModes);
var param2 = GetValue(program, opPointer, 2, parameterModes);
var resultPointer = program[opPointer + 3];
switch (mode)
{
case SetMode.LessThan:
TraceDebug($"SET-LESSTHAN {param1} < {param2}");
if (param1 < param2)
{
program[resultPointer] = 1;
}
else
{
program[resultPointer] = 0;
}
break;
case SetMode.Equals:
TraceDebug($"SET-EQUALS {param1} == {param2}");
if (param1 == param2)
{
program[resultPointer] = 1;
}
else
{
program[resultPointer] = 0;
}
break;
}
opPointer += 4;
}
public void Dispose()
{
_mre?.Dispose();
_inputPipeline?.Dispose();
_outputPipeline?.Dispose();
}
private void TraceDebug(string msg, params object[] args)
{
_log.TraceDebug($"COMPUTER {_id}: {msg}", args);
}
private void TraceMsg(string msg, params object[] args)
{
_log.TraceMsg($"COMPUTER {_id}: {msg}", args);
}
private enum JumpMode
{
JumpIfTrue,
JumpIfFalse
}
private enum SetMode
{
LessThan,
Equals
}
}
}
|
Python | UTF-8 | 1,520 | 2.609375 | 3 | [] | no_license | import xlrd
import sqlite3
conn = sqlite3.connect('xlsparser.db')
cur = conn.cursor()
rb = xlrd.open_workbook('registry_full.xls',formatting_info=True)
sheet = rb.sheet_by_index(0)
#Считываем из эксельки переменные
for rownum in range(sheet.nrows):
row = sheet.row_values(rownum)
comp_inn=int(row[10])
print('inn type:',type(comp_inn),comp_inn)
House_addr=row[12]
House_fias_code=row[13]
House_reg_inc=row[14]
House_man_start=row[15]
House_man_end=row[16]
House_reg_exc=row[17]
House_reg_exc_base=row[18]
House_198data=row[19]
House_reg_pub=row[20]
#ищу в базе Primary key компании с ИНН = comp_inn
cur.execute("SELECT PK FROM Company WHERE comp_inn=?", (comp_inn,))
comp_id = cur.fetchone()[0]
# tcomp_id=lcomp_id[0]
# comp_id=tcomp_id[0]
print('ID type:', type(comp_id), comp_id)
#Запиысываем в базу информацию о доме
cur.execute('''INSERT OR IGNORE INTO House
(House_addr, House_fias_code, House_reg_inc, House_man_start, House_man_end, House_reg_exc, House_reg_exc_base, House_198data, House_reg_pub, Comp_id)
VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )''',
(House_addr, House_fias_code, House_reg_inc, House_man_start, House_man_end, House_reg_exc, House_reg_exc_base, House_198data, House_reg_pub, comp_id) )
conn.commit()
# except: print('shit happened')
# for c_el in row:
# print(c_el)
# print('cel type:',type(c_el))
|
Markdown | UTF-8 | 2,376 | 3 | 3 | [
"MIT"
] | permissive | # create-react-app app example
Example of using **app-server** with a trivial
[**create-react-app**](https://github.com/facebook/create-react-app) app.
## Run the example in development mode
```sh
git clone https://github.com/staticdeploy/app-server.git
cd app-server/examples/create-react-app
yarn install
# Start the development server
yarn start
```
Open the app at http://localhost:3000 and see the `Hello world!` greeting.
Change the value of the variable defined in `public/index.html` and see that the
greeting target has changed.
### What happens in the example
`yarn start` simply starts **create-react-app**'s development server.
When the app is loaded:
1. the `#app-config` script in the app's `index.html` defines the variable
`window.APP_CONFIG`
2. the appropriate greeting is rendered
## Run the example in production mode with Docker
```sh
git clone https://github.com/staticdeploy/app-server.git
cd app-server/examples/create-react-app
# Build the app Docker image
docker build -t app-server-example .
# Run the image passing in the necessary configuration
docker run --rm --init -p 3000:80 -e APP_CONFIG_TARGET=world app-server-example
```
Open the app at http://localhost:3000 and see the `Hello world!` greeting. Stop
the container and restart it passing in a different value for the
`APP_CONFIG_TARGET` variable. Re-open the app and see that the greeting target
has changed.
### What happens in the example
The `docker build ...` command builds the app docker image, using the
`staticdeploy/app-server:cra-builder` and `staticdeploy/app-server:cra-runtime`
base images which respectively:
- build the app into a static bundle
- setup**app-server** to serve the bundle
When the image is run with `docker run ...`, `app-server`:
1. starts serving the app using StaticDeploy's serving algorithm, that includes
features such as:
1. using a fallback asset for requests to non-existing assets
2. allowing the user to use non-canonical paths to request assets (e.g.
`/foo/index.js` instead of `/index.js`)
3. injecting the app configuration in the served html files
4. specifying custom headers for assets
When the app is loaded:
1. the `#app-config` script in the app's `index.html` is evaluated
2. the content of the script defines the variable `window.APP_CONFIG`
3. the appropriate greeting is rendered
|
Python | UTF-8 | 2,554 | 3.296875 | 3 | [
"BSD-2-Clause"
] | permissive | """
Gaussian Distribution with Outliers
-----------------------------------
This figure shows the distribution of points drawn from a narrow
Gaussian distribution, with 20% "outliers" drawn from a wider
Gaussian distribution. Over-plotted are the robust and non-robust
estimators of the mean and standard deviation.
"""
# Author: Jake VanderPlas
# License: BSD
# The figure produced by this code is published in the textbook
# "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
# For more information, see http://astroML.github.com
# To report a bug or issue, use the following forum:
# https://groups.google.com/forum/#!forum/astroml-general
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import norm, anderson
from astroML.stats import mean_sigma, median_sigmaG
#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX. This may
# result in an error if LaTeX is not installed on your system. In that case,
# you can set usetex to False.
if "setup_text_plots" not in globals():
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
#------------------------------------------------------------
# Create distribution
Npts = int(1E6)
f_out = 0.2
N_out = int(f_out * Npts)
sigma1 = 1
sigma2 = 3
np.random.seed(1)
x = np.hstack((np.random.normal(0, sigma1, Npts - N_out),
np.random.normal(0, sigma2, N_out)))
#------------------------------------------------------------
# Compute anderson-darling test
A2, sig, crit = anderson(x)
print("anderson-darling A^2 = {0:.1f}".format(A2))
#------------------------------------------------------------
# Compute non-robust and robust point statistics
mu_sample, sig_sample = mean_sigma(x)
med_sample, sigG_sample = median_sigmaG(x)
#------------------------------------------------------------
# Plot the results
fig, ax = plt.subplots(figsize=(5, 3.75))
# histogram of data
ax.hist(x, 100, histtype='stepfilled', alpha=0.2,
color='k', density=True)
# best-fit normal curves
x_sample = np.linspace(-15, 15, 1000)
ax.plot(x_sample, norm(mu_sample, sig_sample).pdf(x_sample), '-k',
label='$\sigma$ fit')
ax.plot(x_sample, norm(med_sample, sigG_sample).pdf(x_sample), '--k',
label='$\sigma_G$ fit')
ax.legend()
ax.set_xlim(-8, 8)
ax.set_xlabel('$x$')
ax.set_ylabel('$p(x)$')
plt.show()
|
TypeScript | UTF-8 | 2,807 | 2.78125 | 3 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"ISC",
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"0BSD",
"BSD-2-Clause",
"LGPL-2.1-only",
"GPL-3.0-or-later"
] | permissive | import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { DefaultErrorMap, ErrorMap, isMapError, UrlFragmentToHttpErrorMap } from './error-map-utils';
/**
* Options that enable the ErrorMapService to find the wanted ErrorMap (specifically in the case of http errors).
* `url` is a url (from the HttpErrorResponse), whose fragments indicate which map should be used.
* `data` is the original body of the request.
*/
interface GetHttpErrorMapOptions {
url: string;
data?: any;
}
@Injectable({
providedIn: `root`
})
export class ErrorMapService {
public constructor(private translate: TranslateService) {}
/**
* Takes an error message and tries to match it to a cleaner version in the corresponding ErrorMap.
* @param errorMessage the error message that should be mapped and translated.
* @returns A translated and (if possible) mapped "Error: <errorMsg>", or, if the ErrorMap contains an Error-object, said Error-object.
*/
public getCleanErrorMessage(errorMessage: string, options: GetHttpErrorMapOptions): string | Error {
let errorMsg = errorMessage;
let errorMap = options ? this.getHttpErrorMap(options) : DefaultErrorMap;
const fittingExpressions = errorMap ? Array.from(errorMap.keys()).filter(exp => exp.test(errorMessage)) : [];
if (fittingExpressions.length) {
if (fittingExpressions.length > 1) {
console.warn(`ErrorMapService has found multiple matches for "${errorMessage}"`);
}
let mappedValue = errorMap.get(fittingExpressions[0]);
if (typeof mappedValue === `function`) {
mappedValue = mappedValue(errorMessage);
}
if (isMapError(mappedValue)) {
return mappedValue.getError();
}
errorMsg = this.translate.instant(mappedValue);
} else {
console.warn(`ErrorMapService has found no matches for "${errorMessage}"`);
}
return `${this.translate.instant(`Error`)}: ${errorMsg}`;
}
private getHttpErrorMap(options: GetHttpErrorMapOptions): ErrorMap | null {
let urlFragments = options.url.split(/[\/?]+/);
if (/http/.test(urlFragments[0])) {
urlFragments = urlFragments.slice(2);
}
for (let i = 0; i < urlFragments.length; i++) {
let map = UrlFragmentToHttpErrorMap.get(urlFragments[i]);
if (map) {
if (typeof map === `function`) {
map = map(options?.data);
}
if (map) {
return map;
}
}
}
console.warn(`No available error map for ${options.url}`);
return null;
}
}
|
Java | UTF-8 | 197 | 1.835938 | 2 | [] | no_license | package br.com.mm.service;
import br.com.mm.config.exceptions.MMException;
import br.com.mm.model.virtual.Movie;
public interface MovieService {
Movie getById(int id) throws MMException;
}
|
Java | UTF-8 | 2,175 | 2.375 | 2 | [
"MIT"
] | permissive | package com.bakdata.conquery.models.preproc.parser.specific;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.bakdata.conquery.models.config.ConqueryConfig;
import com.bakdata.conquery.models.events.stores.primitive.DecimalArrayStore;
import com.bakdata.conquery.models.events.stores.root.DecimalStore;
import com.bakdata.conquery.models.events.stores.root.IntegerStore;
import com.bakdata.conquery.models.events.stores.specific.ScaledDecimalStore;
import com.bakdata.conquery.models.exceptions.ParsingException;
import com.bakdata.conquery.models.preproc.parser.ColumnValues;
import com.bakdata.conquery.models.preproc.parser.Parser;
import com.bakdata.conquery.util.NumberParsing;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
@ToString(callSuper = true)
@Slf4j
public class DecimalParser extends Parser<BigDecimal, DecimalStore> {
private transient int maxScale = Integer.MIN_VALUE;
private transient BigDecimal maxAbs;
public DecimalParser(ConqueryConfig config) {
super(config);
}
@Override
protected BigDecimal parseValue(String value) throws ParsingException {
return NumberParsing.parseBig(value);
}
@Override
protected void registerValue(BigDecimal v) {
log.trace("Registering `{}`", v);
BigDecimal abs = v.abs();
if (v.scale() > maxScale) {
maxScale = v.scale();
}
if (maxAbs == null || maxAbs.compareTo(abs) < 0) {
maxAbs = abs;
}
}
@Override
protected DecimalStore decideType() {
BigInteger unscaled = ScaledDecimalStore.unscale(maxScale, maxAbs);
if (unscaled.bitLength() > 63) {
return DecimalArrayStore.create(getLines());
}
IntegerParser sub = new IntegerParser(getConfig());
sub.setMaxValue(unscaled.longValueExact());
sub.setMinValue(-unscaled.longValueExact());
sub.setLines(getLines());
sub.setNullLines(getNullLines());
IntegerStore subDecision = sub.findBestType();
return new ScaledDecimalStore(maxScale, subDecision);
}
@Override
public void setValue(DecimalStore store, int event, BigDecimal value) {
store.setDecimal(event, value);
}
@Override
public ColumnValues<BigDecimal> createColumnValues() {
return new ListColumnValues();
}
}
|
Shell | UTF-8 | 177 | 2.859375 | 3 | [
"BSD-3-Clause-Open-MPI"
] | permissive | #!/bin/bash
# checking the parameters
if [$# -ne 1];
then echo "Usage: ./visualize_Q_P.sh P.csv Q.csv"
fi
export P_INPUT=$1
export Q_INPUT=$2
gnuplot visualize_Q_P.gp -p |
Ruby | UTF-8 | 12,086 | 2.71875 | 3 | [] | no_license | #! /usr/bin/ruby -w
#
# callcc.rb: a Fiber implementation for Ruby 1.8, based on callcc
# by pts@fazekas.hu at Tue Nov 30 21:36:00 CET 2010
#
# SUXX: It has terrible memory leaks in Ruby 1.8.
#
# This script works in Ruby 1.9 (using the built-in Fiber class) and Ruby 1.8
# (using the emulation provided here).
#
# TODO(pts): Run the Ruby unit tests.
#
# Root reason for hthe leak, on http://www.ruby-forum.com/topic/170608
#
# The central problem is that gcc (and other compilers) tend to create
# sparse stack frames such that, when a new frame is pushed onto the
# stack, it does not completely overwrite the one that had been previously
# stored there. The new frame gets activated with old VALUE pointers
# preserved inside its holes. These become "live" again as far as any
# conservative garbage collector is concerned. And, viola, a leak is born!
#
$-w = true
class FiberError < StandardError
end
# TODO(pts): Measure speed.
# TODO(pts): Evaluate memory use and GC memory leaks.
class Fiber;
fail "Fiber replacement loaded multiple times" if defined?(@@current)
fail "Fiber emulation loaded over another Fiber" if method_defined?(:alive?)
@@current = @@root = nil
def initialize(&block)
if nil == block;
raise ArgumentError, "tried to create Proc object without a block" if
nil != @@current
@cc = nil
@is_alive = true
@resumed_by = nil
@thread = Thread.current
else
@is_alive = true # Can be resumed/transferred later.
@resumed_by = false
@thread = Thread.current
callcc { |cc1|
x = callcc { |cc2|
@cc = cc2
cc1.call
}
begin
x = block.call(*x)
exc = nil
rescue Exception
exc = $!
end
@is_alive = false
block = nil # Save memory.
# TODO(pts): Discard the current stack frame to reclaim memory.
# TODO(pts): Avoid creating local variables.
# Ruby 1.8 doesn't have tail recursion optimization, and 1.9.2 doesn't
# have it either, see also http://redmine.ruby-lang.org/issues/show/1256
if @resumed_by;
resumed_by = @resumed_by
@resumed_by = nil # Break the reference to save memory.
# TODO(pts): Add a begin/rescue to the transfer call below.
if !resumed_by.alive?
# TODO(pts): Do we have to use the parant of resumed_by instead?
resumed_by = @@root
exc = FiberError.new('dead fiber called')
end
else
resumed_by = @@root
end
@@goodbye_args.push(resumed_by, exc, x)
resumed_by = exc = x = nil # Save memory.
@@goodbye.call()
fail "unreachable" # TODO(pts): Optimize this away.
}
end
end
def inspect()
"#<Fiber:0x%x>" % (object_id << 1)
end
def to_s()
"#<Fiber:0x%x>" % (object_id << 1)
end
def alive?()
@is_alive
end
def transfer(*args)
raise FiberError, "dead fiber called" if !@is_alive
raise FiberError, "fiber called across threads" if @thread != Thread.current
if self == @@current;
fail if args.size > 1 # ruby 1.9.2 does this.
return args[0] # nil if args.empty?
end
fail if nil != @@current.cc
fail if nil == @cc
x = callcc { |cc|
@@current.cc = cc
cc = @cc
@cc = nil
@@current = self
cc.call(args) # TODO(pts): Forget about cc (for garbage collection).
}
@@goodbye_args.clear # Save memory.
raise x if x.kind_of? Exception
x.size > 1 ? x : x[0]
end
def resume() #args)
return [0]
# TODO(pts): Fix the error order.
raise FiberError, "dead fiber called" if !@is_alive
raise FiberError, "double resume" if @resumed_by
raise FiberError, "fiber called across threads" if @thread != Thread.current
@resumed_by = @@current
transfer(*args)
end
def __yield(*args) # TODO(pts): Don't expose this publicly.
raise FiberError, "can't yield from root fiber" if
nil == @resumed_by and self == @@root
resumed_by = @resumed_by || @@root
@resumed_by = nil
# TODO(pts): Clean up our stack to save memory.
resumed_by.transfer(*args)
end
class <<self;
def current()
@@current
end
def yield(*args)
@@current.__yield(*args)
end
end
def __transfer_exc(exc) # TODO(pts): Make this code non-protected.
# TODO(pts): Avoid code duplication.
raise FiberError, "dead fiber called" if !@is_alive
raise FiberError, "fiber called across threads" if @thread != Thread.current
if self == @@current;
fail if args.size > 1 # ruby 1.9.2 does this.
return args[0] # nil if args.empty?
end
fail if nil != @@current.cc
fail if nil == @cc
x = callcc { |cc|
@@current.cc = cc
cc = @cc
@cc = nil
@@current = self
cc.call(exc) # TODO(pts): Forget about cc (for garbage collection).
}
@@goodbye_args.clear # Save memory.
raise x if x.kind_of? Exception
x.size > 1 ? x : x[0]
end
protected
@@root = @@current = self.new
@@goodbye_args = []
callcc { |cc1|
callcc { |cc2|
@@goodbye = cc2
cc1.call()
}
# This is the routine called by @@goodbye.call.
loop {
# fiber, exc, x = @@goodbye_args
if @@goodbye_args[1];
@@goodbye_args[0].__transfer_exc(@@goodbye_args[1])
else
@@goodbye_args[0].transfer(@@goodbye_args[2])
end
}
}
attr_accessor :cc
end if RUBY_VERSION < "1.9"
# ---
if false; # !!
p RUBY_VERSION
root = Fiber.current
fail if "can't yield from root fiber" != begin
Fiber.yield
rescue FiberError
$!.to_s
end
fail if true != root.alive?
fail if nil != root.transfer()
fail if 3 != root.transfer(3)
fail if 4 != root.resume(4)
fail if "double resume" != begin
root.resume() && nil
rescue FiberError
$!.to_s
end
# Yes, we can yield from the root fiber, if we have previously resumed it.
# This works in Ruby 1.9.2.
fail if 5 != Fiber.yield(5)
fail if "can't yield from root fiber" != begin
Fiber.yield 6
rescue FiberError
$!.to_s
end
fi = Fiber.new { |*x| root.transfer({:x=>x}).inspect }
fail if true != fi.alive?
fail if {:x=>[]} != fi.transfer()
fail if true != fi.alive?
fail if 56.inspect != fi.transfer(56)
fail if false != fi.alive?
fail if "dead fiber called" != begin
fi.transfer()
rescue FiberError
$!.to_s
end
fail if "dead fiber called" != begin
fi.resume()
rescue FiberError
$!.to_s
end
fail if "dead fiber called" != begin # Not a "double resume".
fi.resume()
rescue FiberError
$!.to_s
end
fi = Fiber.new { |*x| root.transfer({:x=>x}).inspect }
fail if {:x=>[nil]} != fi.transfer(nil)
fail if [57, 58].inspect != fi.transfer(57, 58)
fi = Fiber.new { |*x| root.transfer({:x=>x}) + [3, 4] }
fail if {:x=>[[:a]]} != fi.transfer([:a])
fail if [1, 2, 3, 4] != fi.transfer([1, 2])
fi = Fiber.new { |*x| root.transfer({:x=>x}) }
fail if {:x=>[:a]} != fi.transfer(:a)
fi = Fiber.new { |*x| root.transfer({:x=>x}) }
fail if {:x=>[:a, :b]} != fi.transfer(:a, :b)
fi = Fiber.new { |*x| root.transfer({:x=>x}) }
fail if {:x=>[[:a, :b]]} != fi.transfer([:a, :b])
fi = Fiber.new { |*x| Fiber.yield({:x=>x}) }
fail if {:x=>[[:a, :b, :c]]} != fi.resume([:a, :b, :c])
fi = Fiber.new { |*x| Fiber.yield(x) }
fail if [[:a, :b, :c]] != fi.resume([:a, :b, :c])
fi = Fiber.new { |*x| Fiber.yield(x) }
fail if [42] != fi.resume(42)
fi = Fiber.new { |*x| Fiber.yield(x[0] * 2) }
fail if 84 != fi.resume(42)
fi = Fiber.new { |*x| Fiber.yield(x[0] + 1, x[0] + 2) }
fail if [43, 44] != fi.resume(42)
# This is to demonstrate that if a non-resume()d fiber yield()s, then it
# will give control to the root fiber. If it gave control to any of its
# caller fibers instead, the return value would be be multiplied by 10
# and/or -1.
fail if 42 != Fiber.new {
Fiber.new { Fiber.new { Fiber.yield 42 }.transfer() * 10 }.resume() * -1
}.transfer()
# This is to demonstrate that if a resume()d fiber yields(), then it will
# give control to the fiber which resumed() it.
fail if -420 != Fiber.new {
Fiber.new { Fiber.new { Fiber.yield 42 }.resume() * 10 }.resume() * -1
}.transfer()
# Combination of the rules above.
fail if 420 != Fiber.new {
Fiber.new { Fiber.new { Fiber.yield 42 }.resume() * 10 }.transfer() * -1
}.resume()
yield_for_me = lambda { |x| Fiber.yield x }
squares = Fiber.new { |n|
Fiber.yield :a
i = 1
while i * i <= n;
Fiber.yield i * i
i += 1
end
}
double = Fiber.new { |fi1|
Fiber.yield :b
loop {
x = fi1.resume()
break if nil == x
yield_for_me.call x * 2
}
}
fail if :a != squares.resume(25)
fail if :b != double.resume(squares)
items = []
loop {
x = double.resume()
break if nil == x
items << x
}
fail if [2, 8, 18, 32, 50] != items
# This is to demonstrate that if a transfer()-ed fiber returns, it will
# return control to the root fiber. If control was returned to f2 and/or f3,
# then the returned value would be multiplied by 10 and/or -1.
f2 = Fiber.new { |fi1| fi1.transfer() * 10 }
f3 = Fiber.new { f2.transfer(Fiber.new { 42 }) * -1 }
fail if 42 != f3.transfer()
# This is to demonstrate that when a resume()d fiber returns, it will
# return control to the fiber which resumed it.
f2 = Fiber.new { |fi1| fi1.resume() * 10 }
f3 = Fiber.new { f2.resume(Fiber.new { 42 }) * -1 }
fail if -420 != f3.resume()
# Combination of the rules above.
f2 = Fiber.new { |fi1| fi1.transfer() * 10 }
f3 = Fiber.new { f2.resume(Fiber.new { 42 }) * -1 }
fail if 42 != f3.resume()
# Combination of the rules above.
f2 = Fiber.new { |fi1| fi1.resume() * 10 }
f3 = Fiber.new { f2.transfer(Fiber.new { 42 }) * -1 }
fail if 420 != f3.resume()
# This is to demonstrate that exceptions are propagated.
f1 = Fiber.new { fail "lucky" }
f2 = Fiber.new {
begin
f1.resume
rescue Exception => e
"un" + e.to_s
end
}
fail if f2.resume != "unlucky"
#p root.cc # Can't call protected method.
foo = Fiber.new { |*x|
fail if x != [41, 410]
fail if [26, 260] != root.transfer(15)
fail if 27 != root.transfer(16)
root.transfer(17)
fail
}
fail if 15 != foo.transfer(41, 410)
fail if 16 != foo.transfer(26, 260)
fail if 17 != foo.transfer(27)
end
if false;
def f(n, root)
if n > 0;
return 1 + f(n - 1, root)
end
while true;
root.transfer 5
end
end
def g(n, fi)
if n > 0;
return 1 + g(n - 1, fi)
end
100000.times {
fail if 5 != fi.transfer
}
0
end
#depth = 230 # SystemStackError above that.
#root = Fiber.current
#g(depth, Fiber.new { f(depth, root) })
end
p "All OK."
class ZFiber
def f()
#callcc { |cc| @cc = cc; return } # wastes
callcc { |cc1| # wastes
callcc { |cc2|
@cc = cc2
cc1.call
}
}
self
end
end
def foo()
callcc { |cc| @cc = cc; return }
end
if true;
GC.enable
GC.start
# SUXX: The Ruby 1.8 garbage collector doesn't get triggered automatically.
# Wouldn't work even with 3GB of RAM wouth calling the GC manually.
Process.setrlimit(Process::RLIMIT_AS, 70 << 20) # 30MB
# On narancs at r171, 510 fits, 520 doesn't fit to 30MB -- so we do 5200.
(1..520000).each { |i|
#Fiber.new {} # This itself doesn't waste memory.
#Fiber.new {}.alive? # This itself wastes memory!
#ZFiber.new.object_id # This itself wastes memory with return.
ZFiber.new.f # This doesn't waste memory.
ZFiber.new.f.object_id # This itself wastes memory with return.
#foo() # This doesn't waste memory.
#fail if Fiber.new { [i * 0] }.resume != [0]
#GC.start if (i & 127) == 0 # This fixes the problem.
}
end
# depth=230 iter=100000 ./callcc.rb 1.80s user 0.06s system 100% cpu 1.825 total
# depth=2 iter=100000 ./callcc.rb 0.74s user 0.00s system 100% cpu 0.737 total
|
Shell | UTF-8 | 2,671 | 3.609375 | 4 | [] | no_license | #!/bin/sh -e
verifyArchive() {
echo "Verifying archive"
YES_COUNT=$(./rosa debug testdata/archive.rosa|head|grep Yes|wc -l)
ORPHANS_COUNT=$(./rosa debug testdata/archive.rosa|grep "refs: 0"|wc -l)
if [ "$YES_COUNT" -ne "0" ]
then
echo "There is either journal or orphan nodes!"
exit 1
fi
if [ "$ORPHANS_COUNT" -ne "0" ]
then
echo "There are orphans, even if header claims there should not be any!"
exit 1
fi
if [ "$1" = "" ]
then
./rosa verify testdata/archive.rosa
else
./rosa verify testdata/archive.rosa -p $1
fi
}
echo "Compiling"
make clean
cp Makefile Makefile.ORIGINAL
sed -i 's/-DNDEBUG/-Wall -Wpointer-arith -Werror -ansi -pedantic/g' Makefile
make
mv Makefile.ORIGINAL Makefile
echo "Obtaining test data"
rm -rf testdata
mkdir testdata
wget http://storage.henu.fi/rosa/testdata/mercurial-1.7.4.tar.gz -O testdata/1.tgz
wget http://storage.henu.fi/rosa/testdata/mercurial-2.1.2.tar.gz -O testdata/2.tgz
wget http://storage.henu.fi/rosa/testdata/mercurial-2.2.3.tar.gz -O testdata/3.tgz
echo "Extracting test data"
cd testdata
mkdir 1
cd 1
tar xf ../1.tgz
cd ..
mkdir 2
cd 2
tar xf ../2.tgz
cd ..
mkdir 3
cd 3
tar xf ../3.tgz
cd ..
cd ..
echo "Taking first snapshot"
./rosa snapshot testdata/archive.rosa yesterday testdata/1
verifyArchive
echo "Taking second snapshot"
./rosa snapshot testdata/archive.rosa today testdata/2
verifyArchive
echo "Taking third snapshot"
./rosa snapshot testdata/archive.rosa tomorrow testdata/3
verifyArchive
echo "Modifying archive"
./rosa remove testdata/archive.rosa today/2/mercurial-2.1.2/contrib /yesterday/1/mercurial-1.7.4/README
verifyArchive
./rosa mkdir testdata/archive.rosa today/2/lol /test_omg
verifyArchive
rm testdata/archive.rosa
echo "Taking first snapshot of encrypted archive"
./rosa -p test snapshot testdata/archive.rosa yesterday testdata/1
verifyArchive test
echo "Taking second snapshot of encrypted archive"
./rosa -p test snapshot testdata/archive.rosa today testdata/2
verifyArchive test
echo "Taking third snapshot of encrypted archive"
./rosa -p test snapshot testdata/archive.rosa tomorrow testdata/3
verifyArchive test
echo "Modifying encrypted archive"
./rosa -p test remove testdata/archive.rosa today/2/mercurial-2.1.2/contrib /yesterday/1/mercurial-1.7.4/README
verifyArchive test
./rosa -p test mkdir testdata/archive.rosa today/2/lol /test_omg
verifyArchive test
rm testdata/archive.rosa
echo "Interrupting snapshotting"
for i in $(seq 1 1 120)
do
./rosa snapshot testdata/archive.rosa test testdata/1 &
ROSA_PID=$!
sleep 1
kill -9 $ROSA_PID
done
./rosa snapshot testdata/archive.rosa test testdata/1
verifyArchive
echo "Cleaning"
rm -rf testdata
|
Markdown | UTF-8 | 2,615 | 2.796875 | 3 | [
"MIT"
] | permissive | ---
title: Jmeter 从数据库查询多个字段,依次传给登录接口怎么实现
date: 2021-09-09 10:37:00 +0800
categories: [JMeter, 基础]
tags: [JMeter基础]
pin: false
---
**如果需要查询多个字段,都要传给登录接口该如何操作?例如查询返回的用户名和密码,两个字段传给登录接口**
### 一、添加jdbc请求并设置变量,获取数据库多个字段值
1、添加好JDBC Connection Configuration并做好数据库连接配置
2、导入mysql驱动jar包
3、添加线程组-->右键线程组-->添加jdbc request,并做好设置

4、添加查看结果树并运行;得到以下结果


ps:这里为了举例方便,并未获取密码的值,如果工作中有需要查库获取密码,那么需要找对应开发将密码加密解密的代码部分导出一个jar包,并添加到jmeter的lib/ext下;另外自己添加BeanShell PostProcessor写代码进行密码解密
### 二、添加另一个jdbc请求,用于获取member中的用户总数
1、右键线程组-->添加一个jdbc请求,并设置变量count

2、运行,确认下用户总数

### 三、添加循环控制器、计数器,实现循环读取库的多个字段信息,并传递到下一个登录请求
1、添加循环控制器,用于所有用户的循环运行

2、在循环控制器之下,添加计数器

3、在循环控制器之下,添加登录请求,并进行嵌套变量引用

- **${n}:**这里n为计数器得出的值,从1到${count\_1},即值为1~25
- **\_V函数:** 若${\_\_V(phone\_${n})}中${n}=2, 则${\_\_V(phone\_2)}返回phone\_2的值
4、点击运行,所有用户全部进行了登录执行

 |
Java | UTF-8 | 1,011 | 2.75 | 3 | [] | no_license | package exemplu2;
public class Programator extends Angajat implements IAngajat{
private int salariuOra;
public Programator(String nume,String cnp,int sal) {
super(nume,cnp);
this.salariuOra=sal;
}
@Override
public int calculeazaSalariu() {
// TODO Auto-generated method stub
return salariuOra*NR_ZILE*NORMA_ZI;
}
@Override
public void afiseazaAngajat() {
// TODO Auto-generated method stub
System.out.println(" Nume:"+getNume()+" Salariu:"+calculeazaSalariu()+" Ani pana la pensie:"+aniPanaLaPensie());
}
@Override
public char afiseazaGen() {
int cnpg = Integer.parseInt(cnp.substring(0,1));
if(cnpg==5||cnpg==1)
return 'M';
return 'F';
}
@Override
public int aniPanaLaPensie() {
// TODO Auto-generated method stub
if(afiseazaGen()=='F')
return 65-getVarsta();
return 67-getVarsta();
}
public int getSalariuOra() {
return salariuOra;
}
public void setSalariu(int salariu) {
this.salariuOra = salariu;
}
public int getAni() {
return aniPanaLaPensie();
}
}
|
JavaScript | UTF-8 | 471 | 2.625 | 3 | [] | no_license | import { LOAD_BOOKS, ADD_BOOK } from '../actions';
const initialState = { books: [] };
const books = (state = initialState, action) => {
switch (action.type) {
case LOAD_BOOKS:
return {
books: [...action.books]
}
break;
case ADD_BOOK:
console.log('REDUCERS ADD_BOOK', action.book);
return {
books: [...state.books, action.book]
}
break;
default:
return state;
}
}
export default books; |
Python | UTF-8 | 1,003 | 3.921875 | 4 | [] | no_license | class Mystuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between\n"
def apple(self):
print "I AM CLASSY APPLES!"
thing = Mystuff()
thing.apple()
print thing.tangerine
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family", "With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
# https://www.youtube.com/watch?v=trOZBgZ8F_c
class Hero:
def __init__(self, name):
self.name = name
self.health = 100
def eat(self, food):
if food == 'apple':
self.health -= 100
elif food == 'ham':
self.health += 20
Bob = Hero('Bob')
print Bob.name
print Bob.health
Bob.eat('apple')
print Bob.health
Bob.eat('ham')
print Bob.health
|
C | UTF-8 | 1,294 | 2.96875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** add_alias.c
** File description:
** add alias
*/
#include "ftsh.h"
void create_alias(alias_t *alias, char *cmd, char *new)
{
memset(alias, 0, sizeof(alias_t));
strcpy(alias->cmd, cmd);
strcpy(alias->new, new);
}
void set_add_alias(char *tmp, char **cmd)
{
strcat(tmp, cmd[0]);
for (int index = 1; cmd[index]; index++) {
strcat(tmp, " ");
strcat(tmp, cmd[index]);
}
}
void add_alias(shell_t *shell, char *cmd, char **new)
{
unsigned int index = 0;
char tmp[CMD_SIZE] = {0};
set_add_alias(tmp, new);
if (shell->alias_len == 0 || !shell->command_alias) {
shell->command_alias = calloc(1, sizeof(alias_t));
shell->alias_len = 1;
return (create_alias(shell->command_alias, cmd, tmp));
}
for (; index != shell->alias_len && \
my_strcmp(shell->command_alias[index].cmd, cmd); index++);
if (index < shell->alias_len && \
!my_strcmp(shell->command_alias[index].cmd, cmd)) {
strcpy(shell->command_alias[index].new, tmp);
} else {
shell->command_alias = realloc(shell->command_alias, \
(shell->alias_len + 1) * sizeof(alias_t));
create_alias(&shell->command_alias[shell->alias_len], cmd, tmp);
shell->alias_len += 1;
}
}
|
Java | UTF-8 | 1,180 | 2.265625 | 2 | [] | no_license | package com.kudinov.restoratorclient.adapter;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.kudinov.restoratorclient.R;
import com.kudinov.restoratorclient.model.Department;
import java.util.List;
public class TestDepartmentAdapter extends ArrayAdapter<Department> {
public TestDepartmentAdapter(@NonNull Context context, int resource, List<Department> objects) {
super(context, resource, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.firebase_test, parent, false);
}
TextView txtId = convertView.findViewById(R.id.dep_id);
TextView txtName = convertView.findViewById(R.id.dep_name);
Department dep = getItem(position);
txtId.setText(String.valueOf(dep.getId()));
txtName.setText(dep.getName());
return convertView;
}
}
|
C# | UTF-8 | 1,629 | 2.875 | 3 | [] | no_license | using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TengDa.Models
{
public interface IPagedData
{
int PageCount { get; set; }
int PageNumber { get; set; }
int PageSize { get; set; }
int TotalItemCount { get; set; }
void AddItem(object obj);
}
public class PagedData<T> : List<T>, IPagedData
{
public int PageCount { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalItemCount { get; set; }
public PagedData()
{
}
public PagedData(IEnumerable<T> list, IPagedList pagedList)
{
this.AddRange(list);
this.PageCount = pagedList.PageCount;
this.PageNumber = pagedList.PageNumber;
this.PageSize = pagedList.PageSize;
this.TotalItemCount = pagedList.TotalItemCount;
}
public PagedData(IPagedList<T> pagedList)
{
this.AddRange((IEnumerable<T>)pagedList);
this.PageCount = pagedList.PageCount;
this.PageNumber = pagedList.PageNumber;
this.PageSize = pagedList.PageSize;
this.TotalItemCount = pagedList.TotalItemCount;
}
public IPagedList ToPagedList()
{
return (IPagedList)new StaticPagedList<T>((IEnumerable<T>)this, this.PageNumber, this.PageSize, this.TotalItemCount);
}
public void AddItem(object obj)
{
//???????
}
}
}
|
Java | UTF-8 | 625 | 1.796875 | 2 | [] | no_license | package consulo.php.impl.lang.documentation.params;
import consulo.codeEditor.Editor;
import consulo.language.editor.AutoPopupController;
import consulo.language.psi.PsiDocumentManager;
import consulo.language.psi.PsiFile;
/**
* @author jay
* @date Jun 30, 2008 8:20:42 PM
*/
public class PhpParameterInfoHandlerUtil
{
public static void showParameterInfo(Editor editor)
{
final PsiFile psiFile = PsiDocumentManager.getInstance(editor.getProject()).getPsiFile(editor.getDocument());
AutoPopupController.getInstance(editor.getProject()).showParameterInfo(editor.getProject(), editor, psiFile, -1, null, true);
}
}
|
Java | UTF-8 | 11,088 | 1.703125 | 2 | [] | no_license | package com.iblood.fellow;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.iblood.R;
import com.iblood.base.BaseActivity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
public class YuYueActivity extends BaseActivity implements View.OnClickListener {
@BindView(R.id.dom_fanhui)
ImageView domFanhui;
@BindView(R.id.jiyangshijian_jiyang)
TextView jiyangshijianJiyang;
@BindView(R.id.kaishi_yuyue)
LinearLayout kaishiYuyue;
@BindView(R.id.zongshu_yuyue)
TextView zongshuYuyue;
@BindView(R.id.jiehuishijian_jiyang)
TextView jiehuishijianJiyang;
@BindView(R.id.jieshu_yuyue)
LinearLayout jieshuYuyue;
@BindView(R.id.img_yuyue)
ImageView imgYuyue;
@BindView(R.id.name_yuyue)
TextView nameYuyue;
@BindView(R.id.pingjia_yuyue)
TextView pingjiaYuyue;
@BindView(R.id.shanchu_yuyue)
ImageView shanchuYuyue;
@BindView(R.id.tianshu_yuyue)
TextView tianshuYuyue;
@BindView(R.id.qian_yuyue)
TextView qianYuyue;
@BindView(R.id.jian1_yuyue)
TextView jian1Yuyue;
@BindView(R.id.jia1_yuyue)
TextView jia1Yuyue;
@BindView(R.id.qian1_yuyue)
TextView qian1Yuyue;
@BindView(R.id.jian2_yuyue)
TextView jian2Yuyue;
@BindView(R.id.jia2_yuyue)
TextView jia2Yuyue;
@BindView(R.id.qian2_yuyue)
TextView qian2Yuyue;
@BindView(R.id.tianjia_yuyue)
LinearLayout tianjiaYuyue;
@BindView(R.id.liuyan_yuyue)
EditText liuyanYuyue;
@BindView(R.id.zongqian_yuyue)
TextView zongqianYuyue;
@BindView(R.id.queding_yuyue)
TextView quedingYuyue;
@BindView(R.id.tian1_yuyue)
EditText tian1Yuyue;
@BindView(R.id.tian2_yuyue)
EditText tian2Yuyue;
@BindView(R.id.heji_yuyue)
TextView hejiYuyue;
private int mYear;
private int mMonth;
private int mDay;
//开始时间
String days1;
//结束时间
String days2;
//寄养天数
private long days;
//洗澡次数
private int tian1;
//接送次数
private int tian2;
//天数费用
private double tianshuqian;
@Override
protected int getLayoutId() {
return R.layout.activity_yu_yue;
}
@Override
protected void initView() {
kaishiYuyue.setOnClickListener(this);
jieshuYuyue.setOnClickListener(this);
jian1Yuyue.setOnClickListener(this);
jia1Yuyue.setOnClickListener(this);
jian2Yuyue.setOnClickListener(this);
jia2Yuyue.setOnClickListener(this);
tianjiaYuyue.setOnClickListener(this);
shanchuYuyue.setOnClickListener(this);
quedingYuyue.setOnClickListener(this);
domFanhui.setOnClickListener(this);
//Activity的onCreate方法中获取当时的年 ,月,日
Calendar calendar = Calendar.getInstance();
mYear = calendar.get(Calendar.YEAR);
mMonth = calendar.get(Calendar.MONTH);
mDay = calendar.get(Calendar.DAY_OF_MONTH);
String trim1 = tian1Yuyue.getText().toString().trim();
String trim2 = tian2Yuyue.getText().toString().trim();
if (TextUtils.isEmpty(tian1Yuyue.getText())){
tian1 = 1;
tian2 = 1;
}else {
//获取洗澡次数
tian1 = Integer.parseInt(trim1);
//获取接送次数
tian2 = Integer.parseInt(trim2);
}
}
@Override
protected void initData() {
}
@Override
protected void initListener() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
/**
* 日期选择器对话框监听
*/
private DatePickerDialog.OnDateSetListener onDateSetListener1 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
if (mMonth + 1 < 10) {
if (mDay < 10) {
days1 = new StringBuffer().append(mYear).append("年").append("0").
append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
} else {
days1 = new StringBuffer().append(mYear).append("年").append("0").
append(mMonth + 1).append("月").append(mDay).append("日").toString();
}
} else {
if (mDay < 10) {
days1 = new StringBuffer().append(mYear).append("年").
append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
} else {
days1 = new StringBuffer().append(mYear).append("年").
append(mMonth + 1).append("月").append(mDay).append("日").toString();
}
}
jiyangshijianJiyang.setText(days1);
}
};
private DatePickerDialog.OnDateSetListener onDateSetListener2 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
if (mMonth + 1 < 10) {
if (mDay < 10) {
days2 = new StringBuffer().append(mYear).append("年").append("0").
append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
} else {
days2 = new StringBuffer().append(mYear).append("年").append("0").
append(mMonth + 1).append("月").append(mDay).append("日").toString();
}
} else {
if (mDay < 10) {
days2 = new StringBuffer().append(mYear).append("年").
append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
} else {
days2 = new StringBuffer().append(mYear).append("年").
append(mMonth + 1).append("月").append(mDay).append("日").toString();
}
}
jiehuishijianJiyang.setText(days2);
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
try {
Date d1 = df.parse(days1);
Date d2 = df.parse(days2);
//Date d2 = new Date(System.currentTimeMillis());//你也可以获取当前时间
long diff = d2.getTime() - d1.getTime();//这样得到的差值是微秒级别
days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
zongshuYuyue.setText(days + "晚");
tianshuYuyue.setText(days + "天");
if (days>0){
tianshuqian = days * 30.00;
qianYuyue.setText(days * 30 + "元");
hejiYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
zongqianYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
}else {
zongshuYuyue.setText(0 + "晚");
tianshuYuyue.setText(0 + "天");
tianshuqian = 0;
Toast.makeText(YuYueActivity.this, "日期不能为负数哟", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.kaishi_yuyue:
new DatePickerDialog(YuYueActivity.this, onDateSetListener1, mYear, mMonth, mDay).show();
break;
case R.id.jieshu_yuyue:
new DatePickerDialog(YuYueActivity.this, onDateSetListener2, mYear, mMonth, mDay).show();
break;
case R.id.jian1_yuyue:
if (tian1>1){
tian1-=1;
}
tian1Yuyue.setText(tian1+"");
qian1Yuyue.setText(tian1*60.00+"元");
hejiYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
zongqianYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
break;
case R.id.jia1_yuyue:
tian1+=1;
tian1Yuyue.setText(tian1+"");
qian1Yuyue.setText(tian1*60.00+"元");
hejiYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
zongqianYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
break;
case R.id.jian2_yuyue:
if (tian2>1){
tian2-=1;
}
tian2Yuyue.setText(tian2+"");
qian2Yuyue.setText(tian2*50.00+"元");
hejiYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
zongqianYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
break;
case R.id.jia2_yuyue:
tian2+=1;
tian2Yuyue.setText(tian2+"");
qian2Yuyue.setText(tian2*50.00+"元");
hejiYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
zongqianYuyue.setText(tianshuqian+tian1*60.00+tian2*50.00+"元");
break;
case R.id.tianjia_yuyue:
Toast.makeText(this, "请您先充值会员!", Toast.LENGTH_SHORT).show();
break;
case R.id.shanchu_yuyue:
Toast.makeText(this, "您确定要残忍删除?!", Toast.LENGTH_SHORT).show();
break;
case R.id.queding_yuyue:
postData();
if (days>0){
Intent intent = new Intent(YuYueActivity.this,SuccessActivity.class);
intent.putExtra("qian",tianshuqian+tian1*60.00+tian2*50.00+"元");
startActivity(intent);
}else {
Toast.makeText(YuYueActivity.this, "日期不能少哟", Toast.LENGTH_SHORT).show();
}
break;
case R.id.dom_fanhui:
finish();
break;
}
}
private void postData() {
}
}
|
PHP | UTF-8 | 1,328 | 2.640625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Api\V1\Auth;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\ApiController;
use Dingo\Api\Exception\ValidationHttpException;
class SignUpValidateController extends ApiController
{
/**
* Validation rules.
*
* @var array
*/
protected $rules = [
'username' => 'bail|required|string|between:5,32|alpha_num|unique:users,username',
'password' => 'bail|required|string|min:6|different:username',
'nickname' => 'bail|required|string|between:3,16',
'email' => 'bail|required|string|email|max:48|unique:users,email',
];
/**
* Validate the given field is valid or not.
*
* @param Request $request
*
* @return \Dingo\Api\Http\Response
*/
public function verify(Request $request)
{
if (! array_key_exists($request->input('field'), $this->rules)) {
$this->response->errorMethodNotAllowed();
}
$validator = Validator::make([$request->input('field') => $request->input('value')], [
$request->input('field') => $this->rules[$request->input('field')],
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors());
}
return $this->response->accepted();
}
}
|
C++ | UTF-8 | 1,975 | 2.609375 | 3 | [
"WTFPL"
] | permissive | #include "SelectiveRepeatRdtReceiver.h"
#include "Global.h"
SelectiveRepeatRdtReceiver::SelectiveRepeatRdtReceiver(int rcvWindowSz)
{
rcvBuffer = new Packet[rcvWindowSz];
rcvWindowSize = rcvWindowSz;
rcvBase = 0;
ackPkt.acknum = 0; //初始状态下,上次发送的确认包的确认序号为-1,使得当第一个接受的数据包出错时该确认报文的确认号为-1
ackPkt.checksum = 0;
ackPkt.seqnum = -1; //忽略该字段
for (int i = 0; i < Configuration::PAYLOAD_SIZE; i++) {
ackPkt.payload[i] = '.';
}
ackPkt.checksum = pUtils->calculateCheckSum(ackPkt);
}
SelectiveRepeatRdtReceiver::~SelectiveRepeatRdtReceiver()
{
delete[] rcvBuffer;
}
void SelectiveRepeatRdtReceiver::receive(const Packet& packet)
{
if (pUtils->calculateCheckSum(packet) == packet.checksum) {
pUtils->printPacket("[SR RECEIVER] packet received, receive window may be moved", packet);
rcvBuffer[packet.seqnum % rcvWindowSize] = packet;
if (packet.seqnum == rcvBase) {
Message msg;
while (rcvBuffer[rcvBase % rcvWindowSize].seqnum == rcvBase)
{
memcpy(msg.data, rcvBuffer[rcvBase % rcvWindowSize].payload, sizeof(rcvBuffer[rcvBase % rcvWindowSize].payload));
pns->delivertoAppLayer(RECEIVER, msg);
rcvBase++;
}
std::cout << "[SR RECEIVER] receive window moved, current receive window:" << std::endl << "[";
for (int i = 0; i < rcvWindowSize - 1; i++)
{
std::cout << rcvBase + i << " ";
}
std::cout << rcvBase + rcvWindowSize - 1<< "]" << std::endl;
}
ackPkt.acknum = packet.seqnum;
ackPkt.checksum = pUtils->calculateCheckSum(ackPkt);
pUtils->printPacket("[SR RECEIVER] sending ack packet", ackPkt);
pns->sendToNetworkLayer(SENDER, ackPkt);
}
}
|
Markdown | UTF-8 | 1,136 | 3.0625 | 3 | [] | no_license | ---
title: プッシュ通知機能
weight: 10
---
次の API を使用して、プッシュ通知受信時の処理を定義できます。
メソッド | 解説
-------|-------------------
[monaca.cloud.Push.setHandler()](#push-sethandler) | プッシュ通知の受信時の JavaScript ハンドラーを設定します。
## Push.setHandler()
プッシュ通知の受信時に呼び出す、プッシュ通知用のハンドラーを定義します。
{{<highlight javascript>}}
monaca.cloud.Push.setHandler(callback: Function) : void
{{</highlight>}}
**パラメーター**
パラメーター | 型 | 解説
-----|------|------------------
`callback` | 関数 | プッシュ通知を処理するコールバック関数です。第一引数に追加のデータを設定できます。
**戻り値**
- なし
**例**
次のサンプルコードでは、プッシュ通知から受け取ったデータを、`Console` ( コンソール ) に表示しています。
{{<highlight javascript>}}
monaca.cloud.Push.setHandler(function(data) {
console.log(data.item_a);
console.log(data.item_b);
});
{{</highlight>}}
|
PHP | UTF-8 | 4,808 | 2.890625 | 3 | [] | no_license | <?php
/**
* 提示操作信息的,并且跳转
* @param string $mes
* @param string $url
*/
function alertMes($mes,$url){
echo "<script type='text/javascript'>alert('{$mes}');location.href='{$url}';</script>";
}
//重定向链接并且输出漂亮的警告框
function redirect($mes,$url){
$url = $url."&mes=".$mes;
echo "<script type='text/javascript'>location.href='{$url}';</script>";
}
/**
* 截取文件扩展名
* @param string $filename
* @return string
*/
function getExt($filename){
return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
}
/**
* 产生唯一名称
* @param int $length
* @return string
*/
function getUniqidName($length=10){
return substr(md5(uniqid(microtime(true),true)),0,$length);
}
//几种样式的警告框 =。= 贼好看
function showSuccessMsg($mes){
echo '<div class="alert alert-success alert-dismissible text-center" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong></strong> '.$mes.' </div>';
}
function showWarningMsg($mes){
echo '<div class="alert alert-warning alert-dismissible text-center" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>警告!</strong> '.$mes.' </div>';
}
function showDangerMsg($mes){
echo '<div class="alert alert-danger alert-dismissible text-center" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>错误!</strong> '.$mes.' </div>';
}
function showInfoMsg($mes){
echo '<div class="alert alert-info alert-dismissible text-center" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>提示:</strong> '.$mes.' </div>';
}
//根据mes 显示不同警告框
function showAlertMes($mes){
switch ($mes) {
case 'CreateFileSuccess':
showSuccessMsg('文件创建成功!');
break;
case 'CreateFileFail':
showDangerMsg('文件创建失败!');
break;
case 'CreateFolderSuccess':
showSuccessMsg('文件夹创建成功!');
break;
case 'CreateFolderFail':
showDangerMsg('文件夹创建失败!');
break;
case 'FileExists':
showWarningMsg('文件已存在,请先重命名!');
break;
case 'IllegalName':
showWarningMsg('非法文件名!');
break;
case 'IllegalNameFolder':
showWarningMsg('非法文件夹名称!');
break;
case 'SameNameFile':
showWarningMsg('存在同名文件!');
break;
case 'SameNameFolder':
showWarningMsg('存在同名文件夹!');
break;
case 'RenameFileSuccess':
showSuccessMsg('文件重命名成功!');
break;
case 'RenameFileFail':
showDangerMsg('文件重命名失败!');
break;
case 'RenameFolderSuccess':
showSuccessMsg('文件夹重命名成功!');
break;
case 'RenameFolderFail':
showDangerMsg('文件夹重命名失败!');
break;
case 'DelFolderSuccess':
showSuccessMsg('删除文件夹成功!');
break;
case 'FileDeleteSuccess':
showSuccessMsg('删除文件成功!');
break;
case 'FileDeleteFail':
showDangerMsg('删除文件失败!');
break;
case 'NoneFileOrFolder':
showWarningMsg('没有文件或目录!');
break;
case 'CopyFileSuccess':
showSuccessMsg('文件复制成功!');
break;
case 'CopyFileFail':
showDangerMsg('文件复制失败!');
break;
case 'CutFileSuccess':
showSuccessMsg('文件剪切成功!');
break;
case 'CutFileFail':
showDangerMsg('文件剪切失败!');
break;
case 'DstFolderNotExist':
showWarningMsg('目标文件夹不存在!');
break;
case 'NotAFolder':
showWarningMsg('不是一个文件夹!');
break;
case "error:1":
$mes="超过了配置文件的大小!";
showWarningMsg($mes);
break;
case "error:2":
$mes="超过了表单允许接收数据的大小!";
showWarningMsg($mes);
break;
case "error:3":
$mes="文件部分被上传!";
showWarningMsg($mes);
break;
case "error:4":
$mes="没有文件被上传!";
showWarningMsg($mes);
break;
case "NotUploadByHttpPost":
$mes="文件不是通过HTTP POST方式上传上来的!";
showWarningMsg($mes);
break;
case "IllegalFileType":
showWarningMsg("非法文件类型!");
break;
case "FileOversize":
showWarningMsg("文件过大!");
break;
case 'UploadFileSuccess':
showSuccessMsg("文件上传成功!");
break;
case 'UploadFileFail':
showDangerMsg("文件上传失败!");
break;
default:
if($mes){
showInfoMsg($mes);
}
break;
}
}
|
C++ | UTF-8 | 723 | 2.53125 | 3 | [] | no_license | #include<stdio.h>
#include<queue>
#include <string.h>
using namespace std;
void shortestpath()
{
int adj[5][5]={{0,1,0,0,1},
{1,0,1,1,1},
{0,1,0,1,0},
{0,1,1,0,1},
{1,1,0,1,0}};
int edges=5;
int root=0;
queue<int> st;
st.push(root);
int distance[edges];
memset(distance,-1,sizeof(int)*5);
distance[root]=0;
while(!st.empty())
{
int c=st.front();
st.pop();
for(int i=0;i<edges;i++)
{
if(distance[i]==-1&&adj[c][i]==1)
{distance[i]=distance[c]+1;
st.push(i);}
}
}
for(int i=0;i<edges;i++)
printf("%d ",distance[i]);
printf("\n");
}
int main()
{
shortestpath();
}
|
JavaScript | UTF-8 | 4,533 | 3 | 3 | [] | no_license | "use strict";
// This is the global list of the stories, an instance of StoryList
let storyList;
/** Get and show stories when site first loads. */
async function getAndShowStoriesOnStart() {
storyList = await StoryList.getStories();
$storiesLoadingMsg.remove();
putStoriesOnPage();
}
/**
* A render method to render HTML for an individual Story instance
* - story: an instance of Story
*
* Returns the markup for the story.
*/
function generateStoryMarkup(story) {
const hostName = story.getHostName();
let s = `<li id="${story.storyId}">
<a href="${story.url}" target="a_blank" class="story-link">
${story.title}
</a>
<small class="story-hostname">(${hostName})</small>
<small class="story-author">by ${story.author}</small>
<small class="story-user">posted by ${story.username}</small>
${getIcon(story.storyId)}
<br /.
</li>
`;
return $(s);
}
// for displaying an item as a favorite or not a favorite
function getIcon(storyId, withDiv = true){
if(currentUser){
let s = (withDiv) ? '<div class="favoritable">' : '';
if(currentUser.favorites.find(favorite => favorite.storyId === storyId)){
s += '<i class="fas fa-heart"></i>'
}
else{
s += '<i class="far fa-heart"></i>'
}
return s += (withDiv) ? '</div>' : '';
}
else{
return '';
}
}
/** Gets list of stories from server, generates their HTML, and puts on page. */
function putStoriesOnPage() {
console.debug("putStoriesOnPage");
$allStoriesList.empty();
// loop through all of our stories and generate HTML for them
for (let story of storyList.stories) {
const $story = generateStoryMarkup(story);
$allStoriesList.append($story);
}
$allStoriesList.show();
}
/*
Get's User static async loginViaStoredCredentials(token, username) {
await checkForRememberedUser()
*/
async function submitStory(evt) {
evt.preventDefault();
if (currentUser) {
let storyData = buildStoryData();
let story = await StoryList.addStory(currentUser, storyData);
generateStoryMarkup(story).prependTo('#all-stories-list')
resetForm();
}
}
$submitForm.on('submit', submitStory);
function buildStoryData(){
let author = $('input[name="author"]').val();
let title = $('input[name="title"]').val();
let url = $('input[name="url"]').val();
return { author, title, url };
}
function resetForm(){
$('#form-story input').val('');
$formSection.hide();
}
async function toggleFavorite({target}){
let parent = target.parentElement;
if(parent.classList.contains('favoritable')){
// get storyId and attempt to find in user's favorites
let storyId = parent.parentElement.id;
let story = currentUser.favorites.find(story => story.storyId === storyId);
if(story){
await currentUser.deleteFavorite(story);
}
else{
// find story and add it to user's favorites
story = storyList.stories.find(story => story.storyId === storyId)
await currentUser.addFavorite(story);
}
// toggle icon on page
parent.innerHTML = getIcon(storyId, false);
}
}
$allStoriesList.click(toggleFavorite);
function loadFavoriteStories(){
$allStoriesList.html('');
for(let favorite of currentUser.favorites){
let $li = generateStoryMarkup(favorite);
$allStoriesList.append($li);
}
$formSection.hide();
}
$navFavorites.click(loadFavoriteStories);
async function loadMySubmissions(){
let stories = await getMyStories();
$allStoriesList.html('');
for(let story of stories){
let $li = generateStoryMarkup(story);
$li.get(0).querySelector('.favoritable').remove();
$('<div class="deletable"><i class="fas fa-backspace"></i></div>').appendTo($li);
$allStoriesList.append($li);
}
$formSection.hide();
}
$navMySubmissions.click(loadMySubmissions);
async function getMyStories(){
let stories = await StoryList.getStories();
stories = stories.stories;
return stories.filter(story => story.username === currentUser.username);
}
async function deleteHandler({target}){
if(target.parentElement.classList.contains('deletable')){
let li = target.parentElement.parentElement;
let storyId = li.id;
// remove from api
await StoryList.deleteStory(currentUser, storyId);
// remove li from page
li.remove();
// remove story from storyList
storyList.removeById(storyId);
}
}
$allStoriesList.click(deleteHandler); |
Python | UTF-8 | 3,856 | 3.125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from __future__ import division
import pandas as pd
import matplotlib.pyplot as plt
from pandas import DataFrame, Series
data = pd.read_csv('./1000-out2.csv', header = None)
data.index = data[0]
import itertools
# Fk−1 × Fk−1 method: Assumes F is in lexicographic order. Return candidates in lexicographic order.
# F is list of list, k is the length: length of the item in F plus 1
def generate_candidates(F, k):
length_Fk_1 = len(F[0])
if not all([len(Fk_1_list_item) == length_Fk_1 for Fk_1_list_item in F]):
print 'length of the item in the Fk-1 is not the same.'
raise Exception
else:
if k != len(F[0]) + 1:
print 'k is not the length of the item in Fk-1 plus 1.'
raise Exception
else:
Fk_2_list = [Fk_1_list_item[0: len(Fk_1_list_item) - 1] for Fk_1_list_item in F]
Fk_2_list_set = list(set(tuple(Fk_2_list_item) for Fk_2_list_item in Fk_2_list if Fk_2_list.count(Fk_2_list_item) > 1))
# print Fk_2_list_set
Fk_2_remain_list = []
for Fk_2_tuple_item in Fk_2_list_set:
remain_list = []
for Fk_1_list_item in F:
if Fk_1_list_item[0: len(Fk_1_list_item) - 1] == list(Fk_2_tuple_item):
remain_list.append(Fk_1_list_item[-1])
Fk_2_remain_list.append(remain_list)
# print Fk_2_remain_list
candidate_result = []
for list_item, remain_list in zip(Fk_2_list_set, Fk_2_remain_list):
for remain_tuple in list(itertools.combinations(remain_list, 2)):
candidate_result.append(list(list_item) + (list(remain_tuple)))
order_candidate_result = sorted(candidate_result)
return order_candidate_result
def prune_candidates(F, C, k):
prune_candidate_list = []
for candidate_item in C:
# print list(itertools.combinations(candidate_item, k - 1))
for item in list(itertools.combinations(candidate_item, k - 1)):
if list(item) not in F:
prune_candidate_list.append(candidate_item)
break
# print prune_candidate_list
return prune_candidate_list
def support_count(D, minsupport, C):
result_minimum_support_list = []
total_count = len(D.index)
for candidate_list in C:
count = 0
# print candidate_list
for index in D.index:
if all([(D.ix[index, candidate_item] == 1) for candidate_item in candidate_list]):
# print index
count +=1
if count/ total_count >= minsupport:
result_minimum_support_list.append(candidate_list)
# print result_minimum_support_list
return result_minimum_support_list
def find_frequent_itemsets(D, minsupport):
F_1_list = []
for F_1_list_item in D.columns:
empty_list = []
empty_list.append(F_1_list_item)
F_1_list.append(empty_list)
# print F_1_list
F_1_frequent_list = support_count(D, minsupport, F_1_list)
F_k = F_1_frequent_list
frequent_itemset = F_k
while(len(F_k) != 0):
k = len(F_k[0])
candidate_list = generate_candidates(F_k, k + 1)
prune_candidate_list = prune_candidates(F_k, candidate_list, k + 1)
current_result_candidate_list = [candidate_item for candidate_item in candidate_list if candidate_item not in prune_candidate_list]
final_result_candidate_list = support_count(D, minsupport, current_result_candidate_list)
frequent_itemset += final_result_candidate_list
F_k = final_result_candidate_list
print 'frequent itemsets:\n', frequent_itemset
return frequent_itemset
# test
find_frequent_itemsets(data[data.columns[1:len(data.columns)]], 0.04)
|
Python | UTF-8 | 1,696 | 3.734375 | 4 | [] | no_license |
'''
ARS Gems Store sells different varieties of gems to its customers.
Write a Python program to calculate the bill amount to be paid by a customer based on the list of gems and quantity purchased. Any purchase with a total bill amount above Rs.30000 is entitled for 5% discount. If any gem required by the customer is not available in the store, then consider total bill amount to be -1.
Assume that quantity required by the customer for any gem will always be greater than 0.
Perform case-sensitive comparison wherever applicable.
'''
#PF-Assgn-23
def calculate_bill_amount(gems_list, price_list, reqd_gems,reqd_quantity):
bill_amount=0
#Write your logic here
for i in reqd_gems:
if i in gems_list:
ind = gems_list.index(i)
indr = reqd_gems.index(i)
gem_price = price_list[ind]
gem_quantity = reqd_quantity[indr]
gem_amount = gem_price*gem_quantity
bill_amount = bill_amount + gem_amount
else:
return -1
if bill_amount>30000:
discount = bill_amount*5/100
bill_amount = bill_amount - discount
return bill_amount
#List of gems available in the store
gems_list=["Emerald","Ivory","Jasper","Ruby","Garnet"]
#Price of gems available in the store. gems_list and price_list have one-to-one correspondence
price_list=[1760,2119,1599,3920,3999]
#List of gems required by the customer
reqd_gems=["Ivory","Emerald","Garnet"]
#Quantity of gems required by the customer. reqd_gems and reqd_quantity have one-to-one correspondence
reqd_quantity=[3,10,12]
bill_amount=calculate_bill_amount(gems_list, price_list, reqd_gems, reqd_quantity)
print(bill_amount) |
C++ | UTF-8 | 1,874 | 3.5625 | 4 | [] | no_license | #ifndef ALG_HPP
#define ALG_HPP
#include <cmath>
template<class Semi>
class alg_vector {
public:
alg_vector(Semi x, Semi y): _x(x), _y(y) {
}
alg_vector( const alg_vector & ) = default;
alg_vector & operator=( const alg_vector & ) = default;
Semi x() const {
return _x;
}
Semi y() const {
return _y;
}
alg_vector operator*(const Semi& scalar) const {
return alg_vector(this->_x*scalar, this->_y*scalar);
}
alg_vector operator+(const alg_vector& nd) const {
return alg_vector(this->_x+nd._x, this->_y+nd._y);
}
alg_vector operator-(const alg_vector& nd) const {
return alg_vector(this->_x-nd._x, this->_y-nd._y);
}
private:
Semi _x;
Semi _y;
};
template<class Semi>
class point {
public:
point(Semi x, Semi y): _x(x), _y(y) {
}
point( const point & ) = default;
Semi x() const {
return _x;
}
Semi y() const {
return _y;
}
point operator+(const point& nd) const {
return point(this->_x+nd.x(), this->_y+nd.y());
}
point operator-(const point& nd) const {
return point(this->_x-nd.x(), this->_y-nd.y());
}
point operator+(const alg_vector<Semi>& nd) const {
return point(this->_x+nd.x(), this->_y+nd.y());
}
point operator-(const alg_vector<Semi>& nd) const {
return point(this->_x-nd.x(), this->_y-nd.y());
}
template<class Semi2>
explicit operator point<Semi2>() const {
return point<Semi2>(static_cast<Semi2>(_x), static_cast<Semi2>(_y));
}
private:
Semi _x;
Semi _y;
};
template<class Semi>
Semi d_to_2(const point<Semi>& st, const point<Semi>& nd) {
Semi x_diff = st.x() - nd.x();
Semi y_diff = st.y() - nd.y();
return x_diff*x_diff + y_diff*y_diff;
}
template<class Semi>
double abs_to_2(const alg_vector<Semi> & v) {
return dot(v,v);
}
template<class Semi>
Semi dot(const alg_vector<Semi> & st, const alg_vector<Semi> & nd) {
return st.x()*nd.x() + st.y()*nd.y();
}
#endif
|
Java | UTF-8 | 2,201 | 2.15625 | 2 | [] | no_license | package gov.nist.hit.elr.aphl.plugin.cs;
import gov.nist.hit.elr.plugin.utils.EntityIdentifier;
import hl7.v2.instance.Element;
import hl7.v2.instance.Query;
import hl7.v2.instance.Simple;
import scala.collection.Iterator;
import scala.collection.immutable.List;
public class ELR_21_1 {
private static String EntityIdentifier = "PHLabReport-NoAck";
private static String NamespaceID = "phLabResultsELRv251";
private static String UniversalID = "2.16.840.1.113883.9.11";
private static String UniversalIDType = "ISO";
/**
* ARLN-21: One occurrence of MSH-21 SHALL be valued
* 'PHLabReport-NoAck^phLabResultsELRv251^2.16.840.1.113883.9.11^ISO'
*/
/**
*
* @param e MSH context
* @return
*/
public boolean assertion(Element e) {
List<Element> MSH21List = Query.query(e, "21[*]").get();
Iterator<Element> it = MSH21List.iterator();
java.util.List<EntityIdentifier> values = new java.util.ArrayList<EntityIdentifier>();
while (it.hasNext()) {
Element next = it.next();
List<Simple> MSH21_1List = Query.queryAsSimple(next, "1[1]").get();
List<Simple> MSH21_2List = Query.queryAsSimple(next, "2[1]").get();
List<Simple> MSH21_3List = Query.queryAsSimple(next, "3[1]").get();
List<Simple> MSH21_4List = Query.queryAsSimple(next, "4[1]").get();
String MSH21_1 = MSH21_1List.size() > 0 ? MSH21_1List.apply(0).value().raw() : "";
String MSH21_2 = MSH21_2List.size() > 0 ? MSH21_2List.apply(0).value().raw() : "";
String MSH21_3 = MSH21_3List.size() > 0 ? MSH21_3List.apply(0).value().raw() : "";
String MSH21_4 = MSH21_4List.size() > 0 ? MSH21_4List.apply(0).value().raw() : "";
EntityIdentifier MSH21 = new EntityIdentifier(MSH21_1, MSH21_2, MSH21_3, MSH21_4);
values.add(MSH21);
}
return check(values);
}
public boolean check(java.util.List<EntityIdentifier> values) {
EntityIdentifier expected =
new EntityIdentifier(EntityIdentifier, NamespaceID, UniversalID, UniversalIDType);
if (values == null || values.size() == 0) {
return false;
}
long count = values.stream().filter(e -> e.equals(expected)).count();
return count == 1;
}
}
|
Java | UTF-8 | 804 | 2.578125 | 3 | [] | no_license | package de.embots.touchflow.module.implementation.helpers.warp;
import de.embots.touchflow.module.Globals;
import de.embots.touchflow.module.implementation.modify.Warp;
public class EndWarp implements WarpFunction {
double n;
@Override
public double applyFunction(double in) {
if (in <0 || in > 1){
if (Globals.isDebug) {
System.err.println("Warning: Warp function called with illegal input:" + in);
}
}
return Math.pow(in, n);
}
@Override
public void setIntensity(double intensity) {
// TODO Auto-generated method stub
if(intensity >=1){
n=(intensity);
}
}
@Override
public double getIntensity() {
// TODO Auto-generated method stub
return n;
}
@Override
public int returnModeNumber() {
// TODO Auto-generated method stub
return Warp.Mode_End;
}
}
|
Java | UTF-8 | 809 | 2.09375 | 2 | [] | no_license | package com.rohit.gitrepoloader.views;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by oust on 4/17/18.
*/
public class CustomTvRegular extends TextView {
public CustomTvRegular(Context context) {
super(context);
}
public CustomTvRegular(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomTvRegular(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init(Context context) {
Typeface customFont = FontCache.getTypeface("Crimson-Roman.otf", context);
setTypeface(customFont);
}
}
|
C# | UTF-8 | 499 | 2.640625 | 3 | [] | no_license | namespace AIGames.FourInARow.TheDaltons
{
public abstract class SearchTreeNode : ISearchTreeNode
{
protected SearchTreeNode(Field field, byte depth, int score)
{
Field = field;
Depth = depth;
Score = score;
}
public Field Field { get; private set; }
public byte Depth { get; private set; }
public int Score { get; protected set; }
public abstract void Add(MoveCandidates candidates);
public abstract int Apply(byte depth, ISearchTree tree, int alpha, int beta);
}
}
|
Python | UTF-8 | 1,262 | 2.984375 | 3 | [] | no_license | class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
class Sequence():
def __init__(self, pulser):
self.pulser = pulser
self.vars = {}
self.parameters = None
def setVariables(self, **input):
#make sure no extraneous keys
requiredKeys = self.requiredVars.keys()
for key in input.keys():
if key not in requiredKeys: raise Exception ("Provided key {} is not required by the sequence".format(key))
#assign keys
for name in requiredKeys:
if name in input.keys():
value = input[name]
else:
value = self.requiredVars[name][3]
print 'Assigning key {0} to the default value {1}'.format(name, value)
#error checking
if type(value) != self.requiredVars[name][0]: raise Exception ('Wrong type for variable {}'.format(name))
if not (self.requiredVars[name][1] <= value <= self.requiredVars[name][2]): raise Exception ('Out of allowed range: {}'.format(name))
self.vars[name] = value
#create a helper class for keeping track of variables
self.parameters = Bunch(**self.vars)
def defineSequence(self):
pass |
Java | UTF-8 | 887 | 2.34375 | 2 | [
"MIT"
] | permissive | package pkg;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class HelloFxmlController
{
@FXML
// The reference of inputText will be injected by the FXML loader
private TextField txtMasukan;
// The reference of outputText will be injected by the FXML loader
@FXML
private TextArea taHasilInput;
// location and resources will be automatically injected by the FXML loader
@FXML
private URL location;
@FXML
private ResourceBundle resources;
// Add a public no-args constructor
public HelloFxmlController()
{
}
@FXML
private void initialize()
{
}
@FXML
private void printOutput()
{
taHasilInput.setText(txtMasukan.getText());
}
}
|
Swift | UTF-8 | 3,115 | 3.28125 | 3 | [] | no_license | //
// AlienView.swift
// drawing
//
// Created by Kate Baumstein on 3/1/21.
//
import Foundation
import UIKit
class GameView: UIView{
var ballx = 0
var bally = 20
var linex = 0
var liney = 300
var ballMove = false
var count = 0
var finaly = 0
var random = 300
var speed = 3
var level = 0
var updateLevel = false
var reset = false
@IBOutlet weak var directionsLabel: UILabel!
@IBOutlet weak var levelLabel: UILabel!
@IBOutlet weak var resetButton: UIButton!
override func draw(_ rect: CGRect) {
//line at a random y within bounds of UIView
linex = Int(self.bounds.maxX) - 100
let drect = CGRect(x: linex , y: liney, width: 100, height: 10)
let bpath: UIBezierPath = UIBezierPath(rect: drect)
UIColor.yellow.set()
UIRectFill(drect)
var cpath = UIBezierPath()
ballx = (Int(self.bounds.maxX ) / 2) - 12
cpath = UIBezierPath(ovalIn: CGRect(x:ballx , y: bally, width: 25, height: 25))
UIColor.yellow.setStroke()
UIColor.red.setFill()
cpath.lineWidth = 5
cpath.stroke()
cpath.fill()
}
@IBAction func clickResetButton(sender: UIButton){
count = 0
level = 0
bally = 20
}
@objc func update(){ //do collision detection here
print("updating")
if(count > 2){
print("reset ball")
bally = 20
count = 0
if(updateLevel == true){
level += 1
updateLevel = false
}
}
levelLabel.text = "Level: " + String(level)
if(count == 0 ){
liney = random
directionsLabel.text = "Click anywhere on the screen to begin. \nClick to try to stop the ball as close as you can to the line"
}
if(count == 2 ) {
if(finaly < liney + 15 && finaly > liney - 15){
directionsLabel.text = "Congratulations! You are moving onto the next level \nClick to try again"
updateLevel = true
levelLabel.text = "Level: " + String(level+1)
}
else{
directionsLabel.text = "You did not stop the ball close enough to the line. \nClick to try again"
}
}
else if(count % 2 == 1){
directionsLabel.text = ""
bally += speed + level
if(bally > Int(self.bounds.maxY)){
count = 2
}
}
setNeedsDisplay() //calls draw function (like a flag)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touched")
for t in touches {
let point = t.location(in: self)
count += 1
finaly = bally
random = Int.random(in: Int(self.bounds.minY) + 70 ... Int(self.bounds.maxY) - 70)
// shapex = Int(point.x)
// shapey = Int(point.y)
}
}
}
|
TypeScript | UTF-8 | 1,867 | 3.125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* A base class of Tweakpane API events.
*/
export class TpEvent {
/**
* The event dispatcher.
*/
public readonly target: unknown;
/**
* @hidden
*/
constructor(target: unknown) {
this.target = target;
}
}
/**
* An event class for value changes of input bindings.
* @template T The type of the value.
*/
export class TpChangeEvent<T> extends TpEvent {
/**
* The preset key of the event target.
*/
public readonly presetKey?: string;
/**
* The value.
*/
public readonly value: T;
/**
* The flag indicating whether the event is for the last change.
*/
public readonly last: boolean;
/**
* @hidden
*/
constructor(target: unknown, value: T, presetKey?: string, last?: boolean) {
super(target);
this.value = value;
this.presetKey = presetKey;
this.last = last ?? true;
}
}
/**
* An event class for value updates of monitor bindings.
* @template T The type of the value.
*/
export class TpUpdateEvent<T> extends TpEvent {
/**
* The preset key of the event target.
*/
public readonly presetKey: string;
/**
* The value.
*/
public readonly value: T;
/**
* @hidden
*/
constructor(target: unknown, value: T, presetKey: string) {
super(target);
this.value = value;
this.presetKey = presetKey;
}
}
/**
* An event class for folder.
*/
export class TpFoldEvent extends TpEvent {
/**
* The current state of the folder expansion.
*/
public readonly expanded: boolean;
/**
* @hidden
*/
constructor(target: unknown, expanded: boolean) {
super(target);
this.expanded = expanded;
}
}
/**
* An event class for tab selection.
*/
export class TpTabSelectEvent extends TpEvent {
/**
* The selected index of the tab item.
*/
public readonly index: number;
/**
* @hidden
*/
constructor(target: unknown, index: number) {
super(target);
this.index = index;
}
}
|
Markdown | UTF-8 | 5,762 | 3.40625 | 3 | [] | no_license | ## 摘要
安装请看上一篇[Sublime Text—安装](http://www.cnblogs.com/easy-blue/p/5148596.html),和[sublime自带快捷键](http://www.cnblogs.com/easy-blue/p/5809760.html)一起用,写html简直快的飞起。
下面整理的是常用的,完整的可看[emmet官方文档][1]。
<br>
## 一、生成标签
### 1.快速生成文档结构
- `!`或`html:5`,快速生成 HTML5 结构(都需要再按tab键)
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
```
- `html:xt` 生成 HTML4 过渡型
- `html:4s` 生成 HTML4 严格型
<br>
### 2.生成带 id 的元素
标签 # ID名,如:`div#header`
```
<div id="header"></div>
```
<br>
### 3.生成带 class 的元素
标签 . 类名,如:`div.title`
```
<div class="title"></div>
```
<br>
### 4.生成后代元素:>
如:`nav>ul>li`
```
<nav>
<ul>
<li></li>
</ul>
</nav>
```
<br>
### 5.生成兄弟元素:+
如:`div+p+div`
```
<div></div>
<p></p>
<div></div>
```
<br>
### 6.生成上级元素:^
如:`p^div`
```
<p></p>
<div></div>
```
<br>
### 7.重复生成多个元素:*
如:`ul>li*5`
```
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
```
<br>
### 8.生成带自定义属性:[attr]
如:`div[value=1] `
```
<div value="1"></div>
```
<br>
### 9.生成带文本内容:{}
如:`a{Click me}`
```
<a href="">Click me</a>
```
<br>
### 10.加编号:$
- 从1开始:加$
如:`div.item${$$}*3`
```
<div class="item1">01</div>
<div class="item2">02</div>
<div class="item3">03</div>
```
- 倒序: $ 后面增加 @-
如:`div.item$@-{$$@-}*3`
```
<div class="item3">03</div>
<div class="item2">02</div>
<div class="item1">01</div>
```
- 指定序号:可以使用 @N
如:`div.item$@4{$$@4}*3`
```
<div class="item4">04</div>
<div class="item5">05</div>
<div class="item6">06</div>
```
<br>
### 11.分组:()
如:`(ul>ol)*3 `
```
<ul>
<ol></ol>
</ul>
<ul>
<ol></ol>
</ul>
<ul>
<ol></ol>
</ul>
```
<br>
### 12.来个综合案例
`table#tab[value=1].a>tr*3>(td{$$}>span)*3`
```
<table id="tab" value="1" class="a">
<tr>
<td>01<span></span></td>
<td>02<span></span></td>
<td>03<span></span></td>
</tr>
<tr>
<td>01<span></span></td>
<td>02<span></span></td>
<td>03<span></span></td>
</tr>
<tr>
<td>01<span></span></td>
<td>02<span></span></td>
<td>03<span></span></td>
</tr>
</table>
```
<br>
## 二、生成css
css样式多,缩写自然也很多,列举常用的举一反三即可。
其中css缩写是采用模糊搜索匹配的,比如ov:h == ov-h == ovh == oh。
- w10 `width: 10px;` w10p `width: 10%;` w10e `width: 10em;` w10x `width: 10xe;`
- h10 `height: 10px;`
- por `position: relative;` poa `position: absolute;`
- fll `float: left;` fr `float: right;`
- dt `display: table;` db `display: block;` dib `display: inline-block;`
- ovy `overflow-y: hidden;`
- cb `clear: both;`
- mt `margin-top: ;` mb `margin-bottom: ;`
- pt `padding-top: ;` pb `padding-bottom: ;`
- tac `text-align: center;`
- lh `line-height:;`
- tsn `text-shadow: none;`
- tja `text-justify: auto;`
- c `color: #000;` cr `color: rgb(0, 0, 0);` cra `color: rgba(0, 0, 0, .5);`
- op `opacity: ;`
- cnt `content: '';`
- ol `outline: ;`
- bd+ `border: 1px solid #000;` bdb+ `border-bottom: 1px solid #000;`
- bd2px#333s `border: 2px #333 solid;`
<br>
## 三、快捷键
如果没作用请检查快捷键是否冲突
- 快速生成包裹标签:Ctrl+Shift+G
只有文本没有结构时,如下
```
首页
简介
动态
```
选中文本按快捷键Ctrl+Shift+G,再弹出的:Enter Wrap Abbreviation(输入扩展缩写)中输入`nav>ul>li.item$*>a`就会生成
```
<nav>
<ul>
<li class="item1"><a href="">首页</a></li>
<li class="item2"><a href="">简介</a></li>
<li class="item3"><a href="">动态</a></li>
</ul>
</nav>
```
如果原先的文本带编号,不想要则可以在上面的基础上加`|t`,`nav>ul>li.item$*>a|t`即可生成如上结果。
```
1首页
2简介
3动态
```
- 自动添加/更新图片尺寸:ctrl+U
光标移到标签上的任意位置,按下快捷键`ctrl+U`即可。
```
<img src="img/x1.png" />
<img src="img/x1.png" width="100" height="200" />
```
- 删除标签:shift+ctrl+;
- 定位到上个编辑点:ctrl+alt+left
- 定位到下个编辑点:ctrl+alt+right
- 选中下一项:shift+ctrl+.
- 加/减1:ctrl+up/ctrl+down
- 加/减10:shift+alt+up/shift+alt+down
- 展开缩写:ctrl+e(和tab键作用相同)
- 重命名标签(rename_tag):ctrl+shift+'
- 更换标签(update_as_you_type):ctrl+Shift+U
- 匹配标签对:ctrl+alt+j
<br>
## 四、生成测试文本
输入`lorem`再按tab会随机生成一段英文,默认是生成30个单词,可以加上数字控制单词数量,如`lorem5`。
```
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis incidunt, expedita voluptates ratione praesentium error a accusamus corporis deleniti. Cum, debitis id, in rem exercitationem at voluptatum illum minima corporis!
```
```
Lorem ipsum dolor sit amet.
```
<br>
### 2017.09.18补充内容
如上输入`lorem`再按tab扩展的代码是已经设置好的,sublime还提供**自定义代码片段**的功能,详细内容请移步[Sublime Text3—自定义代码片段(Code Snippets)](http://www.cnblogs.com/easy-blue/p/7515088.html)。
<br>
## 参考
[emmet官方文档][1]
<br>
[1]: https://docs.emmet.io/cheat-sheet/ "emmet官方文档"
**掘金:**[Sublime Text3—常用插件Emmet](https://juejin.im/post/59c369da5188256c6c3e33a2)
**简书:**[Sublime Text3—常用插件Emmet](http://www.jianshu.com/p/1d9121ef8277)
**博客园:**[Sublime Text3—常用插件Emmet](http://www.cnblogs.com/easy-blue/p/6617852.html) |
Ruby | UTF-8 | 1,260 | 2.59375 | 3 | [] | no_license | require 'sinatra'
require 'json'
require 'commit_parser'
class API < Sinatra::Base
# --------- application config block --------- #
configure do
set :root, File.dirname(__FILE__)
end
# -------------------------------------------- #
helpers do
def data_correct?(data)
data["token"] && data["payload"] && data["payload"]["commits"]
rescue
false
end
end
get '/' do
status 200
end
post '/project/:project_id' do # github-services
# puts "\n* Got POST message from github-services * project_id: #{params[:project_id]}"
# puts "\nJSON:\n" + params[:data]
# puts "\nParsed:\n" + JSON.parse(params[:data]).inspect
if params[:project_id] and data = JSON.parse(params[:data]) and data_correct?(data)
last_commit = data["payload"]["commits"].last # get last commit
# parse commit message
cp = CommitParser.new(last_commit)
# this is just for testing
status 200
puts cp.to_json
content_type :json
cp.to_json # return object attributes as hash (for rspec tests)
else
status 400 # incorrect payload
end
end
post '/push' do
# payload = JSON.parse(params[:payload])
# puts "payload: #{payload}"
status 200
end
end
|
Java | UTF-8 | 263 | 2.109375 | 2 | [] | no_license | package com.virtusa.stockbookproductservice.exception;
public class ProductNameAlreadyExistException extends RuntimeException{
private static final long serialVersionUID = 1L;
public ProductNameAlreadyExistException(String message) {
super(message);
}
}
|
Swift | UTF-8 | 2,816 | 2.796875 | 3 | [] | no_license | //
// softwareDevelopmentViewController.swift
// FInalProjectApp
//
// Created by Ioana Nedelcu on 6/8/21.
//
import UIKit
import BLTNBoard
class softwareDevelopmentViewController: UIViewController {
private lazy var boardManager: BLTNItemManager = {
let item = BLTNPageItem(title: "Clean Code")
item.descriptionText = "Clean Code is divided into three parts. The first describes the principles, patterns, and practices of writing clean code. The second part consists of several case studies of increasing complexity. Each case study is an exercise in cleaning up code―of transforming a code base that has some problems into one that is sound and efficient. The third part is the payoff: a single chapter containing a list of heuristics and “smells” gathered while creating the case studies. The result is a knowledge base that describes the way we think when we write, read, and clean code."
return BLTNItemManager(rootItem: item)
}()
private lazy var boardManager1: BLTNItemManager = {
let item = BLTNPageItem(title: "The Big Score")
item.descriptionText = "One of the first reporters on the tech industry beat at the San Jose Mercury-News, Michael S. Malone recounts the feverish efforts of young technologists and entrepreneurs to build something that would change the world--and score them a big payday. Starting with the birth of Hewlett-Packard in the 1930s, Malone illustrates how decades of technological innovation laid the foundation for the meteoric rise of the Valley in the 1970s. Drawing on exclusive, unvarnished interviews, Malone punctuates this history with incisive profiles of tech’s early luminaries--including Nobelist William Shockley and Apple's Steve Jobs--when they were struggling entrepreneurs working 18-hour days in their garages. And he plunges us into the darker side of the Valley, where espionage, drugs, hellish working conditions, and shocking betrayals shaped the paths for winners and losers in a booming industry."
return BLTNItemManager(rootItem: item)
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func bt1(_ sender: UIButton) {
boardManager.showBulletin(above: self)
}
@IBAction func bt2(_ sender: UIButton) {
boardManager1.showBulletin(above: self)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
Markdown | UTF-8 | 2,952 | 2.671875 | 3 | [] | no_license | # Looker Content Manager

## Description
This Custom Action performs bulk actions on content, leveraging the Looker API and the System Activity model. It will enable you to select various actions (e.g. Favorite / Unfavorite, Copy / Move to Space, Archive / Restore from Trash, Run Scheduled Plan) on a list of content IDs. This may be handy when you want to:
- Archive all content that uses a specific model
- Move all content to a space that was created by a specific users
- Assign favorite content to a given user
- Rerun all scheduled plans that have failed
## How to Use
1. Use any Explore to filter to a list of content IDs
2. Send or schedule the data to Custom Action
3. Select the **action** you want to execute and the **content type** (Dashboard, Look, or Schedule). Enter the **column name** which should be used as the content ID (e.g. `dashboard.id` or `look.id` or `scheduled_plan.id`) and the **variable ID** if required.
## Steps to Deploy with Serverless
This action was built using the Serverless framework. It was deployed as a Google Cloud Function, however any of providers listed [here](https://serverless.com/framework/docs/providers/) should work. Check the **serverless.yml reference pages** to know what parameters to tweak.
Before starting the steps below, ensure you have [Serverless installed](https://serverless.com/framework/docs/providers/google/guide/installation/) and Google Cloud [credentials](https://serverless.com/framework/docs/providers/google/guide/credentials/) set up.
1. Rename `serverless_example.yml` to `serverless.yml`
2. Set the provider details:
- `region` - region to deploy function, e.g. europe-west1
- `project` - the name of your google cloud project
- `credentials` - the path to gcf json credentials file, e.g. ~/PATH/TO/GCF_CREDENTIALS.json
3. Set the envirnment variables, refer to [Looker SDK docs](https://github.com/looker-open-source/sdk-codegen#environment-variable-configuration) for guidance on SDK variables:
- `EXPECTED_LOOKER_SECRET_TOKEN` - can be any random string. This will be used as an auth token set in /admin/actions
- `ACTION_NAME` - unique name for the action, e.g. looker-content-manager
- `ACTION_LABEL` - human-readable label to appear in Looker, e.g. Looker Content Manager
- `CALLBACK_URL_PREFIX` - specify before deploying, e.g. https://REGION_NAME-YOUR_PROJECT_NAME.cloudfunctions.net
- `LOOKERSDK_API_VERSION` - use "3.1"
- `LOOKERSDK_BASE_URL` - base url for Looker instance, e.g. https://MY_LOOKER.com:19999
- `LOOKERSDK_CLIENT_ID`- API3 credentials client_id
- `LOOKERSDK_CLIENT_SECRET` - API3 credentials client_secret
- `LOOKERSDK_VERIFY_SSL` - set to false if testing against self-signed certs
4. Run `serverless deploy`
5. In Looker
- Add the `action_list` endpoint to the /admin/actions page
- Enter the expected secret token
- Enable the action
|
JavaScript | UTF-8 | 515 | 3.546875 | 4 | [] | no_license | // Refactored spinner
// Repeats every four steps
// Timer increments by 200
let numOfTimes = 9;
let timer = 100;
for (let i = 0; i < numOfTimes; i++) {
switch ((i + 4) % 4) {
case 0: setTimeout(() => process.stdout.write('\r| '), timer); break;
case 1: setTimeout(() => process.stdout.write('\r/ '), timer); break;
case 2: setTimeout(() => process.stdout.write('\r- '), timer); break;
case 3: setTimeout(() => process.stdout.write('\r\\ '), timer); break;
default: break;
}
timer += 200;
} |
C# | UTF-8 | 9,893 | 2.609375 | 3 | [] | no_license | using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEngine.EventSystems;
/// <summary>
/// CellGrid class keeps track of the game, stores cells, units and players objects. It starts the game and makes turn transitions.
/// It reacts to user interacting with units or cells, and raises events related to game progress.
/// </summary>
public class CellGrid : MonoBehaviour
{
public event EventHandler GameStarted;
public event EventHandler GameEnded;
public event EventHandler TurnEnded;
public bool isGameOver = false;
private CellGridState _cellGridState;//The grid delegates some of its behaviours to cellGridState object.
public CellGridState CellGridState
{
private get
{
return _cellGridState;
}
set
{
if(_cellGridState != null)
_cellGridState.OnStateExit();
_cellGridState = value;
_cellGridState.OnStateEnter();
}
}
public int NumberOfPlayers { get; private set; }
public Player CurrentPlayer
{
get { return Players.Find(p => p.PlayerNumber.Equals(CurrentPlayerNumber)); }
}
public Unit CurrentUnit { get; set; }
public int CurrentPlayerNumber { get; private set; }
public Transform PlayersParent;
public List<Player> Players { get; private set; }
public List<Cell> Cells { get; private set; }
public List<Unit> Units { get; private set; }
public object PlayerNumber { get; private set; }
public List<Unit> unitTurnOrder = new List<Unit>();
public List<int> turnOrder = new List<int>();
public List<int> turnOrderPlayerNumbers;
public int turnIndex = 0;
public List<Unit>myUnits;
public int lastPlayer; //ai or player
public bool isActionDone = true;
public GameObject pausedMenu;
/// <summary>
/// this will initialize the map for the combat scene of the game.
/// </summary>
void Start()
{
//initiatlizes human and AI players
Players = new List<Player>();
for (int i = 0; i < PlayersParent.childCount; i++)
{
var player = PlayersParent.GetChild(i).GetComponent<Player>();
if (player != null)
Players.Add(player);
else
Debug.LogError("Invalid object in Players Parent game object");
}
NumberOfPlayers = Players.Count;
CurrentPlayerNumber = Players.Min(p => p.PlayerNumber);
//initializes each cell of the map
Cells = new List<Cell>();
for (int i = 0; i < transform.childCount; i++)
{
var cell = transform.GetChild(i).gameObject.GetComponent<Cell>();
if (cell != null)
Cells.Add(cell);
else
Debug.LogError("Invalid object in cells paretn game object");
}
foreach (var cell in Cells)
{
cell.CellClicked += OnCellClicked;
cell.CellHighlighted += OnCellHighlighted;
cell.CellDehighlighted += OnCellDehighlighted;
}
//initializes the units of the current scene
var unitGenerator = GetComponent<IUnitGenerator>();
if (unitGenerator != null)
{
Units = unitGenerator.SpawnUnits(Cells);
foreach (var unit in Units)
{
unit.UnitClicked += OnUnitClicked;
unit.UnitDestroyed += OnUnitDestroyed;
}
}
else
{
Debug.LogError("No IUnitGenerator script attached to cell grid");
}
if (Players.Count <= 1)
{
isGameOver = true;
}
OrderSpeed();
StartGame();
}
/// <summary>
/// Update called per frame, used to highlight the current acting character, so the player will know
/// </summary>
private void Update()
{
CurrentUnit.Cell.Mark(Cell.HighlightState.FriendlySelected);
if (Input.GetKeyDown(KeyCode.Escape))
{
if (pausedMenu.gameObject.activeSelf == true)
{
pausedMenu.GetComponent<PauseMenu>().Resume();
}
else { pausedMenu.GetComponent<PauseMenu>().Pause(); }
}
}
/// <summary>
/// orders the units by their speed parameter. Will be used to determine the turn order
/// </summary>
void OrderSpeed()
{
unitTurnOrder = Units.OrderBy(o => -o.Speed).ToList();
Unit shifted = unitTurnOrder[unitTurnOrder.Count-1];
unitTurnOrder.RemoveAt(unitTurnOrder.Count -1);
unitTurnOrder.Insert(0, shifted);
}
//the following are potential actions that can be triggered
private void OnCellDehighlighted(object sender, EventArgs e)
{
CellGridState.OnCellDeselected(sender as Cell);
}
private void OnCellHighlighted(object sender, EventArgs e)
{
CellGridState.OnCellSelected(sender as Cell);
}
private void OnCellClicked(object sender, EventArgs e)
{
CellGridState.OnCellClicked(sender as Cell);
}
private void OnUnitClicked(object sender, EventArgs e)
{
if (!EventSystem.current.IsPointerOverGameObject())
{
GenericUnit unit = sender as GenericUnit;
//CellGridState.OnCellSelected(unit.Cell as Cell);
CellGridStateUnitSelected selected = CellGridState as CellGridStateUnitSelected;
if (unit.PlayerNumber == 0)
{
}
else
{
CellGridState.OnUnitClicked(sender as Unit);
}
}
}
/// <summary>
/// removes destroyed units from the game, to advance the combate game state towards ending
/// </summary>
private void OnUnitDestroyed(object sender, AttackEventArgs e)
{
Units.Remove(sender as Unit);
unitTurnOrder.Remove(sender as Unit);
var totalPlayersAlive = Units.Select(u => u.PlayerNumber).Distinct().ToList(); //Checking if the game is over
if (totalPlayersAlive.Count == 1)
{
if(GameEnded != null)
{
GameEnded.Invoke(this, new EventArgs());
isGameOver = true;
}
}
}
/// <summary>
/// Action bar button functions, will be used to perform actions in combat. Allows the player to
/// perform different attacks/use different items in the combat scene
/// </summary>
//set the grid state to attacking Health
public void AttackHealth()
{
print("Attacking Health...");
_cellGridState.isAttacking = true;
_cellGridState.attackingHealth = true;
isActionDone = false;
}
//set the grid state to attacking Armor
public void AttackArmor()
{
print("Attacking Armor...");
_cellGridState.isAttacking = true;
_cellGridState.attackingHealth = false;
isActionDone = false;
}
//set the grid state to attacking with a Gun
public void ShootGun()
{
_cellGridState.isAttacking = true;
_cellGridState.attackingHealth = true;
_cellGridState.isTrueDamage = true;
_cellGridState.usingGun = true;
isActionDone = false;
}
//set the grid state to attack with an AOE attack, Testing purposes only. Should be substituted with an item function
public void AoeAttack()
{
print("AOE");
_cellGridState.isAttacking = true;
_cellGridState.isAoe = true;
_cellGridState.attackingHealth = true;
CurrentUnit.AttackAOE = 3;
isActionDone = false;
}
/// <summary>
/// Method is called once, at the beggining of the game. Initialized the board and the turn order
/// </summary>
public void StartGame()
{
if(GameStarted != null)
GameStarted.Invoke(this, new EventArgs());
CurrentPlayer.isPlaying = true;
TurnEnded += TurnCycle;
Players[unitTurnOrder[0].PlayerNumber].Play(this);
CurrentUnit = unitTurnOrder[0];
TurnCycleInvoke();
}
/// <summary>
/// Method makes turn transitions. It is called by player at the end of his turn. Allows for the game state to go
/// from one turn to the next.
/// </summary>
public void TurnCycle(object sender, System.EventArgs e)//code for a single turn of a unit
{
Unit shifted = unitTurnOrder[0];
unitTurnOrder.RemoveAt(0);
unitTurnOrder.Add(shifted);
unitTurnOrder[0].OnTurnStart();
CurrentPlayerNumber = unitTurnOrder[0].PlayerNumber;
if (unitTurnOrder[0].PlayerNumber == 0)
{
Players[0].Play(this);
CellGridState.OnUnitClicked(unitTurnOrder[0]);
CurrentUnit = unitTurnOrder[0];
}
else
{
Players[1].GetComponent<NaiveAiPlayer>().SinglePlay(this, unitTurnOrder[0]);
CurrentUnit = unitTurnOrder[0];
}
}
/// <summary>
/// For invoking the turn cycle
/// </summary>
public void TurnCycleInvoke() //generates event that triggers the turn cycle
{
if (TurnEnded != null)
{
TurnEnded(this, new EventArgs());
}
}
/// <summary>
/// Set some states at the end of the turn. For handling end of turn actions and
/// cycling to the next turn.
/// </summary>
public void EndTurn() //goes to next unit's turn
{
isActionDone = true;
unitTurnOrder[0].OnTurnEnd();
var totalPlayersAlive = Units.Select(u => u.PlayerNumber).Distinct().ToList(); //Checking if the game is over
if (totalPlayersAlive.Count != 1)
{
TurnCycleInvoke();
}
}
}
|
Java | UTF-8 | 1,241 | 2.03125 | 2 | [] | no_license | package com.cn.pppcar.widget;
import android.content.Context;
import android.support.v7.app.AppCompatDialog;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.cn.pppcar.R;
/**
* Created by nurmemet on 2016/5/9.
*/
public class StagePayDlg extends AppCompatDialog {
private Button mCancelButton;
public StagePayDlg(Context context) {
super(context, R.style.dlg_pay_stage);
setContentView(R.layout.dlg_stage_pay);
Window dialogWindow = this.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.width=WindowManager.LayoutParams.MATCH_PARENT;
dialogWindow.setAttributes(lp);
dialogWindow.setGravity(Gravity.BOTTOM);
mCancelButton=(Button)findViewById(com.cn.customlibrary.R.id.cancel_btn);
mCancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
@Override
public void dismiss() {
super.dismiss();
}
@Override
public void show() {
super.show();
}
}
|
Java | UTF-8 | 2,269 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package io.hawt.example.fabric;
import io.fabric8.api.PlaceholderResolver;
import io.fabric8.service.ChecksumPlaceholderResolver;
import io.fabric8.service.FabricServiceImpl;
import io.fabric8.service.ZooKeeperDataStore;
import io.fabric8.service.ZookeeperPlaceholderResolver;
import io.fabric8.zookeeper.IZKClient;
import io.fabric8.zookeeper.spring.ZKClientFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
/**
* A simple factory bean that creates a connection to Fuse Fabric
*/
public class FabricConnectorFactory {
private static final transient Logger LOG = LoggerFactory.getLogger(FabricConnectorFactory.class);
public void init() throws Exception {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
String fabricUrl = System.getProperty("fabricUrl", "");
String fabricPassword = System.getProperty("fabricPassword", "admin");
if (fabricUrl != null && fabricUrl.length() > 0) {
LOG.info("Connecting to Fuse Fabric at " + fabricUrl);
ZKClientFactoryBean factory = new ZKClientFactoryBean();
factory.setPassword(fabricPassword);
factory.setConnectString(fabricUrl);
IZKClient zooKeeper = factory.getObject();
FabricServiceImpl impl = new FabricServiceImpl();
impl.setZooKeeper(zooKeeper);
impl.bindMBeanServer(mbeanServer);
//impl.init();
ZooKeeperDataStore dataStore = new ZooKeeperDataStore();
dataStore.setZk(zooKeeper);
ZookeeperPlaceholderResolver zookeeperPlaceholderResolver = new ZookeeperPlaceholderResolver();
zookeeperPlaceholderResolver.setZooKeeper(zooKeeper);
List<PlaceholderResolver> placeholderResolvers = new ArrayList<PlaceholderResolver>();
placeholderResolvers.add(new ChecksumPlaceholderResolver());
placeholderResolvers.add(zookeeperPlaceholderResolver);
dataStore.setPlaceholderResolvers(placeholderResolvers);
impl.setDataStore(dataStore);
}
}
public void destroy() {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.