text stringlengths 1 1.05M |
|---|
from typing import List
def calculateTotalScore(scores: List[int]) -> List[int]:
total_scores = [scores[0]] # Initialize the total scores list with the first score
for i in range(1, len(scores)):
total_scores.append(total_scores[i-1] + scores[i]) # Calculate the total score for each round
return total_scores |
curl --request POST \
--url http://mockbin.com/har \
--header 'content-type: multipart/form-data' \
--form foo=@hello.txt
|
import React, { Component } from 'react';
import './index.scss';
class ChartTitle extends Component {
constructor(props){
super(props);
this.state = {
active: 0,
basicNumber: 30,
}
}
genTabs = ()=>{
let tabs = [];
let total = this.props.total?this.props.total:0;
let basicNumber = this.props.basicNumber?this.props.basicNumber:this.state.basicNumber;
let i =0;
if(total<basicNumber){
return tabs;
}
while(total>basicNumber){
tabs[i] = `${(i*basicNumber+1)}-${(i+1)*basicNumber}`;
total = total-basicNumber;
i++;
if(total<basicNumber){
tabs[i] =`${(i*basicNumber+1)}-${i*basicNumber+total}`;
}
}
// console.log('tabs', tabs)
return tabs;
}
handleItemClick(item, index){
let arr = item.split('-');
this.props.itemClick(arr)
this.setState({
active: index
})
}
TabList = ()=> {
const tabs = this.genTabs();
const active = this.state.active;
const listItems = tabs.map((item,index) =>
<li className={active==index?'chart-tab active':'chart-tab'} key={item} onClick={this.handleItemClick.bind(this, item, index)} >{item}</li>
);
return (
<ul className="chart-tabs">
{listItems}
</ul>
)
}
render() {
let TabList = this.TabList;
let title = this.props.title?this.props.title:'监控图表'
return(
<div className="admin-chart-title">
<div className="chart-title">{title}</div>
<TabList />
</div>
)
}
}
export default ChartTitle; |
#!/bin/bash
sleep 60 && conky -d -q;
|
import React from 'react';
import ClientModule from '@gqlapp/module-client-react';
import { Route } from 'react-router-dom';
import Static from './containers/Static';
import resources from './locales';
export default new ClientModule({
route: [
<Route exact path="/mission" component={Static} />,
<Route exact path="/about-us" component={Static} />,
<Route exact path="/terms-of-service" component={Static} />,
<Route exact path="/privacy-rules" component={Static} />,
<Route exact path="/renting" component={Static} />,
<Route exact path="/lending" component={Static} />,
<Route exact path="/faq" component={Static} />,
<Route path="/staticview" component={Static} />,
<Route exact path="/blog" component={Static} />
],
localization: [
{
ns: 'pages',
resources
}
]
});
|
public byte[] EncryptMessage(byte[] message, byte[] encryptionKey)
{
byte[] encryptedMessage = new byte[message.Length];
for (int i = 0; i < message.Length; i++)
{
encryptedMessage[i] = (byte)(message[i] ^ encryptionKey[i % encryptionKey.Length]);
}
return encryptedMessage;
} |
package system
import (
"fmt"
"net"
"sort"
"time"
)
type DNS interface {
Host() string
Addrs() ([]string, error)
Resolveable() (interface{}, error)
Exists() (interface{}, error)
SetTimeout(int64)
}
type DefDNS struct {
host string
resolveable bool
addrs []string
Timeout int64
loaded bool
err error
}
func NewDefDNS(host string, system *System) DNS {
return &DefDNS{host: host}
}
func (d *DefDNS) Host() string {
return d.host
}
func (d *DefDNS) SetTimeout(t int64) {
d.Timeout = t
}
func (d *DefDNS) setup() error {
if d.loaded {
return d.err
}
d.loaded = true
timeout := d.Timeout
if timeout == 0 {
timeout = 500
}
addrs, err := lookupHost(d.host, timeout)
if err != nil {
d.resolveable = false
d.addrs = []string{}
d.err = err
return d.err
}
sort.Strings(addrs)
d.resolveable = true
d.addrs = addrs
return nil
}
func (d *DefDNS) Addrs() ([]string, error) {
err := d.setup()
return d.addrs, err
}
func (d *DefDNS) Resolveable() (interface{}, error) {
err := d.setup()
return d.resolveable, err
}
// Stub out
func (d *DefDNS) Exists() (interface{}, error) {
return false, nil
}
func lookupHost(host string, timeout int64) ([]string, error) {
c1 := make(chan []string, 1)
e1 := make(chan error, 1)
go func() {
addrs, err := net.LookupHost(host)
if err != nil {
e1 <- err
}
c1 <- addrs
}()
select {
case res := <-c1:
return res, nil
case err := <-e1:
return nil, err
case <-time.After(time.Millisecond * time.Duration(timeout)):
return nil, fmt.Errorf("DNS lookup timed out (%d milliseconds)", timeout)
}
}
|
#!/usr/bin/env bash
# Terminate already running bar instances
killall -q polybar
# Wait until the processes have been shut down
while pgrep -x polybar >/dev/null; do sleep 1; done
# Launch bar1 and bar2
myarr=($(xrandr | awk '/ connected/ && /[[:digit:]]x[[:digit:]].*+/{print $1}'))
for monitor in "${myarr[@]}"; do
polybar -c ~/.config/polybar/config.ini "$monitor" &
done
echo "Bars launched..."
|
import styled from 'styled-components';
import { media } from '../../utils/media-queries';
import { space } from '../../utils/mixins';
const ProfileWrapper = styled.div`
.background-img { filter: grayscale(100%); }
.thanks { margin-top: ${space(4)}; }
.content > * { max-width: 600px; }
.social {
align-items: flex-start;
display: flex;
flex-direction: column;
margin-top: ${space(2)};
a {
margin-bottom: ${space()};
&:last-child { margin-bottom: 0; }
}
}
${media.max('desktop')`
margin-bottom: ${space(2)};
.background-img { margin-bottom: ${space(2)}; }
`}
${media.min('desktop')`
display: flex;
justify-content: flex-end;
.profile-image {
align-items: flex-end;
display: flex;
height: 100vh;
left: 0;
padding: ${space(2)};
padding-top: 38vh;
pointer-events: none;
position: fixed;
top: 0;
width: 50vw;
z-index: 0;
.background-img {
max-width: 320px;
width: 100%;
}
}
.content-wrapper {
align-items: flex-end;
display: flex;
height: 100vh;
left: 0;
position: fixed;
top: 0;
width: 100vw;
}
.content {
height: 100%;
overflow-y: auto;
padding: ${space(2)};
padding-left: calc(50vw + ${space(2)});
padding-top: ${space(8)};
}
`};
@media screen and (min-width: 1024px) and (min-height: 768px) {
.profile-image .background-img { max-width: 380px; }
}
@media screen and (min-width: 1440px) and (min-height: 715px) {
.profile-image .background-img { max-width: 440px; }
.content { padding-top: ${space(10)}; }
}
@media screen and (min-width: 1440px) and (min-height: 850px) {
.profile-image .background-img { max-width: 500px; }
.content { padding-top: ${space(12)}; }
}
`;
export default ProfileWrapper;
|
require File.join(Rails.root,"app","data_migrations","change_ssn.rb")
# This rake task merges people in Glue.
# format RAILS_ENV=production bundle exec rake migrations:change_ssn hbx_id='hbx_id of the person' new_ssn='the ssn to change to'
namespace :migrations do
desc "Change SSN"
ChangeSsn.define_task :change_ssn => :environment
end |
<filename>Labwork-1/navigation-pages/styles/text.style.js
import { StyleSheet } from 'react-native'
const text = StyleSheet.create({
about: {
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
},
navigate: {
fontSize: 18,
textAlign: 'center',
color: 'grey',
},
link: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
})
export default text
|
#!/usr/bin/env bash
set -eu
: ${ELASTICACHE_SERVICE_NAME:=test-elasticache}
cf service "$ELASTICACHE_SERVICE_NAME"
|
class Image {
/**
* Hintergrundfarbe des Bildes
*
* @var string
*/
public $ColorBackground;
/**
* Gridfarbe
*
* @var string
*/
public $ColorGrid;
/**
* Image constructor.
* @param string $colorBackground
* @param string $colorGrid
*/
public function __construct($colorBackground, $colorGrid) {
$this->ColorBackground = $colorBackground;
$this->ColorGrid = $colorGrid;
}
/**
* Get the background color of the image
*
* @return string
*/
public function getColorBackground() {
return $this->ColorBackground;
}
/**
* Set the background color of the image
*
* @param string $color
*/
public function setColorBackground($color) {
$this->ColorBackground = $color;
}
/**
* Get the grid color of the image
*
* @return string
*/
public function getColorGrid() {
return $this->ColorGrid;
}
/**
* Set the grid color of the image
*
* @param string $color
*/
public function setColorGrid($color) {
$this->ColorGrid = $color;
}
} |
<filename>INFO/Books Codes/Oracle PLSQL Tips and Techniques/OutputChapter04/4_25a.sql<gh_stars>0
-- ***************************************************************************
-- File: 4_25a.sql
--
-- Developed By TUSC
--
-- Disclaimer: Neither Osborne/McGraw-Hill, TUSC, nor the author warrant
-- that this source code is error-free. If any errors are
-- found in this source code, please report them to TUSC at
-- (630)960-2909 ext 1011 or <EMAIL>.
-- ***************************************************************************
SPOOL 4_25a.lis
CREATE OR REPLACE PACKAGE BODY process_products IS
------------------------------------------------------------------
PROCEDURE populate_prod_table IS
CURSOR cur_product IS
SELECT *
FROM s_product;
BEGIN
-- First, empty current PL/SQL table
pvg_prod_table.DELETE;
-- Loop through all products, placing into PL/SQL table
FOR lv_prod_rec IN cur_product LOOP
-- The product_id is used as the array index, but also loaded
-- for the searches that are on product_name and need to
-- return the product_id.
pvg_prod_table(lv_prod_rec.product_id).product_id
:= lv_prod_rec.product_id;
pvg_prod_table(lv_prod_rec.product_id).product_name
:= lv_prod_rec.product_name;
pvg_prod_table(lv_prod_rec.product_id).short_desc
:= lv_prod_rec.short_desc;
pvg_prod_table(lv_prod_rec.product_id).suggested_wholesale_price
:= lv_prod_rec.suggested_wholesale_price;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20100,
'Error in procedure POPULATE_PROD_TABLE.', FALSE);
END populate_prod_table;
------------------------------------------------------------------
PROCEDURE check_product_id
(p_prod_id_num s_product.product_id%TYPE) IS
BEGIN
-- One statement to see if the product exists, since the
-- array index is the product_id.
IF pvg_prod_table.EXISTS(p_prod_id_num) THEN
DBMS_OUTPUT.PUT_LINE('PL/SQL Table Index: ' ||
pvg_prod_table(p_prod_id_num));
DBMS_OUTPUT.PUT_LINE('Product ID: ' ||
pvg_prod_table(p_prod_id_num).product_id );
DBMS_OUTPUT.PUT_LINE('Product Name: ' ||
pvg_prod_table(p_prod_id_num).product_name );
DBMS_OUTPUT.PUT_LINE('Description: ' ||
pvg_prod_table(p_prod_id_num).short_desc );
DBMS_OUTPUT.PUT_LINE('Wholesale Price: ' ||
TO_CHAR(pvg_prod_table(p_prod_id_num).
suggested_wholesale_price, '$9999.00'));
DBMS_OUTPUT.PUT_LINE(CHR(10));
ELSE
DBMS_OUTPUT.PUT_LINE('Product: ' || TO_CHAR(p_prod_id_num) ||
' is invalid.');
END IF;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20102,
'Error in procedure CHECK_PRODUCT_ID.', FALSE);
END check_product_id;
------------------------------------------------------------------
PROCEDURE check_product_name
(p_prod_name_txt s_product.product_name%TYPE) IS
lv_index_num NUMBER;
lv_match_bln BOOLEAN := FALSE;
BEGIN
-- First check if table has any records
IF pvg_prod_table.COUNT <> 0 THEN
-- Attain starting table index for loop
lv_index_num := pvg_prod_table.FIRST;
-- Loop through all products looking for a match on product_name
LOOP
-- Check existence of the product name (not exact match
-- check, only a check to see if the input name is contained
-- in a product name in the table).
IF (INSTR(UPPER(pvg_prod_table(lv_index_num).product_name),
UPPER(p_prod_name_txt)) > 0) THEN
-- Assign TRUE to search boolean
lv_match_bln := TRUE;
-- Output record data from PL/SQL table
DBMS_OUTPUT.PUT_LINE('PL/SQL Table Index: ' ||
pvg_prod_table(lv_index_num));
DBMS_OUTPUT.PUT_LINE('Product ID: ' ||
pvg_prod_table(lv_index_num).product_id );
DBMS_OUTPUT.PUT_LINE('Product Name: ' ||
pvg_prod_table(lv_index_num).product_name );
DBMS_OUTPUT.PUT_LINE('Description: ' ||
pvg_prod_table(lv_index_num).short_desc );
DBMS_OUTPUT.PUT_LINE('Wholesale Price: ' ||
TO_CHAR(pvg_prod_table(lv_index_num).
suggested_wholesale_price, '$9999.00'));
DBMS_OUTPUT.PUT_LINE(CHR(10));
END IF;
EXIT WHEN (lv_index_num = pvg_prod_table.LAST) OR
lv_match_bln;
lv_index_num := pvg_prod_table.NEXT(lv_index_num);
END LOOP;
IF NOT lv_match_bln THEN
-- Output record data from PL/SQL table
DBMS_OUTPUT.PUT_LINE('Product: ' || p_prod_name_txt ||
' is invalid.');
END IF;
ELSE
-- Output record data from PL/SQL table
DBMS_OUTPUT.PUT_LINE('There are no products in the table.');
END IF;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20102,
'Error in procedure CHECK_PRODUCT_NAME.', FALSE);
END check_product_name;
------------------------------------------------------------------
-- Package Initialization Section
BEGIN
-- Call procedure to populate product PL/SQL table
populate_prod_table;
END process_products;
/
SPOOL OFF
|
function drawChessboard(length) {
let board = document.querySelector(".chessboard");
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
let square = document.createElement("div");
square.style.width = "50px";
square.style.height = "50px";
if ((i + j) % 2 === 0) {
square.style.backgroundColor = "#000000";
} else {
square.style.backgroundColor = "#FFFFFF";
}
board.appendChild(square);
}
board.appendChild(document.createElement("br"));
}
}
drawChessboard(8); |
<reponame>nsected/simple-crawler-frontend<filename>both/models/page.model.ts
export interface Page {
contentType: "string",
url: "string",
redirectURL: "string",
create_date: "date",
update_date: "date",
status: "Number",
bodySize: "Number",
site: "string",
}
|
<filename>python/kinematics.py<gh_stars>1-10
""" Kinematics module
This module implements simple function to calculate position of arm based on given angles.
Simple matrix multiplication is used for the calculations.
https://github.com/tomash1234/robot-arm-filler
"""
import numpy as np
def create_rot_x(theta):
""" Creates rotation matrix in x axis for a specific angle
Args:
theta: angle in radians
Return:
rotation x matrix 4x4
"""
return np.matrix([[1, 0, 0, 0],
[0, np.cos(theta), -np.sin(theta), 0],
[0, np.sin(theta), np.cos(theta), 0],
[0, 0, 0, 1]])
def create_rot_y(theta):
""" Creates rotation matrix in y axis for a specific angle
Args:
theta: angle in radians
Return:
rotation y matrix 4x4
"""
return np.matrix([[np.cos(theta), 0, np.sin(theta), 0],
[0, 1, 0, 0],
[-np.sin(theta), 0, np.cos(theta), 0],
[0, 0, 0, 1]])
def create_rot_z(theta):
""" Creates rotation matrix in z axis for a specific angle
Args:
theta: angle in radians
Return:
rotation z matrix 4x4
"""
return np.matrix([[np.cos(theta), -np.sin(theta), 0, 0],
[np.sin(theta), np.cos(theta), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
def create_tran(x, y, z):
""" Creates translation matrix for 3D movement
Args:
x: move in x axis
y: move in y axis
z: move in z axis
Return:
translation matrix 4x4
"""
return np.matrix([[1, 0, 0, x],
[0, 1, 0, y],
[0, 0, 1, z],
[0, 0, 0, 1]])
def convert_point(point, which):
"""Convert 3D point to 2D/3D point
Args:
which: string, convert to which format, [xy, xz, yz, all]
Returns:
np array of length 2 or 3
"""
if which == 'xy':
return np.array([point[0], point[1]])
if which == 'xz':
return np.array([point[0], point[2]])
if which == 'yz':
return np.array([point[1], point[2]])
return point
class Kinematics:
"""Class calculation position of robot arm parts
"""
def __init__(self, dimensions):
"""Inits kinematics class with RoboArm dimensions"""
self.base_off = np.identity(4)
self.arm_off = np.identity(4)
self.elbow_off = np.identity(4)
self.forearm_off = np.identity(4)
self.base_rot = np.identity(4)
self.shoulder_rot = np.identity(4)
self.elbow_rot = np.identity(4)
self.setup_offset(dimensions)
def setup_offset(self, dim):
"""Prepare offset translation based on parts' physical dimensions
Args:
dim: robot arm dimensions
"""
self.base_off = create_tran(dim.shoulder_o, dim.base_h, dim.shoulder_h_o)
self.arm_off = create_tran(dim.arm_l, 0, 0)
self.elbow_off = create_tran(0, dim.elbow_o, dim.elbow_h_o)
self.forearm_off = create_tran(dim.elbow_l, 0, 0)
def calculate(self, base, shoulder, elbow):
"""Calculates positions of all robo arm parts based on given angles
Args:
base: base angle in radians
shoulder: shoulder angle in radians
elbow: elbow angle in radians
Returns:
list of parts 3D positions [position of shoulder, position of end of arm,
position of elbow, tip of arm position]
"""
p = np.array([0, 0, 0, 1])
base_rot = create_rot_y(base)
shoulder_rot = create_rot_z(shoulder)
forearm_rot = create_rot_z(elbow)
base_trans = base_rot @ self.base_off
elbow_trans = base_trans + base_rot @ shoulder_rot @ self.arm_off @ self.elbow_off
end_trans = elbow_trans + base_rot @ shoulder_rot @ forearm_rot @ self.forearm_off
shoulder_pos = base_trans @ p
arm_end_pos = (base_trans + base_rot @ shoulder_rot @ self.arm_off) @ p
elbow_pos = elbow_trans @ p
end_pos = end_trans @ p
return [np.asarray(shoulder_pos[0, 0:3]).reshape(-1), \
np.asarray(arm_end_pos[0, 0:3]).reshape(-1), \
np.asarray(elbow_pos[0, 0:3]).reshape(-1), \
np.asarray(end_pos[0, 0:3]).reshape(-1)]
def calculate_shoulder_pos(self, base, which='all'):
"""Calculates position of shoulder based on base angle
Args:
base: base angle in radians
which: determines to in which format return shoulder pos
Returns:
shoulder 3D/2D position
"""
p = np.array([0, 0, 0, 1])
base_rot = create_rot_y(base)
base_trans = base_rot @ self.base_off
shoulder_pos = base_trans @ p
shoulder_pos = np.asarray(shoulder_pos[0, 0:3]).reshape(-1)
return convert_point(shoulder_pos, which)
|
class CreateRecurringEvents < ActiveRecord::Migration[5.2]
def change
create_table :recurring_events do |t|
t.string :title
t.date :anchor
t.integer :frequency
t.string :color
t.boolean :light_on
t.references :schedule
t.references :venue
t.timestamps
end
end
end
|
<h2>
@ViewData["Title"]
</h2>
@if (Model.Count() > 0)
{
<table>
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Total Amount</th>
</tr>
@foreach (var order in Model)
{
<tr>
<td>@order.OrderId</td>
<td>@order.OrderDate.ToShortDateString()</td>
<td>@order.TotalAmount.ToString("C")</td>
</tr>
}
</table>
}
else
{
<h4 class="text-center">Нямате направени поръчки.</h4>
} |
import React from "react"
import styled from "@emotion/styled"
import { colors } from "../../utils/styles"
const StyledButton = styled.button`
cursor: pointer;
//width: 200px;
//height: 50px;
padding: 1rem;
border: none;
color: #fff;
font-size: 0.75rem;
text-transform: uppercase;
font-weight: bold;
font-family: Roboto, serif;
letter-spacing: 1px;
background: ${colors.darkGrey};
opacity: 0.6;
pointer-events: none;
border-radius: var(--border-radius);
margin-top: 1rem;
`
const DisabledButton = ({ children, className }) => {
return (
<StyledButton className={className} disabled>
{children}
</StyledButton>
)
}
export default DisabledButton
|
<filename>bower_components/angular-ui-router/src/params/interface.ts
/** @module params */ /** for typedoc */
import {ParamType} from "./type";
export interface RawParams {
[key: string]: any;
}
export type ParamsOrArray = (RawParams|RawParams[]);
/**
* Inside a [[StateDeclaration.params]]:
*
* A ParamDeclaration object defines how a single State Parameter should work.
*
* @example
* ```
*
* var mystate = {
* template: '<div ui-view/>',
* controller: function() {}
* url: '/mystate/:param1',
* params: {
* param1: "index", // <-- Default value for 'param1'
* // (shorthand ParamDeclaration)
*
* nonUrlParam: { // <-- ParamDeclaration for 'nonUrlParam'
* type: "int",
* array: true,
* value: []
* }
* }
* }
* ```
*/
export interface ParamDeclaration {
/**
* A property of [[ParamDeclaration]]:
*
* Specifies the default value for this parameter. This implicitly sets this parameter as optional.
*
* When UI-Router routes to a state and no value is specified for this parameter in the URL or transition,
* the default value will be used instead. If value is a function, it will be injected and invoked, and the
* return value used.
*
* Note: `value: undefined` is treated as though no default value was specified, while `value: null` is treated
* as "the default value is null".
*
* ```
* // define default values for param1 and param2
* params: {
* param1: {
* value: "defaultValue"
* },
* param2: {
* value: "param2Default;
* }
* }
* ```
*
* ### Shorthand Declaration
* If you only want to set the default value of the parameter, you may use a shorthand syntax.
* In the params map, instead mapping the param name to a full parameter configuration object, simply set map it
* to the default parameter value, e.g.:
* ```
* // define a parameter's default value
* params: {
* param1: {
* value: "defaultValue"
* },
* param2: {
* value: "param2Default;
* }
* }
*
* // shorthand default values
* params: {
* param1: "defaultValue",
* param2: "param2Default"
* }
* ```
*
* This defines a default value for the parameter. If the parameter value is `undefined`, this value will be used instead
*/
value?: any;
/**
* A property of [[ParamDeclaration]]:
*
* Specifies the [[ParamType]] of the parameter.
*
* Set this property to the name of parameter's type. The type may be either one of the
* built in types, or a custom type that has been registered with the [[$urlMatcherFactory]]
*/
type: (string|ParamType);
/**
* A property of [[ParamDeclaration]]:
*
* Explicitly specifies the array mode of a URL parameter
*
* - If `false`, the parameter value will be treated (encoded/decoded) as a single value
* - If `true`, the parameter value will be treated (encoded/decoded) as an array of values.
* - If `auto` (for query parameters only), if multiple values for a single parameter are present
* in the URL (e.g.: /foo?bar=1&bar=2&bar=3) then the values are mapped to an array (e.g.:
* `{ foo: [ '1', '2', '3' ] }`). However, if only one value is present (e.g.: /foo?bar=1)
* then the value is treated as single value (e.g.: { foo: '1' }).
*
* If you specified a [[type]] for the parameter, the value will be treated as an array
* of the specified [[ParamType]].
*
* @example
* ```
*
* {
* name: 'foo',
* url: '/foo/{arrayParam:int}`,
* params: {
* arrayParam: { array: true }
* }
* }
*
* // After the transition, URL should be '/foo/1-2-3'
* $state.go("foo", { arrayParam: [ 1, 2, 3 ] });
* ```
*
* @default `false` for path parameters, such as `url: '/foo/:pathParam'`
* @default `auto` for query parameters, such as `url: '/foo?queryParam'`
* @default `true` if the parameter name ends in `[]`, such as `url: '/foo/{implicitArrayParam:int[]}'`
*/
array: boolean;
/**
* A property of [[ParamDeclaration]]:
*
* Configures how a default parameter value is represented in the URL when the current parameter value
* is the same as the default value.
*
* There are three squash settings:
*
* - `false`: The parameter's default value is not squashed. It is encoded and included in the URL
* - `true`: The parameter's default value is omitted from the URL. If the parameter is preceeded
* and followed by slashes in the state's url declaration, then one of those slashes are omitted.
* This can allow for cleaner looking URLs.
* - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary
* placeholder of your choice.
*
* @example
* ```
*
* {
* name: 'mystate',
* url: '/mystate/:myparam',
* params: {
* myparam: 'defaultParamValue'
* squash: true
* }
* }
*
* // URL will be `/mystate/`
* $state.go('mystate', { myparam: 'defaultParamValue' });
*
* // URL will be `/mystate/someOtherValue`
* $state.go('mystate', { myparam: 'someOtherValue' });
* ```
*
* @example
* ```
*
* {
* name: 'mystate2',
* url: '/mystate2/:myparam2',
* params: {
* myparam2: 'defaultParamValue'
* squash: "~"
* }
* }
*
* // URL will be `/mystate/~`
* $state.go('mystate', { myparam2: 'defaultParamValue' });
*
* // URL will be `/mystate/someOtherValue`
* $state.go('mystate', { myparam2: 'someOtherValue' });
* ```
*
* If squash is not set, it uses the configured default squash policy. (See [[defaultSquashPolicy]]())
*/
squash: (boolean|string);
/**
* @hidden
* @internalapi
*
* An array of [[Replace]] objects.
*
* When creating a Transition, defines how to handle certain special values, such as `undefined`, `null`,
* or empty string `""`. If the transition is started, and the parameter value is equal to one of the "to"
* values, then the parameter value is replaced with the "from" value.
*
* @example
* ```
*
* replace: [
* { from: undefined, to: null },
* { from: "", to: null }
* ]
*/
replace: Replace[];
/**
* @hidden
* @internalapi
*
* This is not part of the declaration; it is a calculated value depending on if a default value was specified or not.
*/
isOptional: boolean;
/**
* Dynamic flag
*
* When `dynamic` is `true`, changes to the parameter value will not cause the state to be entered/exited.
*
* The resolves will not be re-fetched, nor will views be recreated.
*/
dynamic: boolean;
}
export interface Replace {
from: string;
to: string;
}
/**
* Definition for a custom [[ParamType]]
*
* A developer can create a custom parameter type definition to customize the encoding and decoding of parameter values.
* The definition should implement all the methods of this interface.
*
* Parameter values are parsed from the URL as strings.
* However, it is often useful to parse the string into some other form, such as:
*
* - integer
* - date
* - array of <integer/date/string>
* - custom object
* - some custom string representation
*
* Typed parameter definitions control how parameter values are encoded (to the URL) and decoded (from the URL).
* UI-Router always provides the decoded parameter values to the user from methods such as [[Transition.params]].
*
*
* For example, if a state has a url of `/foo/{fooId:int}` (the `fooId` parameter is of the `int` ParamType)
* and if the browser is at `/foo/123`, then the 123 is parsed as an integer:
*
* ```js
* var fooId = transition.params().fooId;
* fooId === "123" // false
* fooId === 123 // true
* ```
*
*
* #### Examples
*
* This example encodes an array of integers as a dash-delimited string to be used in the URL.
*
* If we call `$state.go('foo', { fooIds: [20, 30, 40] });`, the URL changes to `/foo/20-30-40`.
* If we navigate to `/foo/1-2-3`, the `foo` state's onEnter logs `[1, 2, 3]`.
*
* @example
* ```
*
* $urlMatcherFactoryProvider.type('intarray', {
* // Take an array of ints [1,2,3] and return a string "1-2-3"
* encode: (array) => array.join("-"),
*
* // Take an string "1-2-3" and return an array of ints [1,2,3]
* decode: (str) => str.split("-").map(x => parseInt(x, 10)),
*
* // Match the encoded string in the URL
* pattern: new RegExp("[0-9]+(?:-[0-9]+)*")
*
* // Ensure that the (decoded) object is an array, and that all its elements are numbers
* is: (obj) => Array.isArray(obj) &&
* obj.reduce((acc, item) => acc && typeof item === 'number', true),
*
* // Compare two arrays of integers
* equals: (array1, array2) => array1.length === array2.length &&
* array1.reduce((acc, item, idx) => acc && item === array2[idx], true);
* });
*
* $stateProvider.state('foo', {
* url: "/foo/{fooIds:intarray}",
* onEnter: function($transition$) {
* console.log($transition$.fooIds); // Logs "[1, 2, 3]"
* }
* });
* ```
*
*
* This example decodes an integer from the URL.
* It uses the integer as an index to look up an item from a static list.
* That item from the list is the decoded parameter value.
*
* @example
* ```
*
* var list = ['John', 'Paul', 'George', 'Ringo'];
*
* $urlMatcherFactoryProvider.type('listItem', {
* encode: function(item) {
* // Represent the list item in the URL using its corresponding index
* return list.indexOf(item);
* },
* decode: function(item) {
* // Look up the list item by index
* return list[parseInt(item, 10)];
* },
* is: function(item) {
* // Ensure the item is valid by checking to see that it appears
* // in the list
* return list.indexOf(item) > -1;
* }
* });
*
* $stateProvider.state('list', {
* url: "/list/{item:listItem}",
* controller: function($scope, $stateParams) {
* console.log($stateParams.item);
* }
* });
*
* // ...
*
* // Changes URL to '/list/3', logs "Ringo" to the console
* $state.go('list', { item: "Ringo" });
* ```
*
* See: [[UrlMatcherFactory.type]]
*/
export interface ParamTypeDefinition {
/**
* Tests if some object type is compatible with this parameter type
*
* Detects whether some value is of this particular type.
* Accepts a decoded value and determines whether it matches this `ParamType` object.
*
* If your custom type encodes the parameter to a specific type, check for that type here.
* For example, if your custom type decodes the URL parameter value as an array of ints, return true if the
* input is an array of ints:
* `(val) => Array.isArray(val) && array.reduce((acc, x) => acc && parseInt(val, 10) === val, true)`.
* If your type decodes the URL parameter value to a custom string, check that the string matches
* the pattern (don't use an arrow fn if you need `this`): `function (val) { return !!this.pattern.exec(val) }`
*
* Note: This method is _not used to check if the URL matches_.
* It's used to check if a _decoded value is this type_.
* Use [[pattern]] to check the URL.
*
* @param val The value to check.
* @param key If the type check is happening in the context of a specific [[UrlMatcher]] object,
* this is the name of the parameter in which `val` is stored. Can be used for
* meta-programming of `ParamType` objects.
* @returns `true` if the value matches the type, otherwise `false`.
*/
is(val: any, key?: string): boolean;
/**
* Encodes a custom/native type value to a string that can be embedded in a URL.
*
* Note that the return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
* only needs to be a representation of `val` that has been encoded as a string.
*
* For example, if your type decodes to an array of ints, then encode the array of ints as a string here:
* `(intarray) => intarray.join("-")`
*
* Note: in general, [[encode]] and [[decode]] should be symmetrical. That is, `encode(decode(str)) === str`
*
* @param val The value to encode.
* @param key The name of the parameter in which `val` is stored. Can be used for meta-programming of `ParamType` objects.
* @returns a string representation of `val` that can be encoded in a URL.
*/
encode(val: any, key?: string): (string|string[]);
/**
* Decodes a parameter value string (from URL string or transition param) to a custom/native value.
*
* For example, if your type decodes to an array of ints, then decode the string as an array of ints here:
* `(str) => str.split("-").map(str => parseInt(str, 10))`
*
* Note: in general, [[encode]] and [[decode]] should be symmetrical. That is, `encode(decode(str)) === str`
*
* @param val The URL parameter value to decode.
* @param key The name of the parameter in which `val` is stored. Can be used for meta-programming of `ParamType` objects.
* @returns a custom representation of the URL parameter value.
*/
decode(val: string, key?: string): any;
/**
* Determines whether two decoded values are equivalent.
*
* For example, if your type decodes to an array of ints, then check if the arrays are equal:
* `(a, b) => a.length === b.length && a.reduce((acc, x, idx) => acc && x === b[idx], true)`
*
* @param a A value to compare against.
* @param b A value to compare against.
* @returns `true` if the values are equivalent/equal, otherwise `false`.
*/
equals(a: any, b: any): boolean;
/**
* A regular expression that matches the encoded parameter type
*
* This regular expression is used to match the parameter type in the URL.
*
* For example, if your type encodes as a dash-separated numbers, match that here:
* `new RegExp("[0-9]+(?:-[0-9]+)*")`.
*
* There are some limitations to these regexps:
*
* - No capturing groups are allowed (use non-capturing groups: `(?: )`)
* - No pattern modifiers like case insensitive
* - No start-of-string or end-of-string: `/^foo$/`
*/
pattern: RegExp;
}
|
<filename>jeecg-boot/zyf/src/main/java/org/zyf/scholarship/zy/controller/ZyfZyController.java
package org.zyf.scholarship.zy.controller;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.zyf.scholarship.utils.Util;
import org.zyf.scholarship.utils.service.UtilService;
import org.zyf.scholarship.zy.entity.ZyfZy;
import org.zyf.scholarship.zy.mapper.ZyfZyMapper;
import org.zyf.scholarship.zy.service.IZyfZyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
/**
* @Description: 专业表
* @Author: jeecg-boot
* @Date: 2021-02-14
* @Version: V1.0
*/
@Api(tags = "专业表")
@RestController
@RequestMapping("/zy/zyfZy")
@Slf4j
public class ZyfZyController extends JeecgController<ZyfZy, IZyfZyService> {
@Autowired
private IZyfZyService zyfZyService;
@Resource
private ZyfZyMapper zyfZyMapper;
@Autowired
private UtilService utilService;
/**
* 分页列表查询
*
* @param zyfZy
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@AutoLog(value = "专业表-分页列表查询")
@ApiOperation(value = "专业表-分页列表查询", notes = "专业表-分页列表查询")
@GetMapping(value = "/list")
public Result<?> queryPageList(ZyfZy zyfZy,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
// QueryWrapper<ZyfZy> queryWrapper = QueryGenerator.initQueryWrapper(zyfZy, req.getParameterMap());
// Page<ZyfZy> page = new Page<ZyfZy>(pageNo, pageSize);
// IPage<ZyfZy> pageList = zyfZyService.page(page, queryWrapper);
// QueryWrapper<Map<String, String>> qryWrapper = new QueryWrapper<>();
// .select("zyf_zy.id as id"," zy_name as zyName"," xy_name as xyName")
IPage<Map<String, String>> pageList = new Page<Map<String, String>>(pageNo, pageSize);
Map<String, String> map = new HashMap();
for (Map.Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
map.put(entry.getKey(), entry.getValue()[0]);
}
LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
Util.Role role = utilService.who(loginUser.getId());
if (role == Util.Role.TEACHER) {
map.put("zyId", loginUser.getOrgCode());
}
pageList = zyfZyMapper.queryPageList(pageList, map);
return Result.OK(pageList);
}
@RequestMapping(value = "/queryall", method = RequestMethod.GET)
public Result<List<ZyfZy>> queryall(ZyfZy zyfZy,
HttpServletRequest req) {
Result<List<ZyfZy>> result = new Result<>();
LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
QueryWrapper<ZyfZy> queryWrapper = QueryGenerator.initQueryWrapper(zyfZy, req.getParameterMap());
Util.Role role = utilService.who(loginUser.getId());
if (role == Util.Role.TEACHER) {
queryWrapper.eq("id", loginUser.getOrgCode());
}
List<ZyfZy> list = zyfZyService.list(queryWrapper);
if (list == null || list.size() <= 0) {
result.error500("未找到信息");
} else {
result.setResult(list);
result.setSuccess(true);
}
return result;
}
/**
* 添加
*
* @param zyfZy
* @return
*/
@AutoLog(value = "专业表-添加")
@ApiOperation(value = "专业表-添加", notes = "专业表-添加")
@PostMapping(value = "/add")
public Result<?> add(@RequestBody ZyfZy zyfZy) {
zyfZyService.save(zyfZy);
return Result.OK("添加成功!");
}
/**
* 编辑
*
* @param zyfZy
* @return
*/
@AutoLog(value = "专业表-编辑")
@ApiOperation(value = "专业表-编辑", notes = "专业表-编辑")
@PutMapping(value = "/edit")
public Result<?> edit(@RequestBody ZyfZy zyfZy) {
zyfZyService.updateById(zyfZy);
return Result.OK("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@AutoLog(value = "专业表-通过id删除")
@ApiOperation(value = "专业表-通过id删除", notes = "专业表-通过id删除")
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
zyfZyService.removeById(id);
return Result.OK("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@AutoLog(value = "专业表-批量删除")
@ApiOperation(value = "专业表-批量删除", notes = "专业表-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.zyfZyService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "专业表-通过id查询")
@ApiOperation(value = "专业表-通过id查询", notes = "专业表-通过id查询")
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
ZyfZy zyfZy = zyfZyService.getById(id);
if (zyfZy == null) {
return Result.error("未找到对应数据");
}
return Result.OK(zyfZy);
}
/**
* 导出excel
*
* @param request
* @param zyfZy
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, ZyfZy zyfZy) {
return super.exportXls(request, zyfZy, ZyfZy.class, "专业表");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, ZyfZy.class);
}
}
|
<reponame>Marcura/marcura-ui<filename>marcura-ui/date-box/date-box.js
angular.module('marcuraUI.components').directive('maDateBox', ['$timeout', 'MaDate', 'MaHelper', 'MaValidators', function ($timeout, MaDate, MaHelper, MaValidators) {
return {
restrict: 'E',
scope: {
id: '@',
canReset: '@',
isDisabled: '@',
displayFormat: '@',
timeZone: '@',
culture: '@',
isLoading: '@',
isRequired: '@',
format: '@',
hasTime: '@',
// Used together with hasTime to maintain the time but not to show it.
shouldShowTime: '@',
placeholder: '@',
modifier: '@',
message: '@',
changeTimeout: '@',
min: '@',
max: '@',
change: '&',
validate: '&',
value: '=',
validators: '=',
instance: '=',
eventDates: '=',
disabledDates: '='
},
replace: true,
template: function (element, attributes) {
var canReset = attributes.canReset === 'true',
hasTime = attributes.hasTime === 'true',
shouldShowTime = attributes.shouldShowTime === 'false' ? false : true,
cssClass = 'ma-date-box',
ngClass = 'ng-class="{\
\'ma-date-box-is-invalid\': !isValid,\
\'ma-date-box-is-disabled\': isDisabled === \'true\',\
\'ma-date-box-is-focused\': isFocused,\
\'ma-date-box-is-touched\': isTouched,\
\'ma-date-box-is-loading\': isLoading === \'true\',\
\'ma-date-box-has-value\': hasValue()';
if (canReset) {
cssClass += ' ma-date-box-can-reset';
ngClass += ',\'ma-date-box-is-reset-disabled\': canReset === \'true\' && isDisabled !== \'true\' && !isResetEnabled()';
}
if (hasTime) {
cssClass += ' ma-date-box-has-time';
if (shouldShowTime) {
cssClass += ' ma-date-box-should-show-time';
}
}
ngClass += '}"';
var html = '\
<div class="'+ cssClass + '"' + ngClass + '>\
<div class="ma-date-box-inner">\
<input class="ma-date-box-date" type="text" id="{{::id}}"\
placeholder="{{placeholder}}"\
ng-disabled="isDisabled === \'true\'"\
ng-keydown="onKeydown($event)"\
ng-keyup="onKeyup($event)"/>';
if (hasTime) {
html += '<input class="ma-date-box-hour"\
maxlength="2"\
ng-disabled="isDisabled === \'true\'"\
ng-keyup="onKeyup($event)"\
ng-keydown="onTimeKeydown($event)"\
/><div class="ma-date-box-colon">:</div><input \
class="ma-date-box-minute" type="text"\
maxlength="2"\
ng-disabled="isDisabled === \'true\'"\
ng-keyup="onKeyup($event)"\
ng-keydown="onTimeKeydown($event)"/>';
}
html += '<i class="ma-date-box-icon fa fa-calendar"></i>\
</div>';
if (canReset) {
html += '<ma-button class="ma-button-reset"\
size="xs" simple\
right-icon="times-circle"\
click="onReset()"\
is-disabled="{{!isResetEnabled()}}">\
</ma-button>';
}
html += '<div class="ma-date-box-spinner">\
<div class="ma-pace">\
<div class="ma-pace-activity"></div>\
</div>\
</div>\
</div>';
return html;
},
link: function (scope, element, attributes) {
var picker = null,
hasTime = scope.hasTime === 'true',
displayFormat = (scope.displayFormat || 'dd MMM yyyy').replace(/Y/g, 'y').replace(/D/g, 'd'),
format = (scope.format || 'yyyy-MM-ddTHH:mm:ssZ').replace(/Y/g, 'y').replace(/D/g, 'd'),
timeZone = (scope.timeZone || 'Z').replace(/GMT/g, ''),
dateElement = angular.element(element[0].querySelector('.ma-date-box-date')),
hourElement = hasTime ? angular.element(element[0].querySelector('.ma-date-box-hour')) : null,
minuteElement = hasTime ? angular.element(element[0].querySelector('.ma-date-box-minute')) : null,
previousDate = MaDate.createEmpty(),
timeZoneOffset = MaDate.parseTimeZone(timeZone),
initialDisplayDate,
// Variables keydownValue and keyupValue help track touched state.
keydownValue,
keyupValue,
initialDateOffset = 0,
validators = [],
isRequired = scope.isRequired === 'true',
minDate = new MaDate(scope.min),
maxDate = new MaDate(scope.max),
failedValidator = null,
changePromise,
changeTimeout = Number(scope.changeTimeout) || 100,
dateCaretPosition = 0,
hourCaretPosition = 0,
minuteCaretPosition = 0,
isDateFocused,
isHourFocused,
isMinuteFocused,
eventDates = [],
isDisabledObserverFirstRun = true,
_modifier,
_min,
_max;
var hasDateChanged = function (date) {
if (previousDate.isEqual(date)) {
return false;
}
scope.isTouched = true;
return true;
};
// Returns null if display date is invalid.
var getDisplayDate = function () {
var displayDate = dateElement.val().trim(),
isEmpty = displayDate === '',
hour = hasTime ? Number(hourElement.val()) : 0,
minute = hasTime ? Number(minuteElement.val()) : 0,
date = MaDate.createEmpty();
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
return null;
}
if (isEmpty) {
return date;
}
date = new MaDate(displayDate);
// Date can't be parsed.
if (date.isEmpty()) {
return null;
}
date.add(hour, 'hour');
date.add(minute, 'minute');
date.offset(initialDateOffset);
return date;
};
var setDisplayDate = function (date) {
var displayDate = null;
if (date && !date.isEmpty()) {
// Adjust display date offset.
displayDate = date.copy().toUtc().add(timeZoneOffset, 'minute');
dateElement.val(displayDate.format(displayFormat));
if (hasTime) {
hourElement.val(displayDate.format('HH'));
minuteElement.val(displayDate.format('mm'));
}
if (!initialDisplayDate) {
initialDisplayDate = dateElement.val();
}
} else {
dateElement.val('');
if (hasTime) {
hourElement.val('00');
minuteElement.val('00');
}
}
// Restore caret position if the component has focus.
if (scope.isFocused) {
// In IE setting selectionStart/selectionEnd properties triggers focus/blur event.
// Remove the events while properties are being set and then restore them.
removeFocusEvent();
removeBlurEvent();
// Set caret for an appropriate field.
if (isDateFocused) {
dateElement.prop({
selectionStart: dateCaretPosition,
selectionEnd: dateCaretPosition
});
}
if (hasTime) {
if (isHourFocused) {
hourElement.prop({
selectionStart: hourCaretPosition,
selectionEnd: hourCaretPosition
});
}
if (isMinuteFocused) {
minuteElement.prop({
selectionStart: minuteCaretPosition,
selectionEnd: minuteCaretPosition
});
}
}
$timeout(function () {
addFocusEvent();
addBlurEvent();
});
}
// Set calendar date.
if (picker) {
picker.setDate(displayDate ? displayDate.toDate() : null, true);
}
};
var setMaxDate = function () {
if (!picker) {
return;
}
maxDate = new MaDate(scope.max);
// Pikaday does no support clearing maxDate by providing null value.
// So we just set maxDate to 100 years ahead.
if (maxDate.isEmpty()) {
maxDate = new MaDate().add(100, 'year');
}
picker.setMaxDate(maxDate.copy().toDate());
};
var setMinDate = function () {
if (!picker) {
return;
}
minDate = new MaDate(scope.min);
// Pikaday does no support clearing minDate by providing null value.
// So we just set minDate to 100 years before.
if (minDate.isEmpty()) {
minDate = new MaDate().subtract(100, 'year');
}
picker.setMinDate(minDate.copy().toDate());
};
var parseDate = function (date) {
var parsedDate = MaDate.createEmpty();
if (!date) {
return parsedDate;
}
parsedDate = MaDate.parse(date, scope.culture);
return parsedDate;
};
var setDateTime = function (date) {
if (!date || date.isEmpty()) {
return;
}
date.hour(hasTime ? Number(hourElement.val()) : 0)
.minute(hasTime ? Number(minuteElement.val()) : 0)
.second(0);
};
var resetInitialDateOffset = function () {
// Override initial time zone offset after date has been changed.
initialDateOffset = timeZoneOffset;
};
var isDateDisabled = function (date) {
var _isDateDisabled = false,
_date = new MaDate(date).offset(timeZoneOffset);
if (scope.disabledDates && scope.disabledDates.length) {
for (var i = 0; i < scope.disabledDates.length; i++) {
var disabledDate = new MaDate(scope.disabledDates[i]).offset(timeZoneOffset);
if (_date.isEqual(disabledDate)) {
_isDateDisabled = true;
break;
}
}
}
return _isDateDisabled;
};
var initializePikaday = function () {
var theme = 'ma-pika';
if (!MaHelper.isNullOrWhiteSpace(_modifier)) {
var modifiers = _modifier.split(' ');
for (var i = 0; i < modifiers.length; i++) {
theme += ' ma-pika-' + modifiers[i];
}
}
picker = new Pikaday({
field: angular.element(element[0].querySelector('.ma-date-box-icon'))[0],
position: 'bottom right',
onSelect: function () {
var date = new MaDate(picker.getDate());
date.offset(timeZoneOffset);
if (hasTime) {
setDateTime(date);
resetInitialDateOffset();
}
// Use $timeout to apply scope changes instead of $apply,
// which throws digest error at this point.
$timeout(function () {
validate(date);
});
if (!hasDateChanged(date)) {
// Refresh display date in case the following scenario.
// 1. maxDate is set to 30/10/2016.
// 2. The user enteres greater date by hand 31/10/2016, which
// will not be excepted and become invalid.
// 3. The user then selects the same 30/10/2016 date from the calendar,
// but display date will not be changed as previous date is still 30/10/2016
// (hasDateChanged will return false).
setDisplayDate(date);
return;
}
triggerChange(date);
},
onDraw: function () {
if (scope.message) {
$(picker.el).append('<div class="ma-pika-message">' + scope.message + '</div>');
}
},
disableDayFn: isDateDisabled,
events: eventDates,
theme: theme
});
setDisplayDate(previousDate);
setMaxDate();
setMinDate();
};
var destroyPikaday = function () {
if (picker) {
picker.destroy();
}
};
var validate = function (date, triggerEvent) {
scope.isValid = true;
failedValidator = null;
triggerEvent = triggerEvent !== undefined ? triggerEvent : true;
var formattedDate = date ? date.format(format) : null;
if (validators && validators.length) {
for (var i = 0; i < validators.length; i++) {
if (!validators[i].validate(formattedDate)) {
scope.isValid = false;
failedValidator = validators[i];
break;
}
}
}
if (triggerEvent !== false) {
triggerValidate(date);
}
};
var setValidators = function () {
var hasIsNotEmptyValidator = false;
validators = scope.validators ? angular.copy(scope.validators) : [];
for (var i = 0; i < validators.length; i++) {
if (validators[i].name === 'IsNotEmpty') {
hasIsNotEmptyValidator = true;
break;
}
}
if (!hasIsNotEmptyValidator && isRequired) {
validators.unshift(MaValidators.isNotEmpty());
}
if (hasIsNotEmptyValidator) {
isRequired = true;
}
if (!minDate.isEmpty()) {
validators.push(MaValidators.isGreaterOrEqual(minDate, true));
}
if (!maxDate.isEmpty()) {
validators.push(MaValidators.isLessOrEqual(maxDate, true));
}
if (scope.disabledDates && scope.disabledDates.length) {
validators.push({
name: 'IsDisabled',
message: 'Date is disabled.',
validate: function (date) {
return !isDateDisabled(date);
}
});
}
};
var triggerChange = function (date) {
previousDate = date || MaDate.createEmpty();
scope.value = date ? date.format(format) : null;
// Postpone change event for $apply (which is being invoked by $timeout)
// to have time to take effect and update scope.value,
// so both maValue and scope.value have the same values eventually.
$timeout(function () {
scope.change({
maValue: scope.value
});
});
};
var triggerValidate = function (date) {
// Postpone the event to allow scope.value to be updated, so
// the event can operate relevant value.
$timeout(function () {
scope.validate({
maValue: date ? date.format(format) : null
});
});
};
var changeDate = function () {
scope.isTouched = true;
var displayDate = dateElement.val().trim(),
isEmpty = displayDate === '',
hour = hasTime ? Number(hourElement.val()) : 0,
minute = hasTime ? Number(minuteElement.val()) : 0,
date = MaDate.createEmpty();
// Check time.
if (hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59) {
date = parseDate(displayDate);
date.offset(initialDateOffset);
} else {
scope.isValid = false;
return;
}
// Date is empty and remains unchanged.
if (isEmpty && previousDate.isEmpty()) {
validate(null);
return;
}
// Date has been emptied.
if (isEmpty) {
validate(date);
if (scope.isValid) {
setDisplayDate(null);
triggerChange();
}
return;
}
// Failed to parse the date.
if (date.isEmpty()) {
scope.isValid = false;
return;
}
if (!date.isEmpty() && (hasTime || initialDisplayDate === displayDate)) {
setDateTime(date);
// Substruct time zone offset.
date.subtract(timeZoneOffset - initialDateOffset, 'minute');
}
validate(date);
if (!hasDateChanged(date)) {
// Refresh diplay date in case the user changed its format, e.g.
// from 12 Oct 16 to 12Oct16. We need to set it back to 12 Oct 16.
setDisplayDate(date);
return;
}
if (!date.isEmpty()) {
setDisplayDate(date);
}
if (!scope.isValid) {
return;
}
triggerChange(date);
};
var focusDate = function () {
isDateFocused = true;
isHourFocused = false;
isMinuteFocused = false;
scope.onFocus();
};
var focusHour = function () {
isHourFocused = true;
isDateFocused = false;
isMinuteFocused = false;
scope.onFocus();
};
var focusMinute = function () {
isMinuteFocused = true;
isDateFocused = false;
isHourFocused = false;
scope.onFocus();
};
var blurDate = function () {
isDateFocused = false;
scope.onBlur();
};
var blurHour = function () {
isHourFocused = false;
scope.onBlur();
};
var blurMinute = function () {
isMinuteFocused = false;
scope.onBlur();
};
var addFocusEvent = function () {
// Remove the event in case it exists.
removeFocusEvent();
$('.ma-date-box-date', element).on('focus', focusDate);
if (hasTime) {
$('.ma-date-box-hour', element).on('focus', focusHour);
$('.ma-date-box-minute', element).on('focus', focusMinute);
}
};
var removeFocusEvent = function () {
$('.ma-date-box-date', element).off('focus', focusDate);
if (hasTime) {
$('.ma-date-box-hour', element).off('focus', focusHour);
$('.ma-date-box-minute', element).off('focus', focusMinute);
}
};
var addBlurEvent = function () {
// Remove the event in case it exists.
removeBlurEvent();
$('.ma-date-box-date', element).on('blur', blurDate);
if (hasTime) {
$('.ma-date-box-hour', element).on('blur', blurHour);
$('.ma-date-box-minute', element).on('blur', blurMinute);
}
};
var removeBlurEvent = function () {
$('.ma-date-box-date', element).off('blur', blurDate);
if (hasTime) {
$('.ma-date-box-hour', element).off('blur', blurHour);
$('.ma-date-box-minute', element).off('blur', blurMinute);
}
};
var setModifiers = function (oldModifiers, newModifiers) {
// Remove previous modifiers first.
if (!MaHelper.isNullOrWhiteSpace(oldModifiers)) {
oldModifiers = oldModifiers.split(' ');
for (var i = 0; i < oldModifiers.length; i++) {
element.removeClass('ma-date-box-' + oldModifiers[i]);
}
}
var modifiers = '';
if (!MaHelper.isNullOrWhiteSpace(newModifiers)) {
modifiers = scope.modifier.split(' ');
}
for (var j = 0; j < modifiers.length; j++) {
element.addClass('ma-date-box-' + modifiers[j]);
}
};
var setEventDates = function () {
eventDates = [];
if (scope.eventDates && scope.eventDates.length) {
for (var i = 0; i < scope.eventDates.length; i++) {
var event = new MaDate(scope.eventDates[i]);
eventDates.push(event.format('ddd') + ' ' + event.format('MMM dd yyyy'));
}
}
// Refresh calendar.
if (picker && picker._o) {
picker._o.events = eventDates;
picker.draw();
}
};
setValidators();
scope.isFocused = false;
scope.isValid = true;
scope.isTouched = false;
scope.hasValue = function () {
if (hasTime) {
return (dateElement.val() || hourElement.val() !== '00' || minuteElement.val() !== '00') &&
!scope.isLoading;
}
return dateElement.val() && !scope.isLoading;
};
scope.isResetEnabled = function () {
if (hasTime) {
return scope.isDisabled !== 'true' &&
(dateElement.val() || hourElement.val() !== '00' || minuteElement.val() !== '00');
}
return scope.isDisabled !== 'true' && dateElement.val();
};
scope.onFocus = function () {
// Use safeApply to avoid apply error when Reset icon is clicked.
MaHelper.safeApply(function () {
scope.isFocused = true;
});
};
scope.onBlur = function () {
// Cancel change if it is already in process to prevent the event from firing twice.
if (changePromise) {
$timeout.cancel(changePromise);
}
scope.$apply(function () {
scope.isFocused = false;
changeDate();
});
};
scope.onKeydown = function (event) {
// Ignore tab key.
if (event.keyCode === MaHelper.keyCode.tab || event.keyCode === MaHelper.keyCode.shift) {
return;
}
keydownValue = angular.element(event.target).val();
};
scope.onKeyup = function (event) {
// Ignore tab key.
if (event.keyCode === MaHelper.keyCode.tab || event.keyCode === MaHelper.keyCode.shift) {
return;
}
var hasValueChanged = false;
keyupValue = angular.element(event.target).val();
if (keydownValue !== keyupValue) {
hasValueChanged = true;
scope.isTouched = true;
resetInitialDateOffset();
}
// Change value after a timeout while the user is typing.
if (hasValueChanged && changeTimeout > 0) {
dateCaretPosition = dateElement.prop('selectionStart');
if (hasTime) {
hourCaretPosition = hourElement.prop('selectionStart');
minuteCaretPosition = minuteElement.prop('selectionStart');
}
if (changePromise) {
$timeout.cancel(changePromise);
}
changePromise = $timeout(function () {
changeDate();
}, changeTimeout);
}
};
scope.onTimeKeydown = function (event) {
if (
// Allow backspace, tab, delete.
$.inArray(event.keyCode, [MaHelper.keyCode.backspace, MaHelper.keyCode.tab, MaHelper.keyCode.delete]) !== -1 ||
// Allow left, right.
(event.keyCode === 37 || event.keyCode === 39)) {
return;
}
// Ensure that it is a number and stop the keypress.
if ((event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
};
scope.onReset = function () {
if (scope.isDisabled === 'true') {
return;
}
previousDate = MaDate.createEmpty();
scope.isTouched = true;
validate(null);
triggerChange();
setDisplayDate(null);
dateElement.focus();
};
// Set initial date.
if (scope.value) {
var date = parseDate(scope.value);
if (!date.isEmpty()) {
setDisplayDate(date);
previousDate = date;
initialDateOffset = date.offset();
}
}
addFocusEvent();
addBlurEvent();
$timeout(function () {
if (scope.isDisabled !== 'true') {
initializePikaday();
}
// Move id to input.
element.removeAttr('id');
dateElement.attr('id', scope.id);
});
scope.$watch('value', function (newDate, oldDate) {
if (newDate === null && oldDate === null) {
return;
}
var date = parseDate(newDate);
if (date.isEmpty()) {
previousDate = MaDate.createEmpty();
setDisplayDate(null);
}
// Validate date to make it valid in case it was invalid before or vice versa.
// Pass false as second parameter to avoid loop from triggering validate event.
validate(date, false);
if (!hasDateChanged(date)) {
setDisplayDate(date);
return;
}
setDisplayDate(date);
previousDate = date;
initialDateOffset = date.offset();
});
attributes.$observe('isDisabled', function (newValue, oldValue) {
if (newValue === oldValue) {
return;
}
if (scope.isDisabled === 'true') {
destroyPikaday();
} else {
if (!isDisabledObserverFirstRun) {
initializePikaday();
}
}
isDisabledObserverFirstRun = false;
});
var minMaxDateObserver = function (newValue, oldValue, dateName) {
if (newValue === oldValue) {
return;
}
var date = parseDate(dateElement.val().trim());
date.offset(timeZoneOffset);
if (hasTime) {
setDateTime(date);
}
if (dateName === 'max') {
setMaxDate();
} else {
setMinDate();
}
setValidators();
// Run only min/max validators to avoid the component being highligthed as invalid
// by other validators like IsNotEmpty, when minDate/maxDate is changed.
var minMaxValidators = [];
for (var i = 0; i < validators.length; i++) {
if (validators[i].name === 'IsGreaterOrEqual' || validators[i].name === 'IsLessOrEqual') {
minMaxValidators.push(validators[i]);
}
}
if (minMaxValidators.length) {
var formattedDate = date.format(format);
// Empty failedValidator if it is min/max validator.
if (failedValidator && (failedValidator.name === 'IsGreaterOrEqual' || failedValidator.name === 'IsLessOrEqual')) {
failedValidator = null;
scope.isValid = true;
}
for (i = 0; i < minMaxValidators.length; i++) {
if (!minMaxValidators[i].validate(formattedDate)) {
scope.isValid = false;
failedValidator = minMaxValidators[i];
break;
}
}
if (!scope.isValid) {
scope.isTouched = true;
}
triggerValidate(date);
}
if (scope.isValid && hasDateChanged(date)) {
triggerChange(date);
}
};
attributes.$observe('min', function (newValue) {
var oldValue = _min;
_min = newValue;
minMaxDateObserver(_min, oldValue, 'min');
});
attributes.$observe('max', function (newValue) {
var oldValue = _max;
_max = newValue;
minMaxDateObserver(_max, oldValue, 'max');
});
attributes.$observe('modifier', function (newValue) {
var oldValue = _modifier;
if (newValue === oldValue) {
return;
}
_modifier = newValue;
setModifiers(oldValue, _modifier);
});
scope.$watch('eventDates', function (newValue, oldValue) {
if (scope.isDisabled === 'true' || angular.equals(newValue, oldValue)) {
return;
}
setEventDates();
}, true);
scope.$watch('disabledDates', function (newValue, oldValue) {
if (scope.isDisabled === 'true' || angular.equals(newValue, oldValue)) {
return;
}
setValidators();
// Run only IsDisabled validator to avoid the component being highligthed as invalid
// by other validators like IsNotEmpty.
var validator;
for (var i = 0; i < validators.length; i++) {
if (validators[i].name === 'IsDisabled') {
validator = validators[i];
}
}
if (validator) {
var date = parseDate(dateElement.val().trim());
date.offset(timeZoneOffset);
var formattedDate = date.format(format);
if (failedValidator && failedValidator.name === validator.name) {
failedValidator = null;
scope.isValid = true;
}
if (!validator.validate(formattedDate)) {
scope.isValid = false;
failedValidator = validator;
}
if (!scope.isValid) {
scope.isTouched = true;
}
triggerValidate(date);
}
}, true);
setEventDates();
// Prepare API instance.
if (scope.instance) {
scope.instance.isInitialized = true;
scope.instance.isEditor = function () {
return true;
};
scope.instance.validate = function () {
scope.isTouched = true;
// Use display date, as scope date can't be invalid, because
// we don't update scope value when display date is invalid.
var date = getDisplayDate();
if (!date || (isRequired && date.isEmpty())) {
scope.isValid = false;
return;
}
// Prevent loop that might occur if validate method is invoked
// from validate event from outside.
validate(date, false);
};
scope.instance.isValid = function () {
return scope.isValid;
};
scope.instance.failedValidator = function () {
return failedValidator;
};
scope.instance.refresh = function () {
var date = parseDate(scope.value);
setDisplayDate(date);
validate(date, false);
};
// User typed value, that hasn't gone through validation.
scope.instance.rawValue = function (value) {
if (arguments.length === 1) {
dateElement.val(value);
} else {
return dateElement.val();
}
};
}
}
};
}]); |
public static int calculate(int x, int y, String modifier) {
switch(modifier) {
case "add":
return x + y;
case "subtract":
return x - y;
case "multiply":
return x * y;
case "divide":
return x / y;
default:
throw new IllegalArgumentException("Modifier must be 'add', 'subtract', 'multiply' or 'divide'");
}
} |
<reponame>ccpaging/nxlog4go<filename>file/next_time_test.go
// Copyright (C) 2017, ccpaging <<EMAIL>>. All rights reserved.
package file
import (
"testing"
"time"
)
var now = time.Unix(0, 1234567890123456789).In(time.UTC)
func nextTime(now time.Time, cycle, clock int64) time.Time {
if cycle < 5 {
cycle = 5
}
if cycle < dayToSecs {
// Now + cycle
return now.Add(time.Duration(cycle) * time.Second)
}
// now + cycle
t := now.Add(time.Duration(cycle) * time.Second)
// back to midnight
t = time.Date(t.Year(), t.Month(), t.Day(),
0, 0, 0, 0, t.Location())
// midnight + cycle % 86400
t = t.Add(time.Duration(clock) * time.Second)
return t
}
func TestNextTime(t *testing.T) {
d0, d1 := nextTime(now, 600, -1).Sub(now), time.Duration(10*time.Minute)
if d0 != d1 {
t.Errorf("Incorrect nextTime duration (10 minutes): %v should be %v", d0, d1)
}
// Correct invalid value cycle = 300,clock = 0 to clock = -1
// for cycle < 86400
d0, d1 = nextTime(now, 300, 0).Sub(now), time.Duration(5*time.Minute)
if d0 != d1 {
t.Errorf("Incorrect nextTime duration (5 minutes): %v should be %v", d0, d1)
}
t1 := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location())
d0, d1 = nextTime(now, 86400, 0).Sub(now), t1.Sub(now)
if d0 != d1 {
t.Errorf("Incorrect nextTime duration (next midnight): %v should be %v", d0, d1)
}
t1 = time.Date(now.Year(), now.Month(), now.Day()+1, 3, 0, 0, 0, now.Location())
d0, d1 = nextTime(now, 86400, 10800).Sub(now), t1.Sub(now)
if d0 != d1 {
t.Errorf("Incorrect nextTime duration (next 3:00am): %v should be %v", d0, d1)
}
t1 = time.Date(now.Year(), now.Month(), now.Day()+7, 0, 0, 0, 0, now.Location())
d0, d1 = nextTime(now, 86400*7, 0).Sub(now), t1.Sub(now)
if d0 != d1 {
t.Errorf("Incorrect nextTime duration (next weekly midnight): %v should be %v", d0, d1)
}
}
|
package com.devaneios.turmadeelite.entities;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "achievement")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Achievement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@EqualsAndHashCode.Include
private Long id;
private String name;
private String description;
private LocalDateTime beforeAt;
private Integer earlierOf;
private Integer bestOf;
private Double averageGradeGreaterOrEqualsThan;
private Boolean isActive;
private String iconName;
private String externalSchoolClassId;
private String externalActivityId;
@ManyToOne
@JoinColumn(name = "class_id")
private SchoolClass schoolClass;
@ManyToOne
@JoinColumn(name = "activity_id")
private Activity activity;
@ManyToOne
@JoinColumn(name = "teacher_id")
private Teacher teacher;
@ManyToMany(mappedBy = "studentAchievements")
Set<Student> students = new HashSet<>();
} |
<gh_stars>1-10
package be.kwakeroni.evelyn.model.impl;
import be.kwakeroni.evelyn.model.ParseException;
import be.kwakeroni.evelyn.storage.Storage;
import be.kwakeroni.evelyn.test.SilentCloseable;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.extension.mockito.MockitoExtension;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;
import static be.kwakeroni.evelyn.test.Assertions.*;
import static be.kwakeroni.evelyn.test.TestModel.STORAGE_SOURCE;
import static be.kwakeroni.evelyn.test.TestModel.asStorage;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
public class FileStructureTest {
@Test
@DisplayName("Reads common attributes")
public void testCreateFrom() throws Exception {
Map<String, String> attributes = readAttributesFrom(
"!evelyn-db",
"!version=x.y",
"!name=myDb"
);
assertThat(attributes).containsOnly(
entry("version", "x.y"),
entry("name", "myDb"));
}
@Test
@DisplayName("Reads custom attributes")
public void testCustomAttributes() throws Exception {
Map<String, String> attributes = readAttributesFrom(
"!evelyn-db",
"!version=x.y",
"!name=myDb",
"!custom=customValue"
);
assertThat(attributes.get("custom")).isEqualTo("customValue");
}
@Test
@DisplayName("Reads no data if there is none")
public void testNoData() throws Exception {
FileStructure.StreamData streamData = readDataFrom(
"!evelyn-db",
"!version=x.y",
"!name=myDb",
"!data"
);
assertThat(streamData.dataStream).isEmpty();
assertThat(streamData.linePointer).isEqualTo(4);
}
@Test
@DisplayName("Reads data")
public void testWithData() throws Exception {
FileStructure.StreamData streamData = readDataFrom(
"!evelyn-db",
"!version=x.y",
"!name=myDb",
"!data",
"ABC",
"DEF"
);
assertThat(streamData.dataStream).containsExactly("ABC", "DEF");
assertThat(streamData.linePointer).isEqualTo(4);
}
@Nested
@DisplayName("Throws parsing errors")
class ParseErrorTest {
@Test
@DisplayName("for empty file")
public void testEmptyFileError() {
assertThatParseExceptionThrownBy(reading(/* no data */))
.hasLine(1)
.hasPosition(1)
.hasSource(STORAGE_SOURCE);
}
@Test
@DisplayName("for unrecognized header")
public void testWrongHeader() {
assertThatParseExceptionThrownBy(
reading("!version=x.y"
))
.hasLine(1)
.hasSource(STORAGE_SOURCE);
}
@Test
@DisplayName("for unrecognized line")
public void testWrongAttributeLine() {
assertThatParseExceptionThrownBy(
reading("!evelyn-db",
"!version=x.y",
"@name=myDb"
))
.hasLine(3)
.hasPosition(1)
.hasSource(STORAGE_SOURCE);
}
@Test
@DisplayName("for missing attribute value")
public void testMissingAttributeValue() {
assertThatParseExceptionThrownBy(
reading("!evelyn-db",
"!version:x.y",
"!name=myDb"
))
.hasLine(2)
.hasPosition(12)
.hasSource(STORAGE_SOURCE);
}
@Test
@DisplayName("for '=' in attribute value")
public void testMultipleEqualsSigns() {
assertThatParseExceptionThrownBy(
reading("!evelyn-db",
"!version=x.y",
"!name=my=Db"
))
.hasLine(3)
.hasPosition(9)
.hasSource(STORAGE_SOURCE);
}
@Test
@DisplayName("for duplicate attribute")
public void testDuplicateAttribute() {
assertThatParseExceptionThrownBy(
reading("!evelyn-db",
"!version=x.y",
"!att=value",
"!version=x.y"
))
.hasLine(4)
.hasSource(STORAGE_SOURCE);
}
}
@Nested
@DisplayName("Closes backing resource")
class CloseResourceTest {
@Test
@DisplayName("after retrieving attributes")
public void closesAfterAttributes(@Mock SilentCloseable resource) throws Exception {
Map<String, String> attributes = readAttributesFrom(resource,
"!evelyn-db",
"!version=x.y",
"!name=myDb",
"!data",
"ABC",
"DEF");
verify(resource).close();
}
@Test
@DisplayName("after closing data stream")
public void closesAfterDataStream(@Mock SilentCloseable resource) throws Exception {
FileStructure.StreamData streamData = readDataFrom(resource,
"!evelyn-db",
"!version=x.y",
"!name=myDb",
"!data",
"ABC",
"DEF");
try (Stream<String> toClose = streamData.dataStream) {
verify(resource, never()).close();
}
verify(resource).close();
}
}
@Nested
@DisplayName("writes to storage")
class WriteTest {
@Test
@DisplayName("initialization of headers")
public void initializesStorage(@Mock Storage storage) throws Exception {
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("version", "x.y");
attributes.put("name", "myDb");
attributes.put("custom", "myValue");
getInstance().initializeStorage(storage, attributes, "version");
InOrder inOrder = Mockito.inOrder(storage);
inOrder.verify(storage).writeHeader("x.y");
inOrder.verify(storage).append("!name=myDb");
inOrder.verify(storage).append("!custom=myValue");
inOrder.verify(storage).append("!data");
}
}
private FileStructure getInstance() {
return FileStructure.getInstance();
}
private Map<String, String> readAttributesFrom(String... contents) throws ParseException {
return getInstance().readAttributes(asStorage(contents));
}
private Map<String, String> readAttributesFrom(SilentCloseable resource, String... contents) throws ParseException {
return getInstance().readAttributes(asStorage(resource, contents));
}
private FileStructure.StreamData readDataFrom(String... contents) throws ParseException {
return getInstance().readData(asStorage(contents), Charset.defaultCharset());
}
private FileStructure.StreamData readDataFrom(SilentCloseable resource, String... contents) throws ParseException {
return getInstance().readData(asStorage(resource, contents), Charset.defaultCharset());
}
private ThrowableAssert.ThrowingCallable reading(String... contents) {
return () -> getInstance().readAttributes(asStorage(contents));
}
}
|
<gh_stars>10-100
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.maths.commonapi.exceptions;
/**
* Provides a manner in which maths exceptions can be thrown.
*/
public class MathsExceptionGeneric extends RuntimeException {
private static final long serialVersionUID = 1L;
public MathsExceptionGeneric() {
super();
}
public MathsExceptionGeneric(final String s) {
super(s);
}
public MathsExceptionGeneric(final String s, final Throwable cause) {
super(s, cause);
}
public MathsExceptionGeneric(final Throwable cause) {
super(cause);
}
}
|
def add_book_to_library(book):
db.session.add(book)
db.session.commit() |
<reponame>wujia28762/Tmate<gh_stars>0
package com.honyum.elevatorMan.net;
import com.honyum.elevatorMan.data.AlarmInfo;
import com.honyum.elevatorMan.data.AlarmInfo1;
import com.honyum.elevatorMan.data.BranchInfo;
import com.honyum.elevatorMan.net.base.Response;
import java.util.List;
/**
* Created by Star on 2017/6/15.
*/
public class GetAlarmListResponse extends Response {
public List<AlarmInfo1> getBody() {
return body;
}
public void setBody(List<AlarmInfo1> body) {
this.body = body;
}
private List<AlarmInfo1> body;
/**
* 根据json生成对象
* @param json
* @return
*/
public static GetAlarmListResponse getAlarmListResponse(String json) {
return (GetAlarmListResponse) parseFromJson(GetAlarmListResponse.class, json);
}
}
|
import { combineReducers } from 'redux';
import * as NS from '../../namespace';
import { initial } from '../data/initial';
import { ReducersMap } from 'shared/types/redux';
import makeCommunicationReducer from 'shared/helpers/redux/communication/makeCommunicationReducer';
// tslint:disable:max-line-length
export default combineReducers<NS.IReduxState['communication']>({
cancelOrder: makeCommunicationReducer<NS.ICancelOrder, NS.ICancelOrderCompleted, NS.ICancelOrderFailed>(
'ORDERS:CANCEL_ORDER',
'ORDERS:CANCEL_ORDER_COMPLETED',
'ORDERS:CANCEL_ORDER_FAILED',
initial.communication.cancelOrder,
),
cancelAllOrders: makeCommunicationReducer<NS.ICancelAllOrders, NS.ICancelAllOrdersCompleted, NS.ICancelAllOrdersFailed>(
'ORDERS:CANCEL_ALL_ORDERS',
'ORDERS:CANCEL_ALL_ORDERS_COMPLETED',
'ORDERS:CANCEL_ALL_ORDERS_FAILED',
initial.communication.cancelOrder,
),
} as ReducersMap<NS.IReduxState['communication']>);
|
#!/bin/bash
appium &
APPIUM_PID=$!
xcrun simctl boot 'iPhone 7'
npx lerna run dextrose-clean
npx lerna run dextrose-stories --since
npm run fetch-fonts
npx rnstl --searchDir ./packages --pattern './*/*.dextrose.tmp.js' --outputFile ./fructose/components.js
npx compile-tests -d fructose
export CWD=$(pwd)
export FRC=$CWD/fructose
npx react-native start --root fructose --projectRoots $(pwd)/fructose,$(pwd) &
react-native run-ios --no-packager
PACKAGER_PID=$!
LOGLEVEL=verbose npx dextrose --config ./dextrose/dextrose.ios.js --snapshotWait 2000
npx lerna run dextrose-clean
kill -9 $PACKAGER_PID
xcrun simctl shutdown booted
kill -9 $APPIUM_PID |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Sudoku_Final;
import javax.swing.JOptionPane;
/**
*
* @author Admin
*/
public class Sudoku_Solve extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
Kernel ker = new Kernel();
int [][] sudoku = new int[9][9];
public Sudoku_Solve() {
initComponents();
updateGui();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
jTextField6 = new javax.swing.JTextField();
jTextField7 = new javax.swing.JTextField();
jTextField8 = new javax.swing.JTextField();
jTextField9 = new javax.swing.JTextField();
jTextField10 = new javax.swing.JTextField();
jTextField11 = new javax.swing.JTextField();
jTextField12 = new javax.swing.JTextField();
jTextField13 = new javax.swing.JTextField();
jTextField14 = new javax.swing.JTextField();
jTextField15 = new javax.swing.JTextField();
jTextField16 = new javax.swing.JTextField();
jTextField17 = new javax.swing.JTextField();
jTextField18 = new javax.swing.JTextField();
jTextField19 = new javax.swing.JTextField();
jTextField20 = new javax.swing.JTextField();
jTextField21 = new javax.swing.JTextField();
jTextField22 = new javax.swing.JTextField();
jTextField23 = new javax.swing.JTextField();
jTextField24 = new javax.swing.JTextField();
jTextField25 = new javax.swing.JTextField();
jTextField26 = new javax.swing.JTextField();
jTextField27 = new javax.swing.JTextField();
jTextField28 = new javax.swing.JTextField();
jTextField29 = new javax.swing.JTextField();
jTextField30 = new javax.swing.JTextField();
jTextField31 = new javax.swing.JTextField();
jTextField32 = new javax.swing.JTextField();
jTextField33 = new javax.swing.JTextField();
jTextField34 = new javax.swing.JTextField();
jTextField35 = new javax.swing.JTextField();
jTextField36 = new javax.swing.JTextField();
jTextField37 = new javax.swing.JTextField();
jTextField38 = new javax.swing.JTextField();
jTextField39 = new javax.swing.JTextField();
jTextField40 = new javax.swing.JTextField();
jTextField41 = new javax.swing.JTextField();
jTextField42 = new javax.swing.JTextField();
jTextField43 = new javax.swing.JTextField();
jTextField44 = new javax.swing.JTextField();
jTextField45 = new javax.swing.JTextField();
jTextField46 = new javax.swing.JTextField();
jTextField47 = new javax.swing.JTextField();
jTextField48 = new javax.swing.JTextField();
jTextField49 = new javax.swing.JTextField();
jTextField50 = new javax.swing.JTextField();
jTextField51 = new javax.swing.JTextField();
jTextField52 = new javax.swing.JTextField();
jTextField53 = new javax.swing.JTextField();
jTextField54 = new javax.swing.JTextField();
jTextField55 = new javax.swing.JTextField();
jTextField56 = new javax.swing.JTextField();
jTextField57 = new javax.swing.JTextField();
jTextField58 = new javax.swing.JTextField();
jTextField59 = new javax.swing.JTextField();
jTextField60 = new javax.swing.JTextField();
jTextField61 = new javax.swing.JTextField();
jTextField62 = new javax.swing.JTextField();
jTextField63 = new javax.swing.JTextField();
jTextField64 = new javax.swing.JTextField();
jTextField65 = new javax.swing.JTextField();
jTextField66 = new javax.swing.JTextField();
jTextField67 = new javax.swing.JTextField();
jTextField68 = new javax.swing.JTextField();
jTextField69 = new javax.swing.JTextField();
jTextField70 = new javax.swing.JTextField();
jTextField71 = new javax.swing.JTextField();
jTextField72 = new javax.swing.JTextField();
jTextField73 = new javax.swing.JTextField();
jTextField74 = new javax.swing.JTextField();
jTextField75 = new javax.swing.JTextField();
jTextField76 = new javax.swing.JTextField();
jTextField77 = new javax.swing.JTextField();
jTextField78 = new javax.swing.JTextField();
jTextField79 = new javax.swing.JTextField();
jTextField80 = new javax.swing.JTextField();
jTextField81 = new javax.swing.JTextField();
JButton1 = new javax.swing.JButton();
JButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new java.awt.GridLayout(9, 9));
jPanel1.add(jTextField1);
jPanel1.add(jTextField2);
jPanel1.add(jTextField3);
jTextField4.setBackground(new java.awt.Color(0, 0, 0));
jTextField4.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField4);
jTextField5.setBackground(new java.awt.Color(0, 0, 0));
jTextField5.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField5);
jTextField6.setBackground(new java.awt.Color(0, 0, 0));
jTextField6.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField6);
jPanel1.add(jTextField7);
jPanel1.add(jTextField8);
jPanel1.add(jTextField9);
jPanel1.add(jTextField10);
jPanel1.add(jTextField11);
jPanel1.add(jTextField12);
jTextField13.setBackground(new java.awt.Color(0, 0, 0));
jTextField13.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField13);
jTextField14.setBackground(new java.awt.Color(0, 0, 0));
jTextField14.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField14);
jTextField15.setBackground(new java.awt.Color(0, 0, 0));
jTextField15.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField15);
jPanel1.add(jTextField16);
jPanel1.add(jTextField17);
jPanel1.add(jTextField18);
jPanel1.add(jTextField19);
jPanel1.add(jTextField20);
jPanel1.add(jTextField21);
jTextField22.setBackground(new java.awt.Color(0, 0, 0));
jTextField22.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField22);
jTextField23.setBackground(new java.awt.Color(0, 0, 0));
jTextField23.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField23);
jTextField24.setBackground(new java.awt.Color(0, 0, 0));
jTextField24.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField24);
jPanel1.add(jTextField25);
jPanel1.add(jTextField26);
jPanel1.add(jTextField27);
jTextField28.setBackground(new java.awt.Color(0, 0, 0));
jTextField28.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField28);
jTextField29.setBackground(new java.awt.Color(0, 0, 0));
jTextField29.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField29);
jTextField30.setBackground(new java.awt.Color(0, 0, 0));
jTextField30.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField30);
jPanel1.add(jTextField31);
jPanel1.add(jTextField32);
jPanel1.add(jTextField33);
jTextField34.setBackground(new java.awt.Color(0, 0, 0));
jTextField34.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField34);
jTextField35.setBackground(new java.awt.Color(0, 0, 0));
jTextField35.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField35);
jTextField36.setBackground(new java.awt.Color(0, 0, 0));
jTextField36.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField36);
jTextField37.setBackground(new java.awt.Color(0, 0, 0));
jTextField37.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField37);
jTextField38.setBackground(new java.awt.Color(0, 0, 0));
jTextField38.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField38);
jTextField39.setBackground(new java.awt.Color(0, 0, 0));
jTextField39.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField39);
jPanel1.add(jTextField40);
jPanel1.add(jTextField41);
jPanel1.add(jTextField42);
jTextField43.setBackground(new java.awt.Color(0, 0, 0));
jTextField43.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField43);
jTextField44.setBackground(new java.awt.Color(0, 0, 0));
jTextField44.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField44);
jTextField45.setBackground(new java.awt.Color(0, 0, 0));
jTextField45.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField45);
jTextField46.setBackground(new java.awt.Color(0, 0, 0));
jTextField46.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField46);
jTextField47.setBackground(new java.awt.Color(0, 0, 0));
jTextField47.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField47);
jTextField48.setBackground(new java.awt.Color(0, 0, 0));
jTextField48.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField48);
jPanel1.add(jTextField49);
jPanel1.add(jTextField50);
jPanel1.add(jTextField51);
jTextField52.setBackground(new java.awt.Color(0, 0, 0));
jTextField52.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField52);
jTextField53.setBackground(new java.awt.Color(0, 0, 0));
jTextField53.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField53);
jTextField54.setBackground(new java.awt.Color(0, 0, 0));
jTextField54.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField54);
jPanel1.add(jTextField55);
jPanel1.add(jTextField56);
jPanel1.add(jTextField57);
jTextField58.setBackground(new java.awt.Color(0, 0, 0));
jTextField58.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField58);
jTextField59.setBackground(new java.awt.Color(0, 0, 0));
jTextField59.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField59);
jTextField60.setBackground(new java.awt.Color(0, 0, 0));
jTextField60.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField60);
jPanel1.add(jTextField61);
jPanel1.add(jTextField62);
jPanel1.add(jTextField63);
jPanel1.add(jTextField64);
jPanel1.add(jTextField65);
jPanel1.add(jTextField66);
jTextField67.setBackground(new java.awt.Color(0, 0, 0));
jTextField67.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField67);
jTextField68.setBackground(new java.awt.Color(0, 0, 0));
jTextField68.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField68);
jTextField69.setBackground(new java.awt.Color(0, 0, 0));
jTextField69.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField69);
jPanel1.add(jTextField70);
jPanel1.add(jTextField71);
jPanel1.add(jTextField72);
jPanel1.add(jTextField73);
jPanel1.add(jTextField74);
jPanel1.add(jTextField75);
jTextField76.setBackground(new java.awt.Color(0, 0, 0));
jTextField76.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField76);
jTextField77.setBackground(new java.awt.Color(0, 0, 0));
jTextField77.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField77);
jTextField78.setBackground(new java.awt.Color(0, 0, 0));
jTextField78.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jTextField78);
jPanel1.add(jTextField79);
jPanel1.add(jTextField80);
jPanel1.add(jTextField81);
JButton1.setText("Exit");
JButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton1ActionPerformed(evt);
}
});
JButton2.setText("Solve");
JButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(65, 65, 65)
.addComponent(JButton2)
.addGap(42, 42, 42)
.addComponent(JButton1)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JButton1)
.addComponent(JButton2))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void JButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JButton1ActionPerformed
this.dispose();
//new two().setVisible(true);
}//GEN-LAST:event_JButton1ActionPerformed
private void JButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JButton2ActionPerformed
// TODO add your handling code here:
update();
boolean result = new Violater().Validate(sudoku);
if(result)
sudoku = ker.sudokuSolver(sudoku);
else
JOptionPane.showMessageDialog(null, "Invalid sudoku");
updateGui();
}//GEN-LAST:event_JButton2ActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton JButton1;
private javax.swing.JButton JButton2;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField10;
private javax.swing.JTextField jTextField11;
private javax.swing.JTextField jTextField12;
private javax.swing.JTextField jTextField13;
private javax.swing.JTextField jTextField14;
private javax.swing.JTextField jTextField15;
private javax.swing.JTextField jTextField16;
private javax.swing.JTextField jTextField17;
private javax.swing.JTextField jTextField18;
private javax.swing.JTextField jTextField19;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField20;
private javax.swing.JTextField jTextField21;
private javax.swing.JTextField jTextField22;
private javax.swing.JTextField jTextField23;
private javax.swing.JTextField jTextField24;
private javax.swing.JTextField jTextField25;
private javax.swing.JTextField jTextField26;
private javax.swing.JTextField jTextField27;
private javax.swing.JTextField jTextField28;
private javax.swing.JTextField jTextField29;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField30;
private javax.swing.JTextField jTextField31;
private javax.swing.JTextField jTextField32;
private javax.swing.JTextField jTextField33;
private javax.swing.JTextField jTextField34;
private javax.swing.JTextField jTextField35;
private javax.swing.JTextField jTextField36;
private javax.swing.JTextField jTextField37;
private javax.swing.JTextField jTextField38;
private javax.swing.JTextField jTextField39;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField40;
private javax.swing.JTextField jTextField41;
private javax.swing.JTextField jTextField42;
private javax.swing.JTextField jTextField43;
private javax.swing.JTextField jTextField44;
private javax.swing.JTextField jTextField45;
private javax.swing.JTextField jTextField46;
private javax.swing.JTextField jTextField47;
private javax.swing.JTextField jTextField48;
private javax.swing.JTextField jTextField49;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField50;
private javax.swing.JTextField jTextField51;
private javax.swing.JTextField jTextField52;
private javax.swing.JTextField jTextField53;
private javax.swing.JTextField jTextField54;
private javax.swing.JTextField jTextField55;
private javax.swing.JTextField jTextField56;
private javax.swing.JTextField jTextField57;
private javax.swing.JTextField jTextField58;
private javax.swing.JTextField jTextField59;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField jTextField60;
private javax.swing.JTextField jTextField61;
private javax.swing.JTextField jTextField62;
private javax.swing.JTextField jTextField63;
private javax.swing.JTextField jTextField64;
private javax.swing.JTextField jTextField65;
private javax.swing.JTextField jTextField66;
private javax.swing.JTextField jTextField67;
private javax.swing.JTextField jTextField68;
private javax.swing.JTextField jTextField69;
private javax.swing.JTextField jTextField7;
private javax.swing.JTextField jTextField70;
private javax.swing.JTextField jTextField71;
private javax.swing.JTextField jTextField72;
private javax.swing.JTextField jTextField73;
private javax.swing.JTextField jTextField74;
private javax.swing.JTextField jTextField75;
private javax.swing.JTextField jTextField76;
private javax.swing.JTextField jTextField77;
private javax.swing.JTextField jTextField78;
private javax.swing.JTextField jTextField79;
private javax.swing.JTextField jTextField8;
private javax.swing.JTextField jTextField80;
private javax.swing.JTextField jTextField81;
private javax.swing.JTextField jTextField9;
// End of variables declaration//GEN-END:variables
private void update() {
sudoku[0][0] = Integer.parseInt(String.valueOf(((jTextField1.getText()).charAt(0))));
sudoku[0][1] = Integer.parseInt(String.valueOf((jTextField2.getText()).charAt(0)));
sudoku[0][2] = Integer.parseInt(String.valueOf((jTextField3.getText()).charAt(0)));
sudoku[0][3] = Integer.parseInt(String.valueOf((jTextField4.getText()).charAt(0)));
sudoku[0][4] = Integer.parseInt(String.valueOf((jTextField5.getText()).charAt(0)));
sudoku[0][5] = Integer.parseInt(String.valueOf((jTextField6.getText()).charAt(0)));
sudoku[0][6] = Integer.parseInt(String.valueOf((jTextField7.getText()).charAt(0)));
sudoku[0][7] = Integer.parseInt(String.valueOf((jTextField8.getText()).charAt(0)));
sudoku[0][8] = Integer.parseInt(String.valueOf((jTextField9.getText()).charAt(0)));
sudoku[1][0] = Integer.parseInt(String.valueOf((jTextField10.getText()).charAt(0)));
sudoku[1][1] = Integer.parseInt(String.valueOf((jTextField11.getText()).charAt(0)));
sudoku[1][2] = Integer.parseInt(String.valueOf((jTextField12.getText()).charAt(0)));
sudoku[1][3] = Integer.parseInt(String.valueOf((jTextField13.getText()).charAt(0)));
sudoku[1][4] = Integer.parseInt(String.valueOf((jTextField14.getText()).charAt(0)));
sudoku[1][5] = Integer.parseInt(String.valueOf((jTextField15.getText()).charAt(0)));
sudoku[1][6] = Integer.parseInt(String.valueOf((jTextField16.getText()).charAt(0)));
sudoku[1][7] = Integer.parseInt(String.valueOf((jTextField17.getText()).charAt(0)));
sudoku[1][8] = Integer.parseInt(String.valueOf((jTextField18.getText()).charAt(0)));
sudoku[2][0] = Integer.parseInt(String.valueOf((jTextField19.getText()).charAt(0)));
sudoku[2][1] = Integer.parseInt(String.valueOf((jTextField20.getText()).charAt(0)));
sudoku[2][2] = Integer.parseInt(String.valueOf((jTextField21.getText()).charAt(0)));
sudoku[2][3] = Integer.parseInt(String.valueOf((jTextField22.getText()).charAt(0)));
sudoku[2][4] = Integer.parseInt(String.valueOf((jTextField23.getText()).charAt(0)));
sudoku[2][5] = Integer.parseInt(String.valueOf((jTextField24.getText()).charAt(0)));
sudoku[2][6] = Integer.parseInt(String.valueOf((jTextField25.getText()).charAt(0)));
sudoku[2][7] = Integer.parseInt(String.valueOf((jTextField26.getText()).charAt(0)));
sudoku[2][8] = Integer.parseInt(String.valueOf((jTextField27.getText()).charAt(0)));
sudoku[3][0] = Integer.parseInt(String.valueOf((jTextField28.getText()).charAt(0)));
sudoku[3][1] = Integer.parseInt(String.valueOf((jTextField29.getText()).charAt(0)));
sudoku[3][2] = Integer.parseInt(String.valueOf((jTextField30.getText()).charAt(0)));
sudoku[3][3] = Integer.parseInt(String.valueOf((jTextField31.getText()).charAt(0)));
sudoku[3][4] = Integer.parseInt(String.valueOf((jTextField32.getText()).charAt(0)));
sudoku[3][5] = Integer.parseInt(String.valueOf((jTextField33.getText()).charAt(0)));
sudoku[3][6] = Integer.parseInt(String.valueOf((jTextField34.getText()).charAt(0)));
sudoku[3][7] = Integer.parseInt(String.valueOf((jTextField35.getText()).charAt(0)));
sudoku[3][8] = Integer.parseInt(String.valueOf((jTextField36.getText()).charAt(0)));
sudoku[4][0] = Integer.parseInt(String.valueOf((jTextField37.getText()).charAt(0)));
sudoku[4][1] = Integer.parseInt(String.valueOf((jTextField38.getText()).charAt(0)));
sudoku[4][2] = Integer.parseInt(String.valueOf((jTextField39.getText()).charAt(0)));
sudoku[4][3] = Integer.parseInt(String.valueOf((jTextField40.getText()).charAt(0)));
sudoku[4][4] = Integer.parseInt(String.valueOf((jTextField41.getText()).charAt(0)));
sudoku[4][5] = Integer.parseInt(String.valueOf((jTextField42.getText()).charAt(0)));
sudoku[4][6] = Integer.parseInt(String.valueOf((jTextField43.getText()).charAt(0)));
sudoku[4][7] = Integer.parseInt(String.valueOf((jTextField44.getText()).charAt(0)));
sudoku[4][8] = Integer.parseInt(String.valueOf((jTextField45.getText()).charAt(0)));
sudoku[5][0] = Integer.parseInt(String.valueOf((jTextField46.getText()).charAt(0)));
sudoku[5][1] = Integer.parseInt(String.valueOf((jTextField47.getText()).charAt(0)));
sudoku[5][2] = Integer.parseInt(String.valueOf((jTextField48.getText()).charAt(0)));
sudoku[5][3] = Integer.parseInt(String.valueOf((jTextField49.getText()).charAt(0)));
sudoku[5][4] = Integer.parseInt(String.valueOf((jTextField50.getText()).charAt(0)));
sudoku[5][5] = Integer.parseInt(String.valueOf((jTextField51.getText()).charAt(0)));
sudoku[5][6] = Integer.parseInt(String.valueOf((jTextField52.getText()).charAt(0)));
sudoku[5][7] = Integer.parseInt(String.valueOf((jTextField53.getText()).charAt(0)));
sudoku[5][8] = Integer.parseInt(String.valueOf((jTextField54.getText()).charAt(0)));
sudoku[6][0] = Integer.parseInt(String.valueOf((jTextField55.getText()).charAt(0)));
sudoku[6][1] = Integer.parseInt(String.valueOf((jTextField56.getText()).charAt(0)));
sudoku[6][2] = Integer.parseInt(String.valueOf((jTextField57.getText()).charAt(0)));
sudoku[6][3] = Integer.parseInt(String.valueOf((jTextField58.getText()).charAt(0)));
sudoku[6][4] = Integer.parseInt(String.valueOf((jTextField59.getText()).charAt(0)));
sudoku[6][5] = Integer.parseInt(String.valueOf((jTextField60.getText()).charAt(0)));
sudoku[6][6] = Integer.parseInt(String.valueOf((jTextField61.getText()).charAt(0)));
sudoku[6][7] = Integer.parseInt(String.valueOf((jTextField62.getText()).charAt(0)));
sudoku[6][8] = Integer.parseInt(String.valueOf((jTextField63.getText()).charAt(0)));
sudoku[7][0] = Integer.parseInt(String.valueOf((jTextField64.getText()).charAt(0)));
sudoku[7][1] = Integer.parseInt(String.valueOf((jTextField65.getText()).charAt(0)));
sudoku[7][2] = Integer.parseInt(String.valueOf((jTextField66.getText()).charAt(0)));
sudoku[7][3] = Integer.parseInt(String.valueOf((jTextField67.getText()).charAt(0)));
sudoku[7][4] = Integer.parseInt(String.valueOf((jTextField68.getText()).charAt(0)));
sudoku[7][5] = Integer.parseInt(String.valueOf((jTextField69.getText()).charAt(0)));
sudoku[7][6] = Integer.parseInt(String.valueOf((jTextField70.getText()).charAt(0)));
sudoku[7][7] = Integer.parseInt(String.valueOf((jTextField71.getText()).charAt(0)));
sudoku[7][8] = Integer.parseInt(String.valueOf((jTextField72.getText()).charAt(0)));
sudoku[8][0] = Integer.parseInt(String.valueOf((jTextField73.getText()).charAt(0)));
sudoku[8][1] = Integer.parseInt(String.valueOf((jTextField74.getText()).charAt(0)));
sudoku[8][2] = Integer.parseInt(String.valueOf((jTextField75.getText()).charAt(0)));
sudoku[8][3] = Integer.parseInt(String.valueOf((jTextField76.getText()).charAt(0)));
sudoku[8][4] = Integer.parseInt(String.valueOf((jTextField77.getText()).charAt(0)));
sudoku[8][5] = Integer.parseInt(String.valueOf((jTextField78.getText()).charAt(0)));
sudoku[8][6] = Integer.parseInt(String.valueOf((jTextField79.getText()).charAt(0)));
sudoku[8][7] = Integer.parseInt(String.valueOf((jTextField80.getText()).charAt(0)));
sudoku[8][8] = Integer.parseInt(String.valueOf((jTextField81.getText()).charAt(0)));
}
private void updateGui() {
jTextField1.setText(String.valueOf(sudoku[0][0]));
jTextField2.setText(String.valueOf(sudoku[0][1]));
jTextField3.setText(String.valueOf(sudoku[0][2]));
jTextField4.setText(String.valueOf(sudoku[0][3]));
jTextField5.setText(String.valueOf(sudoku[0][4]));
jTextField6.setText(String.valueOf(sudoku[0][5]));
jTextField7.setText(String.valueOf(sudoku[0][6]));
jTextField8.setText(String.valueOf(sudoku[0][7]));
jTextField9.setText(String.valueOf(sudoku[0][8]));
jTextField1.setText(String.valueOf(sudoku[0][0]));
jTextField2.setText(String.valueOf(sudoku[0][1]));
jTextField3.setText(String.valueOf(sudoku[0][2]));
jTextField4.setText(String.valueOf(sudoku[0][3]));
jTextField5.setText(String.valueOf(sudoku[0][4]));
jTextField6.setText(String.valueOf(sudoku[0][5]));
jTextField7.setText(String.valueOf(sudoku[0][6]));
jTextField8.setText(String.valueOf(sudoku[0][7]));
jTextField9.setText(String.valueOf(sudoku[0][8]));
jTextField10.setText(String.valueOf(sudoku[1][0]));
jTextField11.setText(String.valueOf(sudoku[1][1]));
jTextField12.setText(String.valueOf(sudoku[1][2]));
jTextField13.setText(String.valueOf(sudoku[1][3]));
jTextField14.setText(String.valueOf(sudoku[1][4]));
jTextField15.setText(String.valueOf(sudoku[1][5]));
jTextField16.setText(String.valueOf(sudoku[1][6]));
jTextField17.setText(String.valueOf(sudoku[1][7]));
jTextField18.setText(String.valueOf(sudoku[1][8]));
jTextField19.setText(String.valueOf(sudoku[2][0]));
jTextField20.setText(String.valueOf(sudoku[2][1]));
jTextField21.setText(String.valueOf(sudoku[2][2]));
jTextField22.setText(String.valueOf(sudoku[2][3]));
jTextField23.setText(String.valueOf(sudoku[2][4]));
jTextField24.setText(String.valueOf(sudoku[2][5]));
jTextField25.setText(String.valueOf(sudoku[2][6]));
jTextField26.setText(String.valueOf(sudoku[2][7]));
jTextField27.setText(String.valueOf(sudoku[2][8]));
jTextField28.setText(String.valueOf(sudoku[3][0]));
jTextField29.setText(String.valueOf(sudoku[3][1]));
jTextField30.setText(String.valueOf(sudoku[3][2]));
jTextField31.setText(String.valueOf(sudoku[3][3]));
jTextField32.setText(String.valueOf(sudoku[3][4]));
jTextField33.setText(String.valueOf(sudoku[3][5]));
jTextField34.setText(String.valueOf(sudoku[3][6]));
jTextField35.setText(String.valueOf(sudoku[3][7]));
jTextField36.setText(String.valueOf(sudoku[3][8]));
jTextField37.setText(String.valueOf(sudoku[4][0]));
jTextField38.setText(String.valueOf(sudoku[4][1]));
jTextField39.setText(String.valueOf(sudoku[4][2]));
jTextField40.setText(String.valueOf(sudoku[4][3]));
jTextField41.setText(String.valueOf(sudoku[4][4]));
jTextField42.setText(String.valueOf(sudoku[4][5]));
jTextField43.setText(String.valueOf(sudoku[4][6]));
jTextField44.setText(String.valueOf(sudoku[4][7]));
jTextField45.setText(String.valueOf(sudoku[4][8]));
jTextField46.setText(String.valueOf(sudoku[5][0]));
jTextField47.setText(String.valueOf(sudoku[5][1]));
jTextField48.setText(String.valueOf(sudoku[5][2]));
jTextField49.setText(String.valueOf(sudoku[5][3]));
jTextField50.setText(String.valueOf(sudoku[5][4]));
jTextField51.setText(String.valueOf(sudoku[5][5]));
jTextField52.setText(String.valueOf(sudoku[5][6]));
jTextField53.setText(String.valueOf(sudoku[5][7]));
jTextField54.setText(String.valueOf(sudoku[5][8]));
jTextField55.setText(String.valueOf(sudoku[6][0]));
jTextField56.setText(String.valueOf(sudoku[6][1]));
jTextField57.setText(String.valueOf(sudoku[6][2]));
jTextField58.setText(String.valueOf(sudoku[6][3]));
jTextField59.setText(String.valueOf(sudoku[6][4]));
jTextField60.setText(String.valueOf(sudoku[6][5]));
jTextField61.setText(String.valueOf(sudoku[6][6]));
jTextField62.setText(String.valueOf(sudoku[6][7]));
jTextField63.setText(String.valueOf(sudoku[6][8]));
jTextField64.setText(String.valueOf(sudoku[7][0]));
jTextField65.setText(String.valueOf(sudoku[7][1]));
jTextField66.setText(String.valueOf(sudoku[7][2]));
jTextField67.setText(String.valueOf(sudoku[7][3]));
jTextField68.setText(String.valueOf(sudoku[7][4]));
jTextField69.setText(String.valueOf(sudoku[7][5]));
jTextField70.setText(String.valueOf(sudoku[7][6]));
jTextField71.setText(String.valueOf(sudoku[7][7]));
jTextField72.setText(String.valueOf(sudoku[7][8]));
jTextField73.setText(String.valueOf(sudoku[8][0]));
jTextField74.setText(String.valueOf(sudoku[8][1]));
jTextField75.setText(String.valueOf(sudoku[8][2]));
jTextField76.setText(String.valueOf(sudoku[8][3]));
jTextField77.setText(String.valueOf(sudoku[8][4]));
jTextField78.setText(String.valueOf(sudoku[8][5]));
jTextField79.setText(String.valueOf(sudoku[8][6]));
jTextField80.setText(String.valueOf(sudoku[8][7]));
jTextField81.setText(String.valueOf(sudoku[8][8]));
}
}
|
<gh_stars>1-10
package randomizer.common.utils.dsdecmp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
/**
* @author einstein95
*/
public class JavaDSDecmp {
public static int[] decompress(HexInputStream his) throws IOException {
switch(his.readU8()){
case 0x10: return Decompress10LZ(his);
case 0x11: return decompress11LZ(his);
case 0x13:
his.skip(3);
return decompress11LZ(his);
case 0x24:
case 0x28: return DecompressHuff(his);
case 0x30: return DecompressRLE(his);
default: return null;
}
}
private static int getLength(HexInputStream his) throws IOException {
int length = 0;
for(int i = 0; i < 3; i++)
length = length | (his.readU8() << (i * 8));
if(length == 0) // 0 length? then length is next 4 bytes
length = his.readlS32();
return length;
}
private static int[] Decompress10LZ(HexInputStream his) throws IOException {
int[] outData = new int[getLength(his)];
int curr_size = 0;
int flags;
boolean flag;
int disp, n, b, cdest;
while (curr_size < outData.length)
{
try { flags = his.readU8(); }
catch (EOFException ex) { break; }
for (int i = 0; i < 8; i++)
{
flag = (flags & (0x80 >> i)) > 0;
if (flag)
{
disp = 0;
try { b = his.readU8(); }
catch (EOFException ex) { throw new InvalidFileException("Incomplete data"); }
n = b >> 4;
disp = (b & 0x0F) << 8;
try { disp |= his.readU8(); }
catch (EOFException ex) { throw new InvalidFileException("Incomplete data"); }
n += 3;
cdest = curr_size;
//Console.WriteLine("disp: 0x{0:x}", disp);
if (disp > curr_size)
throw new InvalidFileException("Cannot go back more than already written");
for (int j = 0; j < n; j++)
outData[curr_size++] = outData[cdest - disp - 1 + j];
if (curr_size > outData.length)
break;
}
else
{
try { b = his.readU8(); }
catch (EOFException ex) { break;}// throw new Exception("Incomplete data"); }
try { outData[curr_size++] = b; }
catch (ArrayIndexOutOfBoundsException ex) { if (b == 0) break; }
if (curr_size > outData.length)
break;
}
}
}
return outData;
}
private static int[] decompress11LZ(HexInputStream his) throws IOException {
int[] outData = new int[getLength(his)];
int curr_size = 0;
int flags;
boolean flag;
int b1, bt, b2, b3, len, disp, cdest;
while (curr_size < outData.length)
{
try { flags = his.readU8(); }
catch (EOFException ex) { break; }
for (int i = 0; i < 8 && curr_size < outData.length; i++)
{
flag = (flags & (0x80 >> i)) > 0;
if (flag)
{
try { b1 = his.readU8(); }
catch (EOFException ex) { throw new InvalidFileException("Incomplete data"); }
switch (b1 >> 4)
{
case 0:
// ab cd ef
// =>
// len = abc + 0x11 = bc + 0x11
// disp = def
len = b1 << 4;
try { bt = his.readU8(); }
catch (EOFException ex) { throw new InvalidFileException("Incomplete data"); }
len |= bt >> 4;
len += 0x11;
disp = (bt & 0x0F) << 8;
try { b2 = his.readU8(); }
catch (EOFException ex) { throw new InvalidFileException("Incomplete data"); }
disp |= b2;
break;
case 1:
// ab cd ef gh
// =>
// len = bcde + 0x111
// disp = fgh
// 10 04 92 3F => disp = 0x23F, len = 0x149 + 0x11 = 0x15A
try { bt = his.readU8(); b2 = his.readU8(); b3 = his.readU8(); }
catch (EOFException ex) { throw new InvalidFileException("Incomplete data"); }
len = (b1 & 0xF) << 12; // len = b000
len |= bt << 4; // len = bcd0
len |= (b2 >> 4); // len = bcde
len += 0x111; // len = bcde + 0x111
disp = (b2 & 0x0F) << 8; // disp = f
disp |= b3; // disp = fgh
break;
default:
// ab cd
// =>
// len = a + threshold = a + 1
// disp = bcd
len = (b1 >> 4) + 1;
disp = (b1 & 0x0F) << 8;
try { b2 = his.readU8(); }
catch (EOFException ex) { throw new InvalidFileException("Incomplete data"); }
disp |= b2;
break;
}
if (disp > curr_size)
throw new InvalidFileException("Cannot go back more than already written");
cdest = curr_size;
for (int j = 0; j < len && curr_size < outData.length; j++)
outData[curr_size++] = outData[cdest - disp - 1 + j];
if (curr_size > outData.length)
break;
}
else
{
try { outData[curr_size++] = his.readU8(); }
catch (EOFException ex) { break; }// throw new Exception("Incomplete data"); }
if (curr_size > outData.length)
break;
}
}
}
return outData;
}
public static byte[] compressLZ11(byte[] decompressed) {
if (decompressed.length > 0xFFFFFF) {
throw new IllegalArgumentException("Input is too long.");
}
byte[] compressedBytes = null;
try (ByteArrayInputStream inputStream =
new ByteArrayInputStream(decompressed)) {
try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
int inLength = decompressed.length;
byte[] inData = new byte[(int) inLength];
int numReadBytes = inputStream.read(inData, 0, (int) inLength);
if (numReadBytes != inLength) {
throw new IOException("Stream is too short.");
}
outStream.write((byte) 0x11);
outStream.write((byte) (inLength & 0xFF));
outStream.write((byte) (inLength >> 8) & 0xFF);
outStream.write((byte) (inLength >> 16) & 0xFF);
byte[] outBuffer = new byte[8 * 4 + 1];
outBuffer[0] = 0;
int bufferLength = 1;
int bufferedBlocks = 0;
int readBytes = 0;
int inStart = 0;
int disp;
while (readBytes < inLength) {
if (bufferedBlocks == 8) {
outStream.write(outBuffer, 0, bufferLength);
outBuffer[0] = 0;
bufferLength = 1;
bufferedBlocks = 0;
}
int oldLength = Math.min(readBytes, 0x1000);
int[] result = getOccurrenceLength(
inData,
inStart + readBytes,
Math.min(inLength - readBytes, 0x10110),
inStart + readBytes - oldLength,
oldLength
);
int length = result[0];
disp = result[1];
if (length < 3) {
outBuffer[bufferLength++] = inData[inStart + (readBytes++)];
} else {
readBytes += length;
outBuffer[0] |= (byte) (1 << (7 - bufferedBlocks));
if (length > 0x110) {
outBuffer[bufferLength] = 0x10;
outBuffer[bufferLength] |= (byte)(((length - 0x111) >> 12)
& 0x0F);
bufferLength++;
outBuffer[bufferLength] = (byte)(((length - 0x111) >> 4) & 0xFF);
bufferLength++;
outBuffer[bufferLength] = (byte)(((length - 0x111) << 4) & 0xF0);
} else if (length > 0x10) {
outBuffer[bufferLength] = 0x00;
outBuffer[bufferLength] |= (byte)(((length - 0x111) >> 4) & 0x0F);
bufferLength++;
outBuffer[bufferLength] = (byte)(((length - 0x111) << 4) & 0xF0);
} else {
outBuffer[bufferLength] = (byte)(((length - 1) << 4) & 0xF0);
}
outBuffer[bufferLength] |= (byte) (((disp - 1) >> 8) & 0x0F);
bufferLength++;
outBuffer[bufferLength] = (byte) ((disp - 1) & 0xFF);
bufferLength++;
}
bufferedBlocks++;
}
if (bufferedBlocks > 0) {
outStream.write(outBuffer, 0, bufferLength);
}
compressedBytes = outStream.toByteArray();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return compressedBytes;
}
private static int[] getOccurrenceLength(byte[] bytes, int newPtr, int newLength, int oldPtr, int oldLength) {
int disp = 0;
if (newLength == 0) {
return new int[] { 0, 0 };
}
int maxLength = 0;
for (int i = 0; i < oldLength - 1; i++) {
int currentOldStart = oldPtr + i;
int currentLength = 0;
for (int j = 0; j < newLength; j++) {
if (bytes[currentOldStart + j] != bytes[newPtr + j]) {
break;
}
currentLength++;
}
if (currentLength > maxLength) {
maxLength = currentLength;
disp = oldLength - i;
if (maxLength == newLength) {
break;
}
}
}
return new int[] { maxLength, disp };
}
// note: untested
private static int[] DecompressRLE(HexInputStream his) throws IOException {
int[] outData = new int[getLength(his)];
int curr_size = 0;
int i, rl;
int flag, b;
boolean compressed;
while (true)
{
// get tag
try { flag = his.readU8(); }
catch (EOFException ex) { break; }
compressed = (flag & 0x80) > 0;
rl = flag & 0x7F;
if (compressed)
rl += 3;
else
rl += 1;
if (compressed)
{
try { b = his.readU8(); }
catch (EOFException ex) { break; }
for (i = 0; i < rl; i++)
outData[curr_size++] = b;
}
else
for (i = 0; i < rl; i++)
try { outData[curr_size++] = his.readU8(); }
catch (EOFException ex) { break; }
if (curr_size > outData.length)
throw new InvalidFileException("curr_size > decomp_size; "+curr_size+">"+outData.length);
if (curr_size == outData.length)
break;
}
return outData;
}
// note: untested
private static int[] DecompressHuff(HexInputStream his) throws IOException{
his.skip(-1);
int firstByte = his.readU8();
int dataSize = firstByte & 0x0F;
if (dataSize != 8 && dataSize != 4)
throw new InvalidFileException("Unhandled dataSize "+Integer.toHexString(dataSize));
int decomp_size = getLength(his);
int treeSize = his.readU8();
HuffTreeNode.maxInpos = 4 + (treeSize + 1) * 2;
HuffTreeNode rootNode = new HuffTreeNode();
rootNode.parseData(his);
his.setPosition(4 + (treeSize + 1) * 2); // go to start of coded bitstream.
// read all data
int[] indata = new int[(int)(his.available() - his.getPosition()) / 4];
for (int i = 0; i < indata.length; i++)
indata[i] = his.readS32();
int curr_size = 0;
decomp_size *= dataSize == 8 ? 1 : 2;
int[] outdata = new int[decomp_size];
int idx = -1;
String codestr = "";
NLinkedList<Integer> code = new NLinkedList<Integer>();
while (curr_size < decomp_size)
{
try
{
codestr += Integer.toBinaryString(indata[++idx]);
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new InvalidFileException("not enough data.", e);
}
while (codestr.length() > 0)
{
code.addFirst(Integer.parseInt(codestr.charAt(0)+""));
codestr = codestr.substring(1);
Pair<Boolean, Integer> attempt = rootNode.getValue(code.getLast());
if (attempt.getFirst())
{
try
{
outdata[curr_size++] = attempt.getSecond();
}
catch (ArrayIndexOutOfBoundsException ex)
{
if (code.getFirst().getValue() != 0)
throw ex;
}
code.clear();
}
}
}
if (codestr.length() > 0 || idx < indata.length-1)
{
while (idx < indata.length-1)
codestr += Integer.toBinaryString(indata[++idx]);
codestr = codestr.replace("0", "");
if (codestr.length() > 0)
System.out.println("too much data; str="+codestr+", idx="+idx+"/"+indata.length);
}
int[] realout;
if (dataSize == 4)
{
realout = new int[decomp_size / 2];
for (int i = 0; i < decomp_size / 2; i++)
{
if ((outdata[i * 2] & 0xF0) > 0
|| (outdata[i * 2 + 1] & 0xF0) > 0)
throw new InvalidFileException("first 4 bits of data should be 0 if dataSize = 4");
realout[i] = (byte)((outdata[i * 2] << 4) | outdata[i * 2 + 1]);
}
}
else
{
realout = outdata;
}
return realout;
}
}
class HuffTreeNode
{
protected static int maxInpos = 0;
protected HuffTreeNode node0, node1;
protected int data = -1; // [-1,0xFF]
/// <summary>
/// To get a value, provide the last node of a list of bytes < 2.
/// the list will be read from back to front.
/// </summary>
protected Pair<Boolean, Integer> getValue(NLinkedListNode<Integer> code) throws InvalidFileException
{
Pair<Boolean, Integer> outData = new Pair<Boolean, Integer>();
outData.setSecond(data);
if (code == null){
outData.setFirst(node0 == null && node1 == null && data >= 0);
return outData;
}
if(code.getValue() > 1)
throw new InvalidFileException("The list should be a list of bytes < 2. got: " + code.getValue());
int c = code.getValue();
HuffTreeNode n = c == 0 ? node0 : node1;
if(n == null)
outData.setFirst(false);
return n.getValue(code.getPrevious());
}
protected int getValue(String code) throws InvalidFileException
{
NLinkedList<Integer> c = new NLinkedList<Integer>();
for(char ch : code.toCharArray())
c.addFirst((int)ch);
Pair<Boolean, Integer> attempt = this.getValue(c.getLast());
if(attempt.getFirst())
return attempt.getSecond();
else
return -1;
}
protected void parseData(HexInputStream his) throws IOException
{
/*
* Tree Table (list of 8bit nodes, starting with the root node)
Root Node and Non-Data-Child Nodes are:
Bit0-5 Offset to next child node,
Next child node0 is at (CurrentAddr AND NOT 1)+Offset*2+2
Next child node1 is at (CurrentAddr AND NOT 1)+Offset*2+2+1
Bit6 Node1 End Flag (1=Next child node is data)
Bit7 Node0 End Flag (1=Next child node is data)
Data nodes are (when End Flag was set in parent node):
Bit0-7 Data (upper bits should be zero if Data Size is less than 8)
*/
this.node0 = new HuffTreeNode();
this.node1 = new HuffTreeNode();
long currPos = his.getPosition();
int b = his.readU8();
long offset = b & 0x3F;
boolean end0 = (b & 0x80) > 0, end1 = (b & 0x40) > 0;
// parse data for node0
his.setPosition((currPos - (currPos & 1)) + offset * 2 + 2);
if (his.getPosition() < maxInpos)
{
if (end0)
node0.data = his.readU8();
else
node0.parseData(his);
}
// parse data for node1
his.setPosition((currPos - (currPos & 1)) + offset * 2 + 2 + 1);
if (his.getPosition() < maxInpos)
{
if (end1)
node1.data = his.readU8();
else
node1.parseData(his);
}
// reset position
his.setPosition(currPos);
}
@Override
public String toString()
{
if (data < 0)
return "<" + node0.toString() + ", " + node1.toString() + ">";
else
return "["+Integer.toHexString(data)+"]";
}
protected int getDepth()
{
if (data < 0)
return 0;
else
return 1 + Math.max(node0.getDepth(), node1.getDepth());
}
}
|
#!/bin/bash
METRICS=${METRICS-../test/metrics/random-value}
MAXLABELS=${MAXLABELS-4}
NUMBER=${NUMBER-100}
LABELS=(pippo pluto topolino gastone paperino paperone brigitta paperoga paperina priscilla orazio clarabella topolina)
time=`date +%s`;
for i in `seq 1 $NUMBER`; do
labels=$(( RANDOM % MAXLABELS ))
addlabel=""
for (( i = 0; i < labels; i++ )); do
elements=${#LABELS[@]}
which=$(( RANDOM % elements ))
addlabel="$addlabel -label=${LABELS[$which]}"
done
tsdb-cli --serie ../test/metrics/random-value --labelsperentry=$MAXLABELS --time=$(( time + i * 10 )) --value=$RANDOM $addlabel;
done;
|
<gh_stars>1-10
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
//import css
import styles from './styles.module.scss'
const Checkbox = ({
id,
className,
value,
name,
labelText,
defaultChecked,
onChange,
onBlur
}) => {
return (
<div
className={classNames({
[styles.container]: true,
[className] : className
})}
>
<input
id={id}
value={value}
name={name}
type={`checkbox`}
defaultChecked={defaultChecked}
onChange={onChange}
onBlur={onBlur}
/>
<svg className={styles.check} aria-hidden="true" focusable="false" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"></path></svg>
<div className={styles.checkbox}></div>
<label
htmlFor={id}
>{labelText}</label>
</div>
)
}
//rules for props being passed in
Checkbox.propTypes = {
id: PropTypes.string,
className: PropTypes.string,
labelText: PropTypes.string.isRequired,
defaultChecked: PropTypes.bool,
name: PropTypes.string,
onChange: PropTypes.func,
onBlur: PropTypes.func
}
//maintain the name for documentation purposes
Checkbox.displayName = 'Checkbox'
export default Checkbox |
<reponame>baschtl/todoapp-rails
require 'rails_helper'
RSpec.describe "todos/edit", type: :view do
before(:each) do
@todo = assign(:todo, Todo.create!(
:title => "MyString",
:completed => false
))
end
it "renders the edit todo form" do
render
assert_select "form[action=?][method=?]", todo_path(@todo), "post" do
assert_select "input#todo_title[name=?]", "todo[title]"
assert_select "input#todo_completed[name=?]", "todo[completed]"
end
end
end
|
teardown() {
rm -rf $HOME/.local/bin/sdd $HOME/.local/lib/sdd
rm -rf /usr/bin/sdd /usr/lib/sdd
}
@test "Default sdd installation succeeds" {
[ ! -e "$HOME/.local/share/sdd/apps/installed" ]
run "$BATS_TEST_DIRNAME"/../../bootstrap.sh
[ $status -eq 0 ]
[ -e "$HOME/.local/bin/sdd" ]
run grep '^sdd=' "$HOME/.local/share/sdd/apps/installed"
[ $status -eq 0 ]
run "$HOME/.local/bin/sdd"
[ "$status" -eq 0 ]
run grep '^v' <("$HOME/.local/bin/sdd" --version)
[ "$status" -eq 0 ]
}
@test "Custom sdd installation succeeds" {
export PREFIX=/usr
run "$BATS_TEST_DIRNAME"/../../bootstrap.sh
[ $status -eq 0 ]
[ -e /usr/bin/sdd ]
run /usr/bin/sdd
[ "$status" -eq 0 ]
}
|
import requests
from bs4 import BeautifulSoup
url = "http://example.com/newspaper"
# fetch data from the given URL
r = requests.get(url)
# create a BeautifulSoup object
soup = BeautifulSoup(r.content, "lxml")
# extract the title of all articles
for article_title in soup.find_all('h3', class_='title'):
print(article_title.text) |
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5) |
<reponame>isaec/gune
const MESSAGE_ENUM = require("/server/message").MESSAGE_ENUM
module.exports.ActionHandler = function (engine) {
this.engine = engine
this.handle = (action) => {
if (action && action.validate(this.engine.getPlayer(), this.engine)) {
this.engine.connection.send(
JSON.stringify(
{
type: MESSAGE_ENUM.CLIENT_ACTION,
body: action,
}
)
)
return true
}
return false
}
} |
package com.ruoyi.project.system.mzkdsr.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.mzkdsr.mapper.MzkdsrMapper;
import com.ruoyi.project.system.mzkdsr.domain.Mzkdsr;
import com.ruoyi.project.system.mzkdsr.service.IMzkdsrService;
import com.ruoyi.common.support.Convert;
/**
* 门诊开单收入数据 服务层实现
*
* @author panda
* @date 2018-12-25
*/
@Service
public class MzkdsrServiceImpl implements IMzkdsrService
{
@Autowired
private MzkdsrMapper mzkdsrMapper;
/**
* 查询门诊开单收入数据信息
*
* @param id 门诊开单收入数据ID
* @return 门诊开单收入数据信息
*/
@Override
public Mzkdsr selectMzkdsrById(Integer id)
{
return mzkdsrMapper.selectMzkdsrById(id);
}
/**
* 查询门诊开单收入数据列表
*
* @param mzkdsr 门诊开单收入数据信息
* @return 门诊开单收入数据集合
*/
@Override
public List<Mzkdsr> selectMzkdsrList(Mzkdsr mzkdsr)
{
return mzkdsrMapper.selectMzkdsrList(mzkdsr);
}
/**
* 新增门诊开单收入数据
*
* @param mzkdsr 门诊开单收入数据信息
* @return 结果
*/
@Override
public int insertMzkdsr(Mzkdsr mzkdsr)
{
return mzkdsrMapper.insertMzkdsr(mzkdsr);
}
/**
* 修改门诊开单收入数据
*
* @param mzkdsr 门诊开单收入数据信息
* @return 结果
*/
@Override
public int updateMzkdsr(Mzkdsr mzkdsr)
{
return mzkdsrMapper.updateMzkdsr(mzkdsr);
}
/**
* 删除门诊开单收入数据对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteMzkdsrByIds(String ids)
{
return mzkdsrMapper.deleteMzkdsrByIds(Convert.toStrArray(ids));
}
}
|
docker logs -f anycontent-cms-construction-kit-php56 |
<filename>beatmap/beatmapcompact.go
package beatmap
type BeatmapCompact struct {
BeatmapsetID int `json:"beatmapset_id"`
DifficultyRating float64 `json:"difficulty_rating"`
ID int `json:"id"`
// Mode gamemode.GameMode `json:"mode"`
Status string `json:"status"`
TotalLength int `json:"total_length"`
UserID int `json:"user_id"`
Version string `json:"version"`
// Optional Attributes
// WIP
}
|
<reponame>BadDaemon/updater-client
import { createStore } from 'vuex'
export default createStore({
state() {
return {
ongoingRequests: 0,
oems: [],
extras: [],
devices: {},
builds: {},
changes: {
page: -1,
items: [],
},
};
},
mutations: {
startRequest(state) {
state.ongoingRequests++;
},
endRequest(state) {
state.ongoingRequests--;
},
setOems(state, oems) {
state.oems = oems;
},
setDevice(state, payload) {
state.devices[payload.model] = payload.data;
},
setDeviceBuilds(state, payload) {
state.builds[payload.model] = payload.data;
},
addNextChangesPage(state, changes) {
state.changes.items = state.changes.items.concat(changes);
state.changes.page++;
},
setExtras(state, extras) {
state.extras = extras;
},
},
getters: {
ongoingRequests(state) {
return state.ongoingRequests;
},
oems(state) {
return state.oems;
},
getDevice: (state) => (model) => {
return state.devices[model];
},
getDeviceBuilds: (state) => (model) => {
return state.builds[model];
},
changes(state) {
return state.changes.items;
},
changesPage(state) {
return state.changes.page;
},
extras(state) {
return state.extras;
},
},
});
|
<reponame>ragonzales/carritoVentas
$( document ).ready(function() {
ListarBanners();
ListarCoberturasCombo();
});
function ListarBanners() {
$.ajax({
type: "POST",
url: BASE_URL + 'Productos/ListarBanners',
data: { },
//async: true,
dataType: 'json',
success: function (listaBanners) {
if (listaBanners != null) {
var bannerTexto = '';
var contador = 0;
listaBanners.forEach(function (banner) {
var active = '';
if(contador==0)
active = 'active';
switch(parseInt(banner.alineacion)){
case 0:
bannerTexto += BannerIzquierda(banner,active);
break;
case 1:
bannerTexto += BannerIzquierda(banner,active);
break;
case 2:
bannerTexto += BannerDerecha(banner,active);
break;
case 3:
bannerTexto += BannerCentro(banner,active);
break;
}
contador++;
});
$("#dvBanner").append(bannerTexto);
}
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(jqXhr); console.log(textStatus); console.log(errorThrown);
MensajeAlert(MODULO,'Error al listar los productos. Detalle Técnico : ' + errorThrown);
}
});
}
function BannerIzquierda(banner,active){
var bannerTexto = '';
bannerTexto += '<div class="item ' + active +'">';
bannerTexto += '<img src="' + banner.rutafoto +'" class="bg-cover-img" alt="" />';
bannerTexto += '<div class="carousel-caption carousel-caption-left">';
bannerTexto += '<div class="container">';
bannerTexto += '<h3 class="title m-b-5 fadeInLeftBig animated">' + banner.titulo + '</h3> ';
bannerTexto += '<p class="m-b-15 fadeInLeftBig animated">' + banner.descripcioncorta + '</p>';
if(banner.mensaje != ""){
bannerTexto += '<div class="price m-b-30 fadeInLeftBig animated"><span> ' + banner.mensaje + '</span></div>';
}
bannerTexto += '</div>';
bannerTexto += '</div>';
bannerTexto += '</div>';
return bannerTexto;
}
function BannerDerecha(banner,active){
var bannerTexto = '';
bannerTexto += '<div class="item ' + active +'">';
bannerTexto += '<img src="' + banner.rutafoto +'" class="bg-cover-img" alt="" />';
bannerTexto += '<div class="carousel-caption carousel-caption-right">';
bannerTexto += '<div class="container">';
bannerTexto += '<h3 class="title m-b-5 fadeInRightBig animated">' + banner.titulo + '</h3> ';
bannerTexto += '<p class="m-b-15 fadeInRightBig animated">' + banner.descripcioncorta + '</p>';
if(banner.mensaje != ""){
bannerTexto += '<div class="price m-b-30 fadeInRightBig animated"><span>' + banner.mensaje + '</span></div>';
}
bannerTexto += '</div>';
bannerTexto += '</div>';
bannerTexto += '</div>';
return bannerTexto;
}
function BannerCentro(banner,active){
var bannerTexto = '';
bannerTexto += '<div class="item ' + active +'">';
bannerTexto += '<img src="' + banner.rutafoto +'" class="bg-cover-img" alt="" />';
bannerTexto += '<div class="carousel-caption">';
bannerTexto += '<div class="container">';
bannerTexto += '<h3 class="title m-b-5 fadeInDownBig animated">' + banner.titulo + '</h3> ';
bannerTexto += '<p class="m-b-15 fadeInDownBig animated">' + banner.descripcioncorta + '</p>';
if(banner.mensaje != ""){
bannerTexto += '<div class="price fadeInDownBig animated"><span>' + banner.mensaje + '</span></div>';
}
bannerTexto += '</div>';
bannerTexto += '</div>';
bannerTexto += '</div>';
return bannerTexto;
}
function validar_email(email)
{
var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email) ? true : false;
}
function MensajeAlert(titulo,mensaje){
$.gritter.add({
title: titulo,
text: mensaje,
sticky: false,
class_name: 'my-sticky-class'
});
}
function number_format(amount, decimals) {
amount += '';
amount = parseFloat(amount.replace(/[^0-9\.]/g, ''));
decimals = decimals || 0;
if (isNaN(amount) || amount === 0) return parseFloat(0).toFixed(decimals);
amount = '' + amount.toFixed(decimals);
var amount_parts = amount.split('.'),
regexp = /(\d+)(\d{3})/;
while (regexp.test(amount_parts[0]))
amount_parts[0] = amount_parts[0].replace(regexp, '$1' + ',' + '$2');
return amount_parts.join('.');
}
function validarDecimales(e,thix) {
var keynum = window.event ? window.event.keyCode : e.which;
if (document.getElementById(thix.id).value.indexOf('.') != -1 && keynum == 46)
return false;
if ((keynum == 8 || keynum == 48 || keynum == 46))
return true;
if (keynum <= 47 || keynum >= 58) return false;
return /\d/.test(String.fromCharCode(keynum));
}
function ReemplazoNulo(parametro) {
var valor = '';
if (parametro != null && parametro != undefined) valor = parametro;
return valor;
}
function ReemplazoNuloMonto(parametro) {
var valor = 0;
if (parametro != null && parametro != undefined) valor = parseFloat(parametro);
return valor;
}
function numeroFormato(num,cantidadCaracteres){
numtmp='"'+num+'"';
largo=numtmp.length-2;
numtmp=numtmp.split('"').join('');
if(largo==cantidadCaracteres)return numtmp;
ceros='';
pendientes=cantidadCaracteres-largo;
for(i=0;i<pendientes;i++)ceros+='0';
return ceros+numtmp;
}
$( "#btnBuscarCoberturas").click(function() {
ListarCoberturas();
});
function ListarCoberturasCombo(){
$.ajax({
type: "POST",
url: BASE_URL + 'Coberturas/ListarCoberturas',
data: {},
async: false,
dataType: 'json',
success: function (listadoCoberturas) {
$("#cmbDistritoEnvio").empty();
if (listadoCoberturas != null)
{
listadoCoberturas.forEach(function (cobertura) {
$('#cmbDistritoEnvio').append('<option value="foo">' + cobertura.distrito + '</option>');
});
}
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(jqXhr); console.log(textStatus); console.log(errorThrown);
MensajeAlert(MODULO, 'Error al listar las coberturas. Detalle Técnico : ' + errorThrown);
}
});
}
function ListarCoberturas(){
$.ajax({
type: "POST",
url: BASE_URL + 'Coberturas/ListarCoberturas',
data: {},
async: false,
dataType: 'json',
success: function (listadoCoberturas) {
if (listadoCoberturas != null) {
var texto = '';
listadoCoberturas.forEach(function (cobertura) {
texto += AgregarCobertura(cobertura);
});
$("#dvDetalleCobertura").empty();
$("#dvDetalleCobertura").append(texto);
}
$('#modalCoberturas').modal('toggle');
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(jqXhr); console.log(textStatus); console.log(errorThrown);
MensajeAlert(MODULO, 'Error al listar las coberturas. Detalle Técnico : ' + errorThrown);
}
});
}
function AgregarCobertura(cobertura){
var coberturaTexto = '';
coberturaTexto += '<div class="row">';
coberturaTexto += '<div class="col-md-12">';
coberturaTexto += cobertura.distrito + '</br>';
coberturaTexto += '</div>';
coberturaTexto += '</div>';
return coberturaTexto;
}
function ListarBancos(){
$.ajax({
type: "POST",
url: BASE_URL + 'Bancos/ListarBancos',
data: {},
async: false,
dataType: 'json',
success: function (listarBancos) {
if (listarBancos != null) {
var texto = '';
listarBancos.forEach(function (banco) {
texto += AgregarCobertura(banco);
});
$("#dvDetalleCobertura").append(texto);
}
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(jqXhr); console.log(textStatus); console.log(errorThrown);
MensajeAlert(MODULO, 'Error al listar los bancos. Detalle Técnico : ' + errorThrown);
}
});
}
function BuscarBanco(){
$.ajax({
type: "POST",
url: BASE_URL + 'Bancos/BuscarBanco',
data: {},
async: false,
dataType: 'json',
success: function (banco) {
if (banco != null) {
}
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(jqXhr); console.log(textStatus); console.log(errorThrown);
MensajeAlert(MODULO, 'Error al buscar el banco. Detalle Técnico : ' + errorThrown);
}
});
} |
<gh_stars>1-10
const { radians } = require('axis3d/utils')
const clamp = require('clamp')
const vec3 = require('gl-vec3')
/**
* Applies orientation changes to orbit orbitCamera from
* keyboard input
*/
module.exports = exports = ({
keyboardInput: keyboard,
interpolationFactor, initialFov, damping,
translation, position, offset, euler,
invert = false, zoom = true,
} = {}) => {
keyboard && keyboard(({keys}) => {
const mappings = new KeyboardCommandMappings(keys)
// @TODO(werle) - should we reset keyboard state ?
if (mappings.value('control')) {
return
}
// reset orientation
if (keys['shift']) {
if (keys['0']) {
if (zoom && 'number' == typeof zoom.fov) {
zoom.fov = initialFov
} else if (false !== zoom) {
position[2] = 0
}
} else if (/*+*/keys['='] || keys['+'] || keys['-']) {
let dv = 0
if (keys['='] || keys['+']) {
dv = -0.1*damping
} else if (keys['-']) {
dv = 0.1*damping
}
if (zoom && 'number' == typeof zoom.fov) {
zoom.fov = (zoom.fov || 0) + dv
} else if (false !== zoom) {
translation[2] = clamp(translation[2] + dv, 0, Infinity)
}
}
if (keys['space']) {
euler[0] = 0
euler[1] = 0
vec3.set(position, 0, 0, 0)
vec3.set(offset, 0, 0, 0)
}
if (mappings.value('up')) {
vec3.add(translation, translation, [0, 0, -0.05])
} else if (mappings.value('down')) {
vec3.add(translation, translation, [0, 0, 0.05])
}
if (mappings.value('left')) {
vec3.add(translation, translation, [-0.05, 0, 0])
} else if (mappings.value('right')) {
vec3.add(translation, translation, [0.05, 0, 0])
}
return
}
if (mappings.value('up')) {
if (invert) {
euler[0] -= 0.068*damping
} else {
euler[0] += 0.068*damping
}
} else if (mappings.value('down')) {
if (invert) {
euler[0] += 0.068*damping
} else {
euler[0] -= 0.068*damping
}
}
if (mappings.value('left')) {
if (invert) {
euler[1] -= 0.062*damping
} else {
euler[1] += 0.062*damping
}
} else if (mappings.value('right')) {
if (invert) {
euler[1] += 0.062*damping
} else {
euler[1] -= 0.062*damping
}
}
})
}
class KeyboardCommandMappings {
constructor(keys = {}, extension = {mapping: {}}) {
this.keys = keys
this.map = Object.assign({}, extension.mapping, {
up: ['up', 'w', 'k', ].concat(extension.mapping.up || []),
down: ['down', 's', 'j'].concat(extension.mapping.down || []),
left: ['left', 'a', 'h'].concat(extension.mapping.left || []),
right: ['right', 'd', 'l'].concat(extension.mapping.right || []),
control: [
'right command', 'right control',
'left command', 'left control',
'control', 'super', 'ctrl', 'alt', 'fn',
].concat(extension.mapping.control || [])
})
}
value(which) {
return this.map[which].some((key) => Boolean(this.keys[key]))
}
}
|
export default config;
declare namespace config {
const port: number;
const databaseURL: string | undefined;
const redisURI: string | undefined;
const jwtSecret: string | undefined;
const cookieSecret: string | undefined;
namespace logs {
const level: string;
}
namespace api {
const prefix: string;
}
}
|
#!/usr/bin/env python3
import os
import sys
from importlib.machinery import SourceFileLoader
# Add the pulsar path
thispath = os.path.dirname(os.path.realpath(__file__))
psrpath = os.path.join(os.path.dirname(thispath), "modules")
sys.path.insert(0, psrpath)
from pulsar import GlobalOutput CheckSupermodule
from pulsar.exception import PyGeneralException
GlobalOutputSetOut_Stdout()
GlobalOutputSetDebug(True)
GlobalOutputSetColor(True)
paths = sys.argv[1:]
output.GlobalOutput("\n")
allok = True
for supermodule in paths:
try:
# will raise exception with a problem
CheckSupermodule(supermodule)
GlobalOutputSuccess(" Successfully checked supermodule {}\n\n".format(supermodule))
except PyGeneralException as e:
output.GlobalError("Checking of supermodule {} failed. See above for errors\n\n".format(supermodule))
allok = False
output.GlobalOutput("\n\n")
if allok:
GlobalOutputSuccess("All supermodules seem ok\n")
else:
output.GlobalError("***Problem detected. Fix it!***\n")
output.GlobalOutput("\n\n")
|
# finetune scripts for movenet
cd /data/ai/movenet/movenet/src
# python main.py single_pose --exp_id yoga_movenet --dataset active --arch movenet --batch_size 24 --master_batch 4 --lr 5e-4 --gpus 0,1,2,3 --num_epochs 150 --lr_step 30 60 90 --num_workers 16 --load_model ../models/movenet.pth
# test 7e -3 5e-3 1e-3 5e-4 1e-4
# python test.py single_pose --exp_id yoga_movenet --dataset active --arch movenet --resume
# # flip test
# python test.py single_pose --exp_id yoga_movenet --dataset active --arch movenet --resume --flip_test
python demo.py single_pose --dataset active --arch movenet --demo ../images/1111error/ --load_model ../models/movenet_thunder.pth --K 1 --gpus -1 --debug 2 #--vis_thresh 0.0 --not_reg_offset
cd ..
|
<?php
namespace App\Repositories;
use App\Type_de_fichier;
class Type_de_fichierRepository
{
protected $type_de_fichier;
public function __construct(Type_de_fichier $type_de_fichier)
{
$this->type_de_fichier = $type_de_fichier;
}
public function find($id)
{
return $this->type_de_fichier->find($id);
}
public function create($data)
{
return $this->type_de_fichier->create($data);
}
public function update($id, $data)
{
$fileType = $this->type_de_fichier->find($id);
if ($fileType) {
$fileType->update($data);
return $fileType;
}
return null;
}
public function delete($id)
{
$fileType = $this->type_de_fichier->find($id);
if ($fileType) {
$fileType->delete();
return true;
}
return false;
}
} |
import React from 'react'
import logo from './logo.svg';
import {
Container,
Divider,
Dropdown,
Grid,
Header,
Image,
List,
Menu,
Segment
} from 'semantic-ui-react'
const PageLayout = ({children}) =>
<div>
<Menu fixed='top' inverted>
<Container>
<Menu.Item as='a' header>
<Image
size='mini'
src={logo}
style={{ marginRight: '1.5em' }}
/>
Cool Todos
</Menu.Item>
<Menu.Item as='a'>Home</Menu.Item>
<Dropdown item simple text='Dropdown'>
<Dropdown.Menu>
<Dropdown.Item>List Item</Dropdown.Item>
<Dropdown.Item>List Item</Dropdown.Item>
<Dropdown.Divider />
<Dropdown.Header>Header Item</Dropdown.Header>
<Dropdown.Item>
<i className='dropdown icon' />
<span className='text'>Submenu</span>
<Dropdown.Menu>
<Dropdown.Item>List Item</Dropdown.Item>
<Dropdown.Item>List Item</Dropdown.Item>
</Dropdown.Menu>
</Dropdown.Item>
<Dropdown.Item>List Item</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Container>
</Menu>
<Container style={{ marginTop: '7em' }}>
{children}
</Container>
<Segment
inverted
vertical
style={{ margin: '5em 0em 0em', padding: '5em 0em' }}
>
<Container textAlign='center'>
<Grid divided inverted stackable>
<Grid.Row>
<Grid.Column width={3}>
<Header inverted as='h4' content='Group 1' />
<List link inverted>
<List.Item as='a'>Link One</List.Item>
<List.Item as='a'>Link Two</List.Item>
<List.Item as='a'>Link Three</List.Item>
<List.Item as='a'>Link Four</List.Item>
</List>
</Grid.Column>
<Grid.Column width={3}>
<Header inverted as='h4' content='Group 2' />
<List link inverted>
<List.Item as='a'>Link One</List.Item>
<List.Item as='a'>Link Two</List.Item>
<List.Item as='a'>Link Three</List.Item>
<List.Item as='a'>Link Four</List.Item>
</List>
</Grid.Column>
<Grid.Column width={3}>
<Header inverted as='h4' content='Group 3' />
<List link inverted>
<List.Item as='a'>Link One</List.Item>
<List.Item as='a'>Link Two</List.Item>
<List.Item as='a'>Link Three</List.Item>
<List.Item as='a'>Link Four</List.Item>
</List>
</Grid.Column>
<Grid.Column width={3}>
<Header inverted as='h4' content='Footer Header' />
<p>Extra space for a call to action inside the footer that could help re-engage users.</p>
</Grid.Column>
</Grid.Row>
</Grid>
<Divider inverted section />
<List horizontal inverted divided link>
<List.Item as='a' href='#'>Site Map</List.Item>
<List.Item as='a' href='#'>Contact Us</List.Item>
<List.Item as='a' href='#'>Terms and Conditions</List.Item>
<List.Item as='a' href='#'>Privacy Policy</List.Item>
</List>
</Container>
</Segment>
</div>
export default PageLayout
|
import { expect } from 'chai';
import processRenderings from './processRenderings';
const args = {
dynamicPlaceholderKeyGenerator: (key: string, _: any, name: string) => `${key}/${name}`,
placeholder: {
phKey: '/',
},
rendering: {},
components: [
{
name: 'lorem',
},
{
name: 'ipsum',
},
{
name: 'dolor',
},
],
componentFactory: (components: any, componentName: string) =>
components.find((component: any) => component.name === componentName),
datasourceNamer: ({ index }: any) => `name${index}`,
datasourceDisplayNamer: ({ index }: any) => `displayName${index}`,
};
const initItem = (route: any) => ({
name: route.name,
template: 'template',
layout: {
renderings: [],
},
});
describe('generateRouteItem pipeline', () => {
describe('processRenderings processor', () => {
it('should add renderings to item layout', () => {
const route: any = {
name: 'route',
placeholders: {
main: [
{
componentName: 'ipsum',
},
{
componentName: 'dolor',
},
],
},
};
const item = initItem(route);
const argObject: any = { ...args, route, item };
const result = processRenderings(argObject);
expect(result.item.layout.renderings.length).to.eql(2);
});
it('should auto name unnamed datasource', () => {
const expectedName = 'name0';
const expectedDisplayName = 'displayName0';
const route: any = {
name: 'route',
placeholders: {
main: [
{
componentName: 'lorem',
},
],
},
};
const item = initItem(route);
const argObject: any = { ...args, route, item };
const result = processRenderings(argObject);
expect(result.item.layout.renderings[0].dataSource.name).to.eql(expectedName);
expect(result.item.layout.renderings[0].dataSource.displayName).to.eql(expectedDisplayName);
});
it('should use provided name for datasource', () => {
const expectedName = 'geoff';
const expectedDisplayName = 'geoffDisplay';
const route: any = {
name: 'route',
placeholders: {
main: [
{
name: expectedName,
displayName: expectedDisplayName,
componentName: 'lorem',
},
],
},
};
const item = initItem(route);
const argObject: any = { ...args, route, item };
const result = processRenderings(argObject);
expect(result.item.layout.renderings[0].dataSource.name).to.eql(expectedName);
expect(result.item.layout.renderings[0].dataSource.displayName).to.eql(expectedDisplayName);
});
it('should throw if item has duplicate datasource names', () => {
const duplicates = ['maple', 'sycamore'];
const nonDuplicates = ['pine', 'hemlock', 'fir'];
const components: any[] = [];
[...duplicates, ...nonDuplicates].forEach((name) => {
components.push({
name,
componentName: 'lorem',
});
});
duplicates.forEach((name) => {
components.push({
name,
componentName: 'ipsum',
});
});
const route = {
name: 'route',
placeholders: {
main: components,
},
};
const item = initItem(route);
const argObject: any = { ...args, route, item };
// tslint:disable-next-line no-unused-expression
expect(() => processRenderings(argObject)).to.throw;
});
});
});
|
# returns a list of every type which has a literal provider. This is an ordered list of providers. |
#!/bin/sh
BASTET_VERSION=$(git rev-parse --short HEAD)
TAG="bastet:$BASTET_VERSION"
DOCKER_TAR="bastet-docker-$BASTET_VERSION.tar"
SCRIPT=$(readlink -f "$0")
SCRIPT_DIR=$(dirname "$SCRIPT")
INPUT_DIR=$SCRIPT_DIR
OUTPUT_DIR="$SCRIPT_DIR/output/"
mkdir -p $OUTPUT_DIR
source ./docker.sh.inc
if [ ! -f $DOCKER_TAR ]
then
./docker-build.sh
fi
# Load the docker image
$DOCKERCMD load -i $DOCKER_TAR
# Run the image
$DOCKERCMD run \
--mount type=bind,source=${INPUT_DIR},target=/input \
--mount type=bind,source=${OUTPUT_DIR},target=/output \
$TAG \
/bin/bash ./scripts/bastet.sh "$@"
|
#!/usr/bin/env bash
# this script must be run by root or sudo
if [[ "$UID" -ne "0" ]] ; then
echo "ERROR: This script must be run by root or sudo"
exit
fi
if [ ${VAGRANT} == 1 ]; then
export SUBMISSION_URL='http://192.168.56.111'
fi
#################################################################
# PACKAGE SETUP
#################
apt-get -qqy update
apt-get install -qqy apt-transport-https ca-certificates curl software-properties-common
apt-get install -qqy python python-dev python3 python3-dev libpython3.6
############################
# NTP: Network Time Protocol
# You want to be sure the clock stays in sync, especially if you have
# deadlines for homework to be submitted.
#
# The default settings are ok, but you can edit /etc/ntp.conf and
# replace the default servers with your local ntp server to reduce
# traffic through your campus uplink (To replace the default servers
# with your own, comment out the default servers by adding a # before
# the lines that begin with “server” and add your server under the
# line that says “Specify one or more NTP servers” with something
# along the lines of “server xxx.xxx.xxx.xxx”)
apt-get install -qqy ntp
service ntp restart
echo "Preparing to install packages. This may take a while."
apt-get install -qqy libpam-passwdqc
# Set up apache to run with suphp in pre-fork mode since not all
# modules are thread safe (do not combine the commands or you may get
# the worker/threaded mode instead)
apt-get install -qqy ssh sshpass unzip
apt-get install -qqy postgresql-10
apt-get install -qqy apache2 apache2-suexec-custom libapache2-mod-authnz-external libapache2-mod-authz-unixgroup libapache2-mod-wsgi-py3
apt-get install -qqy php php-cli php-fpm php-curl php-pgsql php-zip php-mbstring php-xml
if [ ${VAGRANT} == 1 ]; then
apt-get install -qqy php-xdebug
fi
#Add the scrot screenshotting program
apt-get install -qqy scrot
# Add additional packages for compiling, authentication, and security,
# and program support
# DOCUMENTATION FIXME: Go through this list and categorize purpose of
# these packages (as appropriate.. )
apt-get install -qqy clang autoconf automake autotools-dev diffstat finger gdb git git-man \
p7zip-full patchutils libpq-dev unzip valgrind zip libmagic-ocaml-dev common-lisp-controller \
libboost-all-dev javascript-common libfile-mmagic-perl libgnupg-interface-perl libbsd-resource-perl \
libarchive-zip-perl gcc g++ g++-multilib jq libseccomp-dev libseccomp2 seccomp junit flex bison spim \
poppler-utils
apt-get install -qqy ninja-build
#CMAKE
echo "installing cmake"
apt-get install -qqy cmake
# for Lichen (Plagiarism Detection)
apt-get install -qqy python-clang-6.0
# Install OpenJDK8 Non-Interactively
echo "installing java8"
apt-get install -qqy openjdk-8-jdk
update-java-alternatives --set java-1.8.0-openjdk-amd64
# Install Image Magick for image comparison, etc.
apt-get install -qqy imagemagick
# miscellaneous usability
apt-get install -qqy emacs
# fix networking on vagrants
# https://bugs.launchpad.net/ubuntu/+source/netplan.io/+bug/1768560
# When the vagrant box comes with netplan.io 0.40+ we can remove this
if [ ${VAGRANT} == 1 ]; then
# In case they upgrade before we notice, don't run this fix
NETPLANIO_VERSION=$(apt-cache policy netplan.io | grep 'Installed' | sed -E 's/^.*: (.*)$/\1/')
NPIO_MAJOR=$(echo "$NETPLANIO_VERSION" | cut -d "." -f1)
NPIO_MINOR=$(echo "$NETPLANIO_VERSION" | cut -d "." -f2)
if [ "$NPIO_MAJOR" -eq 0 -a "$NPIO_MINOR" -lt 40 ]; then
# Update netplan.io
echo "Detected old version of netplan.io (${NETPLANIO_VERSION})... updating it automatically"
apt-get install -y netplan.io=0.40.1~18.04.4
fi
fi
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
apt-key fingerprint 0EBFCD88
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
apt-get update
apt-get install -qqy docker-ce
systemctl status docker | head -n 100
apt-get -qqy autoremove
|
<reponame>cs-fullstack-2019-spring/django-bootstrap-grid-ic-Kenn-CodeCrew
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, "BootGridApp/signIn.html")
def signIn(request):
return render(request, "BootGridApp/signIn.html")
def signUp(request):
return render(request, "BootGridApp/signUp.html")
|
package com.kastking.supplierProduct.service.impl;
import java.util.Date;
import java.util.List;
import com.kastking.historicalPrice.domain.MisSupplierHistoricalPrice;
import com.kastking.historicalPrice.mapper.MisSupplierHistoricalPriceMapper;
import com.kastking.productLadder.domain.MisSupplierProductLadder;
import com.kastking.productLadder.mapper.MisSupplierProductLadderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kastking.supplierProduct.mapper.MisSupplierProductMapper;
import com.kastking.supplierProduct.domain.MisSupplierProduct;
import com.kastking.supplierProduct.service.IMisSupplierProductService;
import com.kastking.common.core.text.Convert;
import com.kastking.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kastking.common.exception.BusinessException;
/**
* 供应商产品Service业务层处理
*
* @author James
* @date 2020-02-07
*/
@Service
public class MisSupplierProductServiceImpl implements IMisSupplierProductService {
private static final Logger log = LoggerFactory.getLogger(MisSupplierProductServiceImpl.class);
@Autowired
private MisSupplierProductMapper misSupplierProductMapper;
@Autowired
private MisSupplierProductLadderMapper productLadderMapper;
@Autowired
private MisSupplierHistoricalPriceMapper priceMapper;
/**
* 查询供应商产品
*
* @param productId 供应商产品ID
* @return 供应商产品
*/
@Override
public MisSupplierProduct selectMisSupplierProductById(Long productId) {
return misSupplierProductMapper.selectMisSupplierProductById(productId);
}
/**
* 查询供应商产品列表
*
* @param misSupplierProduct 供应商产品
* @return 供应商产品
*/
@Override
public List<MisSupplierProduct> selectMisSupplierProductList(MisSupplierProduct misSupplierProduct) {
return misSupplierProductMapper.selectMisSupplierProductList(misSupplierProduct);
}
/**
* 新增供应商产品
*
* @param misSupplierProduct 供应商产品
* @return 结果
*/
@Override
public int insertMisSupplierProduct(MisSupplierProduct misSupplierProduct) {
//判断SKU是否重复
if (this.verificationSku(misSupplierProduct) != null) {
return 0;
} else {
//新增产品对象
misSupplierProductMapper.insertMisSupplierProduct(misSupplierProduct);
if (misSupplierProduct.getStr1() != null && !"".equals(misSupplierProduct.getStr1()) && !"-/".equals(misSupplierProduct.getStr1())) {
// 1 - 2 / 3
//阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr1().substring(0, misSupplierProduct.getStr1().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr1().substring(str1.length() + 1, misSupplierProduct.getStr1().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr2() != null && !"".equals(misSupplierProduct.getStr2())) {
// 1 - 2 / 3
//阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr2().substring(0, misSupplierProduct.getStr2().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr2().substring(str1.length() + 1, misSupplierProduct.getStr2().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr3() != null && !"".equals(misSupplierProduct.getStr3())) {
// 1 - 2 / 3
//阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr3().substring(0, misSupplierProduct.getStr3().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr3().substring(str1.length() + 1, misSupplierProduct.getStr3().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr4() != null && !"".equals(misSupplierProduct.getStr4())) {
// 1 - 2 / 3
//阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr4().substring(0, misSupplierProduct.getStr4().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr4().substring(str1.length() + 1, misSupplierProduct.getStr4().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr5() != null && !"".equals(misSupplierProduct.getStr5())) {
// 1 - 2 / 3
//阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr5().substring(0, misSupplierProduct.getStr5().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr5().substring(str1.length() + 1, misSupplierProduct.getStr5().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
return 1;
}
}
/**
* 修改供应商产品
*
* @param misSupplierProduct 供应商产品
* @return 结果
*/
@Override
public int updateMisSupplierProduct(MisSupplierProduct misSupplierProduct) {
//判断SKU是否重复
if (this.verificationSku(misSupplierProduct) != null) {
return 0;
} else {
//未修改产品对象
MisSupplierProduct product = misSupplierProductMapper.selectMisSupplierProductById(misSupplierProduct.getProductId());
//判断单价是否修改
if (!product.getNoUnitPrice().equals(misSupplierProduct.getNoUnitPrice()) || !product.getCurrency().equals(misSupplierProduct.getTaxPoint()) || !product.getCurrency().equals(misSupplierProduct.getCurrency())) {
//历史价对象
MisSupplierHistoricalPrice price = new MisSupplierHistoricalPrice();
//未修改产品对象ID
price.setProductId(product.getProductId());
//修改产品对象币种
price.setCurrency(misSupplierProduct.getCurrency());
//当前时间
price.setCurrentTime(new Date());
//修改税点
price.setTaxPoint(misSupplierProduct.getTaxPoint());
//未修改产品对象不含税价格
price.setLastNoPrice(product.getNoUnitPrice());
//未修改产品对象含税价格
price.setLastPrice(product.getUnitPrice());
//未修改税点
price.setLastTax(product.getTaxPoint());
//当前产品对象不含税价格
price.setCurrentNoPrice(misSupplierProduct.getNoUnitPrice());
//当前产品对象含税价格
price.setCurrentPrice(misSupplierProduct.getNoUnitPrice());
//未修改产品对象修改时间
price.setLastTime(product.getUpdateDate());
//新增历史价对象
priceMapper.insertMisSupplierHistoricalPrice(price);
}
//修改产品对象
misSupplierProductMapper.updateMisSupplierProduct(misSupplierProduct);
//根据产品ID删除阶梯价对象
productLadderMapper.deleteMisSupplierProductLadderByHeadId(misSupplierProduct.getProductId());
if (misSupplierProduct.getStr1() != null && !"".equals(misSupplierProduct.getStr1()) && !"-/".equals(misSupplierProduct.getStr1())) {
// 1 - 2 / 3
//新建阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr1().substring(0, misSupplierProduct.getStr1().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr1().substring(str1.length() + 1, misSupplierProduct.getStr1().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr2() != null && !"".equals(misSupplierProduct.getStr2())) {
// 1 - 2 / 3
//新建阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr2().substring(0, misSupplierProduct.getStr2().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr2().substring(str1.length() + 1, misSupplierProduct.getStr2().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr3() != null && !"".equals(misSupplierProduct.getStr3())) {
// 1 - 2 / 3
//新建阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr3().substring(0, misSupplierProduct.getStr3().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr3().substring(str1.length() + 1, misSupplierProduct.getStr3().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr4() != null && !"".equals(misSupplierProduct.getStr4())) {
// 1 - 2 / 3
//新建阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr4().substring(0, misSupplierProduct.getStr4().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr4().substring(str1.length() + 1, misSupplierProduct.getStr4().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
if (misSupplierProduct.getStr5() != null && !"".equals(misSupplierProduct.getStr5())) {
// 1 - 2 / 3
//新建阶梯价对象
MisSupplierProductLadder misSupplierProductLadder = new MisSupplierProductLadder();
//价格1
String str1 = misSupplierProduct.getStr5().substring(0, misSupplierProduct.getStr5().indexOf("-"));
//价格2
String str2 = misSupplierProduct.getStr5().substring(str1.length() + 1, misSupplierProduct.getStr5().length());
String str2s = str2.substring(0, str2.indexOf("/"));
//单价
String str3 = str2.substring(str2s.length() + 1, str2.length());
misSupplierProductLadder.setPriceOne(Double.valueOf(str1));
misSupplierProductLadder.setPriceTwo(Double.valueOf(str2s));
misSupplierProductLadder.setUnitPrice(Double.valueOf(str3));
misSupplierProductLadder.setProductId(misSupplierProduct.getProductId());
productLadderMapper.insertMisSupplierProductLadder(misSupplierProductLadder);
}
return 1;
}
}
/**
* 删除供应商产品对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteMisSupplierProductByIds(String ids) {
return misSupplierProductMapper.deleteMisSupplierProductByIds(Convert.toStrArray(ids));
}
/**
* 删除供应商产品信息
*
* @param productId 供应商产品ID
* @return 结果
*/
@Override
public int deleteMisSupplierProductById(Long productId) {
//删除产品对象同时删除阶梯价
//productLadderMapper.deleteMisSupplierProductLadderByHeadId(productId);
return misSupplierProductMapper.deleteMisSupplierProductById(productId);
}
/**
* 导入供应商产品数据
*
* @param misSupplierProductList 供应商产品数据列表
* @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据
* @param operName 操作用户
* @return 结果
*/
public String importMisSupplierProduct(List<MisSupplierProduct> misSupplierProductList, Boolean isUpdateSupport, String operName) {
if (StringUtils.isNull(misSupplierProductList) || misSupplierProductList.size() == 0) {
throw new BusinessException("导入供应商产品数据不能为空!");
}
int successNum = 0;
int failureNum = 0;
StringBuilder successMsg = new StringBuilder();
StringBuilder failureMsg = new StringBuilder();
for (MisSupplierProduct misSupplierProduct : misSupplierProductList) {
try {
//判断是否修改还是新增
if (isUpdateSupport) {
if (this.verificationSku(misSupplierProduct) != null) {
//根据SKU唯一查找产品ID
misSupplierProduct.setProductId(this.verificationSku(misSupplierProduct));
//修改产品对象
if (this.updateMisSupplierProduct(misSupplierProduct) > 0) {
successNum++;
successMsg.append("<br/>" + successNum + "、导入修改成功");
}
}
} else {
//判断SKU是否唯一
if (this.verificationSku(misSupplierProduct) != null) {
failureNum++;
String msg = "<br/>" + failureNum + "、导入失败:";
failureMsg.append(msg + "SKU重复");
} else {
if (this.insertMisSupplierProduct(misSupplierProduct) > 0) {
successNum++;
successMsg.append("<br/>" + successNum + "、导入新增成功");
}
}
}
} catch (Exception e) {
failureNum++;
String msg = "<br/>" + failureNum + "、导入失败:";
failureMsg.append(msg + e.getMessage());
log.error(msg, e);
}
}
if (failureNum > 0) {
failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");
throw new BusinessException(failureMsg.toString());
} else {
successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
}
return successMsg.toString();
}
@Override
public Long verificationSku(MisSupplierProduct misSupplierProduct) {
//判断SKU唯一
return misSupplierProductMapper.verificationSku(misSupplierProduct);
}
}
|
class Search
attr_accessor :totalResults,
:startIndex,
:itemsPerPage,
:artistmatches
def artistmatches
result = []
# if the search only has one result then lastfm sends a hash instead of an array
if @artistmatches['results']['artistmatches']['artist'].is_a?(Hash)
@artistmatches['results']['artistmatches']['artist'] = [@artistmatches['results']['artistmatches']['artist']]
end
if @artistmatches['results']['artistmatches']['artist']
@artistmatches['results']['artistmatches']['artist'].each do |artist|
a = Artist.new
a.name = artist['name']
a.url = artist['url']
a.image = artist['image']
a.listeners = artist['listeners']
result.push a
end
end
return result
end
end |
#! /bin/sh
# $Id$
#
# Spawns CPP-inserver-fancy and CPP-inclient executables on a single host.
usage="usage: $0 #client_threads"
user=`whoami`
iterations=1000
if [ $# -ne 1 ]; then
echo $usage;
exit 1
fi
threads=$1;
########
######## Enable signal handler.
########
trap 'kill -1 $server_pid; ' 0 1 2 15
########
######## Start CPP-inserver-fancy and save its pid.
########
./CPP-inserver-fancy > \
${tmp}server.log 2>&1 &
server_pid=$!
sleep 2;
########
######## Start CPP-inclient.
########
./CPP-inclient -2 -T 100000 -m 69 -t $threads -i 100 > ${tmp}client-${threads}.log 2>&1
|
<reponame>kirancchand/n7-see-frontend-beta-1-7
export const types = {
SEND_REQUEST: 'SEND_REQUEST',
SEND_REQUEST_SUCCESS: 'SEND_REQUEST_SUCCESS',
SEND_REQUEST_FAILURE: 'SEND_REQUEST_FAILURE',
SEND_HOMEPAGE_REQUEST: 'SEND_HOMEPAGE_REQUEST',
SEND_HOMEPAGE_REQUEST_SUCCESS: 'SEND_HOMEPAGE_REQUEST_SUCCESS',
SEND_HOMEPAGE_REQUEST_FAILURE: 'SEND_HOMEPAGE_REQUEST_FAILURE',
};
|
<reponame>JArmunia/Calendario
/**
* Calendario.java
*
* @author <NAME>
* @version 14-9-2018
*/
package Control;
import Modelo.calendarioOnline.PrimitivaComunicacion;
import Modelo.CalendarioModelo;
import Modelo.Contacto;
import Modelo.FactoriaModelo;
import Vista.CalendarioVista;
import Modelo.Recordatorio;
import Modelo.Tupla;
import Vista.DebugVista;
import Vista.FactoriaVista;
import com.google.gson.Gson;
import Modelo.calendarioOnline.ClienteCalendarioOnline;
import Vista.InicioSesionVista;
import Vista.Localizacion;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import static java.lang.Thread.sleep;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
public class Calendario implements OyenteVista {
/**
* Configuración
*/
private static String FICHERO_CONFIG_WRONG
= "Config file is wrong. Set default values";
private static String COMENTARIO_CONFIG
= "country = ES|US, language = es|en";
public static String VERSION = "2.0";
private static final String REGEX_RECORDATORIOS = ".*\\.rec$";
private static final String REGEX_CONTACTOS = ".*\\.cont$";
private Properties configuracion;
private static final String FICHERO_CONFIG = "config.properties";
public static final String LENGUAJE = "language";
private String lenguaje;
public static final String PAIS = "country";
public String pais;
private CalendarioVista vista;
private CalendarioModelo modelo;
private Calendario calendario;
private String ficheroRecordatorios = null;
private String ficheroContactos = null;
private boolean modoDebug = false;
private Localizacion localizacion;
private static String ARG_DEBUG = "-d";
/**
* Constructor del Calendario.
*
* @param args: Argumentos pasados por consola
*/
public Calendario(String[] args) {
calendario = this;
procesarArgsMain(args);
leerConfiguracion();
localizacion = Localizacion.devolverInstancia(LENGUAJE, PAIS);
modelo = FactoriaModelo.nuevoCalendario(this, localizacion);
vista = FactoriaVista.calendarioVista(
this, VERSION, modelo, lenguaje, pais);
modelo.addObserver(vista);
new InicioSesionVista(this, localizacion, InicioSesionVista.INICIO_SESION);
}
/**
* Main
* @param args
*/
public static void main(String[] args) {
new Calendario(args);
}
/**
* Inicio de sesion del usuario
*
* @param credenciales
*/
private void iniciarSesion(Tupla<String, String> credenciales) {
boolean seguir = true;
while (seguir) {
if (modelo.comprobarPass(credenciales.a, credenciales.b)) {
seguir = false;
modelo.ponerUsuario(credenciales.a);
vista.mostrar(true);
} else {
InicioSesionVista inicioSesion
= new InicioSesionVista(this, localizacion,
InicioSesionVista.INICIO_SESION,
localizacion.devuelve(localizacion.FALLO_INICIO_SESION));
}
}
}
/**
* Cierre de sesion del usuario
*/
private void cerrarSesion(){
modelo.quitarUsuario();
vista.mostrar(false);
new InicioSesionVista(this, localizacion, InicioSesionVista.INICIO_SESION);
}
/**
* Registro del usuario
* @param credenciales
*/
private void registrarUsuario(Tupla<String, String> credenciales) {
boolean seguir = true;
while (seguir) {
if (modelo.nuevoUsuario(credenciales.a, credenciales.b)) {
seguir = false;
InicioSesionVista inicioSesion
= new InicioSesionVista(this, localizacion,
InicioSesionVista.INICIO_SESION,
localizacion.devuelve(localizacion.REGISTRO_EXITOSO));
} else {
InicioSesionVista registro
= new InicioSesionVista(this, localizacion,
InicioSesionVista.REGISTRO_USUARIO,
localizacion.devuelve(localizacion.FALLO_REGISTRO));
}
}
}
/**
* Lee configuración
*
*/
private void leerConfiguracion() {
// valores por defecto de localización;
lenguaje = Locale.getDefault().getLanguage();
pais = Locale.getDefault().getCountry();
try {
configuracion = new Properties();
configuracion.load(new FileInputStream(FICHERO_CONFIG));
lenguaje = configuracion.getProperty(LENGUAJE);
pais = configuracion.getProperty(PAIS);
// si falta lenguaje o país ponemos valores por defecto
if ((lenguaje == null) || (pais == null)) {
lenguaje = Locale.getDefault().getLanguage();
configuracion.setProperty(LENGUAJE, lenguaje);
pais = Locale.getDefault().getCountry();
configuracion.setProperty(PAIS, pais);
} else {
Locale.setDefault(new Locale(lenguaje, pais));
}
} catch (Exception e) {
configuracion.setProperty(LENGUAJE, lenguaje);
configuracion.setProperty(PAIS, pais);
if (esModoDebug()) {
DebugVista.devolverInstancia().mostrar(FICHERO_CONFIG_WRONG, e);
}
}
}
/**
* Añade un nuevo recordatorio en el dia indicado
*
* @param recordatorio a introducir
*/
public void nuevo(Recordatorio recordatorio) {
new Thread() {
public boolean resultado;
@Override
public void run() {
if (!modelo.nuevo(recordatorio)) {
vista.mensajeDialogo(
localizacion.devuelve(
localizacion.RECORDATORIO_NO_GUARDADO));
} else {
vista.habilitarEvento(Evento.GUARDAR_RECORDATORIOS, true);
}
}
}.start();
}
/**
* Edita el recordatorio seleccionado
*
* @param recordatorio con la información que sustituirá al antiguo
*/
public void editar(Recordatorio recordatorio) {
new Thread() {
public boolean resultado;
@Override
public void run() {
boolean resultado = modelo.editar(recordatorio);
if (!resultado) {
vista.mensajeDialogo(
localizacion.devuelve(
localizacion.RECORDATORIO_NO_EDITADO));
} else {
vista.habilitarEvento(Evento.GUARDAR_RECORDATORIOS, true);
}
}
}.start();
}
/**
* Elimina el recordatorio seleccionado
*
*/
public void eliminar() {
new Thread() {
public boolean resultado;
@Override
public void run() {
boolean resultado = modelo.eliminar(
vista.devuelveVistaRecordatorios().
devuelveRecordatorioSeleccionado());
if (!resultado) {
vista.mensajeDialogo(
localizacion.devuelve(
localizacion.RECORDATORIO_NO_ELIMINADO));
} else {
vista.habilitarEvento(Evento.GUARDAR_RECORDATORIOS, true);
}
}
}.start();
}
/**
* Introduce un nuevo contacto
*
* @param contacto
*/
public void nuevo(Contacto contacto) {
new Thread() {
public boolean resultado;
@Override
public void run() {
if (!modelo.nuevo(contacto)) {
vista.mensajeDialogo(
localizacion.devuelve(
localizacion.CONTACTO_NO_GUARDADO));
} else {
vista.habilitarEvento(Evento.GUARDAR_CONTACTOS, true);
}
}
}.start();
}
/**
* Edita el contacto seleccionado
*
* @param contacto
*/
public void editar(Contacto contacto) {
new Thread() {
public boolean resultado;
@Override
public void run() {
boolean resultado = modelo.editar(contacto);
if (!resultado) {
vista.mensajeDialogo(
localizacion.devuelve(
localizacion.CONTACTO_NO_EDITADO));
} else {
vista.habilitarEvento(Evento.GUARDAR_CONTACTOS, true);
}
}
}.start();
}
/**
* Elimina el contacto seleccionado
*
* @param contacto
*/
public void eliminar(Contacto contacto) {
new Thread() {
public boolean resultado;
@Override
public void run() {
boolean resultado = modelo.eliminar(contacto);
if (!resultado) {
vista.mensajeDialogo(
localizacion.devuelve(
localizacion.CONTACTO_NO_ELIMINADO));
} else {
vista.habilitarEvento(Evento.GUARDAR_CONTACTOS, true);
}
}
}.start();
}
/**
* Cierra el programa dando opción a guardar el calendario
*/
public void salir() {
// guarda configuración
try {
FileOutputStream fichero = new FileOutputStream(FICHERO_CONFIG);
configuracion.store(fichero, COMENTARIO_CONFIG);
fichero.close();
} catch (Exception e) {
if (esModoDebug()) {
DebugVista.devolverInstancia().mostrar(
localizacion.CONFIGURACION_NO_GUARDADA, e);
} else {
vista.mensajeDialogo(
localizacion.devuelve(
localizacion.CONFIGURACION_NO_GUARDADA));
}
}
System.exit(0);
}
/**
* Cambia lenguaje
*
* @param tupla
*/
private void cambiarLenguaje(Tupla tupla) {
configuracion.setProperty(LENGUAJE, (String) tupla.a);
configuracion.setProperty(PAIS, (String) tupla.b);
salir();
}
/**
* Indica si aplicación está en modo debug
*
*/
public boolean esModoDebug() {
return modoDebug;
}
/**
* Procesa argumentos de main. Si está ARG_DEBUG como argumento, pone el
* calendario en modo debug. Si se pasan ficheros de contactos o
* recordatorios, los carga en el calendario.
*
*/
private void procesarArgsMain(String[] args) {
List<String> argumentos = new ArrayList<String>(Arrays.asList(args));
if (argumentos.contains(ARG_DEBUG)) {
modoDebug = true;
}
}
/**
* Recibe eventos de vista
*
* @param evento
* @param obj
*/
@Override
public void eventoProducido(Evento evento, Object obj) {
switch (evento) {
case INICIAR_SESION:
iniciarSesion((Tupla<String, String>) obj);
break;
case CERRAR_SESION:
cerrarSesion();
break;
case REGISTRAR_USUARIO:
registrarUsuario((Tupla<String, String>) obj);
break;
case NUEVO_RECORDATORIO:
nuevo((Recordatorio) obj);
break;
case EDITAR_RECORDATORIO:
Calendario.this.editar((Recordatorio) obj);
break;
case ELIMINAR_RECORDATORIO:
eliminar();
break;
case NUEVO_CONTACTO:
nuevo((Contacto) obj);
break;
case EDITAR_CONTACTO:
editar((Contacto) obj);
break;
case ELIMINAR_CONTACTO:
Calendario.this.eliminar((Contacto) obj);
break;
case SALIR:
salir();
break;
case CAMBIAR_LENGUAJE:
cambiarLenguaje((Tupla) obj);
break;
}
}
}
|
#!/usr/bin/env bash
eb deploy my-beanstalk-wormer --region eu-west-2
eb deploy my-beanstalk-wormer --region ap-southeast-2
|
import { SpriteFontLoader } from '../loaders';
import { SpriteFont } from '../text';
import { Rect } from '../Rect';
import { CanvasImage } from './sources';
interface ColorSpriteFontGeneratorIitem {
defaultColor: string;
defaultFont: SpriteFont;
canvas?: NativeCanvas;
generatedFonts: Map<string, SpriteFont>;
}
export class ColorSpriteFontGenerator {
private spriteFontLoader: SpriteFontLoader;
private map = new Map<string, ColorSpriteFontGeneratorIitem>();
constructor(spriteFontLoader: SpriteFontLoader) {
this.spriteFontLoader = spriteFontLoader;
}
public get(fontId: string, color: string = null): SpriteFont {
const item = this.map.get(fontId);
if (item === undefined) {
throw new Error(`Font "${fontId}" not registered`);
}
const { defaultColor, defaultFont, generatedFonts } = item;
if (color === null || color === defaultColor) {
return defaultFont;
}
const generatedFont = generatedFonts.get(color);
if (generatedFont === undefined) {
throw new Error(`Font "${fontId}" color "${color}" not generated`);
}
return generatedFont;
}
public register(fontId: string, defaultColor: string): void {
const defaultFont = this.spriteFontLoader.load(fontId);
// Initial font is registered by it's default color.
// Based on this initial font other colors are generated as separate fonts.
const generatedFonts = new Map<string, SpriteFont>();
const item = {
defaultColor,
defaultFont,
generatedFonts,
};
this.map.set(fontId, item);
}
public generate(fontId: string, generatedColor: string): void {
const item = this.map.get(fontId);
if (item === undefined) {
throw new Error(`Font "${fontId}" not registered`);
}
const { defaultFont } = item;
const sourceRect = defaultFont.getImageSourceRect();
let canvas = item.canvas;
const isNewCanvas = canvas === undefined;
if (isNewCanvas) {
canvas = document.createElement('canvas');
canvas.width = sourceRect.width;
canvas.height = sourceRect.height;
// Keep for debug
// document.body.appendChild(canvas);
// Save canvas for following fonts
item.canvas = canvas;
}
const context = canvas.getContext('2d');
const prevHeight = canvas.height;
let prevImageData = null;
if (!isNewCanvas) {
// Make sure to save all drawings, because we are going to resize the
// canvas
prevImageData = context.getImageData(0, 0, canvas.width, canvas.height);
// Calculate new area taken by all generated fonts on canvas.
// New generated font will be added at the bottom.
const prevHeight = canvas.height;
const nextHeight = prevHeight + sourceRect.height;
// WARNING: all drawing is erased when canvas is resized.
// Update canvas size to include area for new generated font
canvas.height = nextHeight;
}
const generatedY = isNewCanvas ? 0 : prevHeight;
// New generated font area on canvas
const generatedSourceRect = new Rect(
0,
generatedY,
sourceRect.width,
sourceRect.height,
);
// Draw original image onto canvas
context.globalCompositeOperation = 'source-over';
context.drawImage(
defaultFont.image.getElement(),
sourceRect.x,
sourceRect.y,
sourceRect.width,
sourceRect.height,
generatedSourceRect.x,
generatedSourceRect.y,
generatedSourceRect.width,
generatedSourceRect.height,
);
// Use composite operation to create colored version of the font
context.globalCompositeOperation = 'source-in';
context.fillStyle = generatedColor;
context.fillRect(
generatedSourceRect.x,
generatedSourceRect.y,
generatedSourceRect.width,
generatedSourceRect.height,
);
context.globalCompositeOperation = 'source-over';
// Restore previously drawn fonts. Do it after new font is drawn,
// because composite operations are applied on entire canvas and will
// screw up existing fonts if they are drawn earlier.
if (!isNewCanvas) {
context.putImageData(prevImageData, 0, 0);
}
// Use canvas as image source for rendering the font
const generatedImage = new CanvasImage(canvas);
// Clone font config to specify location of characters on canvas
const generatedFontConfig = Object.assign({}, defaultFont.config, {
offsetX: generatedSourceRect.x,
offsetY: generatedSourceRect.y,
});
const generatedFont = new SpriteFont(
generatedFontConfig,
generatedImage,
defaultFont.options,
);
item.generatedFonts.set(generatedColor, generatedFont);
}
}
|
package org.dspace.content.authority.mesh;
import org.dspace.core.ConfigurationManager;
import java.io.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class MeSHMapLoader {
static private Map<String, Map<String, String>> cachedTrees = new HashMap<String, Map<String, String>>();
static private String treeFileName = null;
static private String testTreeFileName = null;
static public Map<String, String> load() {
return MeSHMapLoader.load(null);
}
static public Map<String, String> load(Locale loc) {
String language;
if (loc == null) {
language = Locale.ENGLISH.getLanguage();
} else {
language = loc.getLanguage();
}
synchronized (cachedTrees) {
if (cachedTrees.containsKey(language)) {
return cachedTrees.get(language);
}
InputStream is = getInputStream(language);
if (is == null && language.startsWith("en")) {
is = getInputStream(null);
}
// File treeFile = new File(treeFileName + "_" + language);
// if (!treeFile.exists() && language.startsWith("en")) {
// treeFile = new File(treeFileName);
// }
if (is == null) {
return null;
}
try {
Map<String, String> meshTree = new HashMap<String, String>();
BufferedReader meshReader = new BufferedReader(new InputStreamReader(is));
//new BufferedReader(new FileReader(treeFile));
String meshLine = meshReader.readLine();
while (meshLine != null) {
String[] meshLineArray = meshLine.split(";");
if (meshLineArray.length == 2) {
meshTree.put(meshLineArray[1], meshLineArray[0]);
}
meshLine = meshReader.readLine();
}
cachedTrees.put(language, meshTree);
return meshTree;
} catch (IOException ioe) {
return null;
}
}
}
static private InputStream getInputStream(String language) {
try {
if (language != null) {
if (testTreeFileName != null) {
return MeSHMapLoader.class.getClassLoader().getResourceAsStream(testTreeFileName + "_" + language);
}
initTreeFileName();
return new FileInputStream(treeFileName + "_" + language);
} else {
if (testTreeFileName != null) {
return MeSHMapLoader.class.getClassLoader().getResourceAsStream(testTreeFileName);
}
initTreeFileName();
return new FileInputStream(treeFileName);
}
} catch (IOException ioe) {
return null;
}
}
static private void initTreeFileName() {
treeFileName = ConfigurationManager.getProperty("mesh.tree.file");
}
static void setTestTreeFileName(String name) {
testTreeFileName = name;
}
}
|
# curl -O http://localhost:5002/swagger/external/swagger.json
autorest --input-file=swagger.json --output-folder=. --namespace=Kmd.Studica.SchoolAdministration.Client --csharp --add-credentials --payload-flattening-threshold=2
|
#!/bin/sh
. /usr/share/openclash/openclash_ps.sh
. /lib/functions.sh
status=$(unify_ps_status "openclash_rule.sh")
[ "$status" -gt 3 ] && exit 0
START_LOG="/tmp/openclash_start.log"
LOGTIME=$(date "+%Y-%m-%d %H:%M:%S")
LOG_FILE="/tmp/openclash.log"
echo "开始获取使用中的第三方规则名称..." >$START_LOG
RUlE_SOURCE=$(uci get openclash.config.rule_source 2>/dev/null)
OTHER_RULE_PROVIDER_FILE="/tmp/other_rule_provider.yaml"
OTHER_SCRIPT_FILE="/tmp/other_rule_script.yaml"
OTHER_RULE_FILE="/tmp/other_rule.yaml"
echo "开始下载使用中的第三方规则..." >$START_LOG
if [ "$RUlE_SOURCE" = "lhie1" ]; then
if pidof clash >/dev/null; then
curl -sL --connect-timeout 10 --retry 2 https://raw.githubusercontent.com/lhie1/Rules/master/Clash/Rule.yaml -o /tmp/rules.yaml >/dev/null 2>&1
else
curl -sL --connect-timeout 10 --retry 2 https://cdn.jsdelivr.net/gh/lhie1/Rules@master/Clash/Rule.yaml -o /tmp/rules.yaml >/dev/null 2>&1
fi
sed -i '1i rules:' /tmp/rules.yaml
elif [ "$RUlE_SOURCE" = "ConnersHua" ]; then
if pidof clash >/dev/null; then
curl -sL --connect-timeout 10 --retry 2 https://raw.githubusercontent.com/DivineEngine/Profiles/master/Clash/Global.yaml -o /tmp/rules.yaml >/dev/null 2>&1
else
curl -sL --connect-timeout 10 --retry 2 https://cdn.jsdelivr.net/gh/DivineEngine/Profiles@master/Clash/Global.yaml -o /tmp/rules.yaml >/dev/null 2>&1
fi
sed -i -n '/^rule-providers:/,$p' /tmp/rules.yaml 2>/dev/null
sed -i "s/# - RULE-SET,ChinaIP,DIRECT/- RULE-SET,ChinaIP,DIRECT/g" /tmp/rules.yaml 2>/dev/null
sed -i "s/- GEOIP,/#- GEOIP,/g" /tmp/rules.yaml 2>/dev/null
elif [ "$RUlE_SOURCE" = "ConnersHua_return" ]; then
if pidof clash >/dev/null; then
curl -sL --connect-timeout 10 --retry 2 https://raw.githubusercontent.com/ConnersHua/Profiles/master/Clash/China.yaml -o /tmp/rules.yaml >/dev/null 2>&1
else
curl -sL --connect-timeout 10 --retry 2 https://cdn.jsdelivr.net/gh/DivineEngine/Profiles@master/Clash/China.yaml -o /tmp/rules.yaml >/dev/null 2>&1
fi
sed -i -n '/^rules:/,$p' /tmp/rules.yaml 2>/dev/null
fi
if [ "$?" -eq "0" ] && [ "$RUlE_SOURCE" != 0 ] && [ -s "/tmp/rules.yaml" ]; then
echo "下载成功,开始预处理规则文件..." >$START_LOG
sed -i "/^rules:/a\##source:${RUlE_SOURCE}" /tmp/rules.yaml >/dev/null 2>&1
#处理rule_provider位置
rule_provider_len=$(sed -n '/^ \{0,\}rule-providers:/=' "/tmp/rules.yaml" 2>/dev/null)
if [ -n "$rule_provider_len" ]; then
/usr/share/openclash/yml_field_cut.sh "$rule_provider_len" "$OTHER_RULE_PROVIDER_FILE" "/tmp/rules.yaml"
fi 2>/dev/null
#处理script位置
script_len=$(sed -n '/^ \{0,\}script:/=' "/tmp/rules.yaml" 2>/dev/null)
if [ -n "$script_len" ]; then
/usr/share/openclash/yml_field_cut.sh "$script_len" "$OTHER_SCRIPT_FILE" "/tmp/rules.yaml"
fi 2>/dev/null
#处理备份rule位置
rule_bak_len=$(sed -n '/^ \{0,\}rules:/=' "/tmp/rules.yaml" 2>/dev/null)
if [ -n "$rule_bak_len" ]; then
/usr/share/openclash/yml_field_cut.sh "$rule_bak_len" "$OTHER_RULE_FILE" "/tmp/rules.yaml"
fi 2>/dev/null
#合并
cat "$OTHER_RULE_PROVIDER_FILE" "$OTHER_SCRIPT_FILE" "$OTHER_RULE_FILE" > "/tmp/rules.yaml" 2>/dev/null
rm -rf /tmp/other_rule* 2>/dev/null
rm -rf /tmp/yaml_general 2>/dev/null
echo "检查下载的规则文件是否有更新..." >$START_LOG
cmp -s /usr/share/openclash/res/"$RUlE_SOURCE".yaml /tmp/rules.yaml
if [ "$?" -ne "0" ]; then
echo "检测到下载的规则文件有更新,开始替换..." >$START_LOG
mv /tmp/rules.yaml /usr/share/openclash/res/"$RUlE_SOURCE".yaml >/dev/null 2>&1
sed -i '/^rules:/a\##updated' /usr/share/openclash/res/"$RUlE_SOURCE".yaml >/dev/null 2>&1
echo "替换成功,重新加载 OpenClash 应用新规则..." >$START_LOG
echo "${LOGTIME} Other Rules 【$RUlE_SOURCE】 Update Successful" >>$LOG_FILE
[ "$(unify_ps_prevent)" -eq 0 ] && /etc/init.d/openclash restart
else
echo "检测到下载的规则文件没有更新,停止继续操作..." >$START_LOG
rm -rf /tmp/rules.yaml >/dev/null 2>&1
echo "${LOGTIME} Updated Other Rules 【$RUlE_SOURCE】 No Change, Do Nothing" >>$LOG_FILE
sleep 10
echo "" >$START_LOG
fi
elif [ "$RUlE_SOURCE" = 0 ]; then
echo "未启用第三方规则,更新程序终止!" >$START_LOG
rm -rf /tmp/rules.yaml >/dev/null 2>&1
echo "${LOGTIME} Other Rules Not Enable, Update Stop" >>$LOG_FILE
sleep 10
echo "" >$START_LOG
else
echo "第三方规则下载失败,请检查网络或稍后再试!" >$START_LOG
rm -rf /tmp/rules.yaml >/dev/null 2>&1
echo "${LOGTIME} Other Rules 【$RUlE_SOURCE】 Update Error" >>$LOG_FILE
sleep 10
echo "" >$START_LOG
fi
|
#!/bin/bash
set -ueo pipefail
channel="${CHANNEL:-unstable}"
product="${PRODUCT:-chef-workstation}"
version="${VERSION:-latest}"
is_darwin()
{
uname -v | grep "^Darwin" >/dev/null 2>&1
}
echo "--- Installing $channel $product $version"
package_file="$(/opt/omnibus-toolchain/bin/install-omnibus-product -c "$channel" -P "$product" -v "$version" | tail -n 1)"
echo "--- Verifying omnibus package is signed"
/opt/omnibus-toolchain/bin/check-omnibus-package-signed "$package_file"
sudo rm -f "$package_file"
echo "--- Verifying ownership of package files"
export INSTALL_DIR=/opt/chef-workstation
NONROOT_FILES="$(find "$INSTALL_DIR" ! -user 0 -print)"
if [[ "$NONROOT_FILES" == "" ]]; then
echo "Packages files are owned by root. Continuing verification."
else
echo "Exiting with an error because the following files are not owned by root:"
echo "$NONROOT_FILES"
exit 1
fi
echo "--- Running verification for $channel $product $version"
# Ensure user variables are set in git config
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
export CHEF_LICENSE="accept-no-persist"
# chef version ensures our bin ends up on path and the basic ruby env is working.
chef-run --version
# Ensure our Chef Workstation works
chef env
# Run Chef Workstation verification suite to ensure it still works
chef verify
# Verify that the chef-workstation-app was installed (MacOS only)
if is_darwin; then
echo "Verifying that chef-workstation-app exist in /Applications directory"
test -d "/Applications/Chef Workstation App.app"
fi
|
def string_condenser(my_string):
prev = ''
output_string = ''
counter = 1
for c in my_string:
if c == prev:
counter += 1
else:
if counter > 1:
output_string += prev + str(counter)
elif counter == 1:
output_string += prev
prev = c
counter = 1
if counter > 1:
output_string += prev + str(counter)
elif counter == 1:
output_string += prev
return output_string |
/*
* Copyright (c) 2017 Sprint
*
* 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.
*/
#include "chronos.h"
#include "logger.h"
#include "rule.h"
void ChronosHandler::onRequest( const Pistache::Http::Request &request, Pistache::Http::ResponseWriter response )
{
Logger::chronos().debug( "%s:%d - ChronosHandler::onRequest() - received request [%s] body [%s]",
__FILE__, __LINE__, request.resource().c_str(), request.body().c_str() );
if ( request.resource() == "/ruleTimer")
{
response.send( Pistache::Http::Code::Ok, "" );
RuleTimer *rt = RuleTimers::singleton().getRuleTimer( request.body() );
if ( rt )
{
try
{
rt->setNextInterval();
}
catch ( std::runtime_error &e )
{
Logger::chronos().error( "%s:%d - ChronosHandler::onRequest() - RuleTimer for [%s] setNextInterval() threw exception - %s"
__FILE__, __LINE__, rt->getRule()->getRuleName().c_str(), e.what() );
}
try
{
rt->processIntervalExpiration();
}
catch ( std::runtime_error &e )
{
Logger::chronos().error( "%s:%d - ChronosHandler::onRequest() - RuleTimer for [%s] processIntervalExpiration() threw exception - %s"
__FILE__, __LINE__, rt->getRule()->getRuleName().c_str(), e.what() );
}
}
else
{
Logger::chronos().warn( "%s:%d - ChronosHandler::onRequest() - unable to find rule [%s]",
__FILE__, __LINE__, request.body().c_str() );
}
}
else
{
response.send( Pistache::Http::Code::Bad_Request );
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Pistache::Http::Client Chronos::m_client;
//
// It seems that the Pistache::Http::Client is buggy. If problems occur,
// it may be necessary to move to a different http client library.
//
void Chronos::init()
{
auto opts = Pistache::Http::Client::options()
.threads(1)
.maxConnectionsPerHost(8);
client().init( opts );
}
void Chronos::uninit()
{
client().shutdown();
}
|
<filename>ods-base-support/ods-core/src/main/java/cn/stylefeng/guns/core/exception/ServiceException.java
/*
Copyright [2020] [https://www.stylefeng.cn]
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.
Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Guns源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处,作者声明等。
4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns-separation
5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns-separation
6.若您的项目无法满足以上几点,可申请商业授权,获取Guns商业授权许可,请在官网购买授权,地址为 https://www.stylefeng.cn
*/
package cn.stylefeng.guns.core.exception;
import cn.stylefeng.guns.core.exception.enums.abs.AbstractBaseExceptionEnum;
import java.util.Objects;
/**
* 业务异常
*
* @author xuyuxiang
* @date 2020/4/8 15:54
*/
public class ServiceException extends RuntimeException {
private Integer code;
private String errorMessage;
public ServiceException(Integer code, String errorMessage) {
super(errorMessage);
this.code = code;
this.errorMessage = errorMessage;
}
public ServiceException(AbstractBaseExceptionEnum exception) {
super(exception.getMessage());
this.code = exception.getCode();
this.errorMessage = exception.getMessage();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ServiceException that = (ServiceException) o;
return Objects.equals(code, that.code) &&
Objects.equals(errorMessage, that.errorMessage);
}
@Override
public int hashCode() {
return Objects.hash(code, errorMessage);
}
@Override
public String toString() {
return "ServiceException{" +
"code=" + code +
", errorMessage='" + errorMessage + '\'' +
'}';
}
}
|
import React from "react";
var LayoutStateContext = React.createContext();
var LayoutDispatchContext = React.createContext();
function layoutReducer(state, action) {
switch (action.type) {
case "TOGGLE_SIDEBAR":
return { ...state, isSidebarOpened: !state.isSidebarOpened };
default: {
throw new Error(`Unhandled action type: ${action.type}`);
}
}
}
function LayoutProvider({ children }) {
var [state, dispatch] = React.useReducer(layoutReducer, {
isSidebarOpened: true,
userLanguage: "zh-CN",
});
return (
<LayoutStateContext.Provider value={state}>
<LayoutDispatchContext.Provider value={dispatch}>
{children}
</LayoutDispatchContext.Provider>
</LayoutStateContext.Provider>
);
}
function useLayoutState() {
var context = React.useContext(LayoutStateContext);
if (context === undefined) {
throw new Error("useLayoutState must be used within a LayoutProvider");
}
return context;
}
function useLayoutDispatch() {
var context = React.useContext(LayoutDispatchContext);
if (context === undefined) {
throw new Error("useLayoutDispatch must be used within a LayoutProvider");
}
return context;
}
export {
LayoutProvider,
useLayoutState,
useLayoutDispatch,
toggleSidebar,
changeTheme,
};
// ###########################################################
function toggleSidebar(dispatch) {
dispatch({
type: "TOGGLE_SIDEBAR",
});
}
function changeTheme(dispatch) {
dispatch({
type: "CHANGE_THEME",
});
}
|
const BaseEmbed = require("../../modules/BaseEmbed");
const { toCapitalize } = require("../../utils/functions");
module.exports = {
name: "rps",
description: "Rock Paper Scissors",
category: "games",
usage: "rps <rock | paper | scissors>",
requiredArgs: ["rock | paper | scissors"],
cooldown: 5,
async execute(bot, message, args) {
const lang = await bot.getGuildLang(message.guild.id);
const input = args.join("").toLowerCase();
const replies = [lang.GAMES.ROCK, lang.GAMES.PAPER, lang.GAMES.SCISSORS];
const inp = replies.find((r) => r.toLowerCase() === input);
if (!inp) {
return message.channel.send(`${lang.GAMES.INVALID_INPUT} <rock | paper | scissors>`);
}
const reply = replies[Math.floor(Math.random() * replies.length)];
const hasWon = checkWon(inp.toLowerCase(), reply.toLowerCase());
if (hasWon === true) {
const { user } = await bot.getUserById(message.author.id, message.guild.id);
await bot.updateUserById(message.author.id, message.guild.id, {
money: user.money + 50,
});
}
const winner =
hasWon === true
? lang.GAMES.YOU_WON
: hasWon === 0
? lang.GAMES.BOTH_WON
: lang.GAMES.BOT_WON;
const embed = BaseEmbed(message)
.setTitle(lang.GAMES.RPS)
.setDescription(`**${lang.GAMES.WINNER}:** ${winner}`)
.addField(lang.GAMES.YOUR_CHOICE, toCapitalize(input))
.addField(lang.GAMES.OPPONENTS_CHOICE, reply);
message.channel.send(embed);
},
};
function checkWon(input, reply) {
const isRock = (v) => v === "rock";
const isPaper = (v) => v === "paper";
const isScissors = (v) => v === "scissors";
const IWon =
(isRock(input) && isScissors(reply)) /* 'Rock' wins over 'Scissors' */ ||
(isPaper(input) && isRock(reply)) /* 'Paper' wins over 'Rock' */ ||
(isScissors(input) && isPaper(reply)); /* 'Scissors' wins over 'Paper' */
if (IWon) {
return true;
} else if (input === reply) {
return 0;
} else {
return false;
}
}
|
package com.datahub.authentication.authenticator;
import com.datahub.authentication.Actor;
import com.datahub.authentication.ActorType;
import com.datahub.authentication.Authentication;
import com.datahub.authentication.AuthenticationException;
import com.datahub.authentication.AuthenticationRequest;
import com.datahub.authentication.AuthenticatorContext;
import com.datahub.authentication.token.TokenType;
import com.google.common.collect.ImmutableMap;
import com.linkedin.common.urn.Urn;
import com.linkedin.data.schema.annotation.PathSpecBasedSchemaAnnotationVisitor;
import com.linkedin.metadata.Constants;
import com.linkedin.metadata.entity.EntityService;
import com.linkedin.metadata.models.AspectSpec;
import com.linkedin.metadata.models.registry.ConfigEntityRegistry;
import org.mockito.Mockito;
import org.testng.annotations.Test;
import java.util.Collections;
import java.util.Map;
import static com.datahub.authentication.AuthenticationConstants.AUTHORIZATION_HEADER_NAME;
import static com.datahub.authentication.AuthenticationConstants.ENTITY_SERVICE;
import static com.datahub.authentication.authenticator.DataHubTokenAuthenticator.SALT_CONFIG_NAME;
import static com.datahub.authentication.authenticator.DataHubTokenAuthenticator.SIGNING_ALG_CONFIG_NAME;
import static com.datahub.authentication.authenticator.DataHubTokenAuthenticator.SIGNING_KEY_CONFIG_NAME;
import static com.datahub.authentication.token.TokenClaims.ACTOR_ID_CLAIM_NAME;
import static com.datahub.authentication.token.TokenClaims.ACTOR_TYPE_CLAIM_NAME;
import static com.datahub.authentication.token.TokenClaims.TOKEN_TYPE_CLAIM_NAME;
import static com.datahub.authentication.token.TokenClaims.TOKEN_VERSION_CLAIM_NAME;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertThrows;
public class DataHubTokenAuthenticatorTest {
private static final String TEST_SIGNING_KEY = "WnEdIeTG/VVCLQqGwC/BAkqyY0k+H8NEAtWGejrBI94=";
private static final String TEST_SALT = "WnEdIeTG/VVCLQqGwC/BAkqyY0k+H8NEAtWGejrBI93=";
final EntityService mockService = Mockito.mock(EntityService.class);
@Test
public void testInit() {
final DataHubTokenAuthenticator authenticator = new DataHubTokenAuthenticator();
AuthenticatorContext authenticatorContext =
new AuthenticatorContext(ImmutableMap.of(ENTITY_SERVICE, mockService));
assertThrows(() -> authenticator.init(null, authenticatorContext));
assertThrows(() -> authenticator.init(Collections.emptyMap(), authenticatorContext));
assertThrows(() -> authenticator.init(ImmutableMap.of(SIGNING_KEY_CONFIG_NAME, TEST_SIGNING_KEY,
SIGNING_ALG_CONFIG_NAME, "UNSUPPORTED_ALG"), authenticatorContext));
assertThrows(() -> authenticator.init(ImmutableMap.of(SIGNING_KEY_CONFIG_NAME, TEST_SIGNING_KEY,
SIGNING_ALG_CONFIG_NAME, "HS256"), null));
// Correct configs provided.
authenticator.init(ImmutableMap.of(SIGNING_KEY_CONFIG_NAME, TEST_SIGNING_KEY, SALT_CONFIG_NAME,
TEST_SALT, SIGNING_ALG_CONFIG_NAME, "HS256"), authenticatorContext);
}
@Test
public void testAuthenticateFailureMissingAuthorizationHeader() {
final DataHubTokenAuthenticator authenticator = new DataHubTokenAuthenticator();
authenticator.init(ImmutableMap.of(SIGNING_KEY_CONFIG_NAME, TEST_SIGNING_KEY, SALT_CONFIG_NAME,
TEST_SALT, SIGNING_ALG_CONFIG_NAME, "HS256"),
new AuthenticatorContext(ImmutableMap.of(ENTITY_SERVICE, mockService)));
final AuthenticationRequest context = new AuthenticationRequest(Collections.emptyMap());
assertThrows(AuthenticationException.class, () -> authenticator.authenticate(context));
}
@Test
public void testAuthenticateFailureMissingBearerCredentials() {
final DataHubTokenAuthenticator authenticator = new DataHubTokenAuthenticator();
authenticator.init(ImmutableMap.of(SIGNING_KEY_CONFIG_NAME, TEST_SIGNING_KEY, SALT_CONFIG_NAME,
TEST_SALT, SIGNING_ALG_CONFIG_NAME, "HS256"),
new AuthenticatorContext(ImmutableMap.of(ENTITY_SERVICE, mockService)));
final AuthenticationRequest context = new AuthenticationRequest(
ImmutableMap.of(AUTHORIZATION_HEADER_NAME, "Basic username:password")
);
assertThrows(AuthenticationException.class, () -> authenticator.authenticate(context));
}
@Test
public void testAuthenticateFailureInvalidToken() {
final DataHubTokenAuthenticator authenticator = new DataHubTokenAuthenticator();
authenticator.init(ImmutableMap.of(SIGNING_KEY_CONFIG_NAME, TEST_SIGNING_KEY, SALT_CONFIG_NAME,
TEST_SALT, SIGNING_ALG_CONFIG_NAME, "HS256"),
new AuthenticatorContext(ImmutableMap.of(ENTITY_SERVICE, mockService)));
final AuthenticationRequest context = new AuthenticationRequest(
ImmutableMap.of(AUTHORIZATION_HEADER_NAME, "Bearer someRandomToken")
);
assertThrows(AuthenticationException.class, () -> authenticator.authenticate(context));
}
@Test
public void testAuthenticateSuccess() throws Exception {
PathSpecBasedSchemaAnnotationVisitor.class.getClassLoader()
.setClassAssertionStatus(PathSpecBasedSchemaAnnotationVisitor.class.getName(), false);
final ConfigEntityRegistry configEntityRegistry = new ConfigEntityRegistry(
DataHubTokenAuthenticatorTest.class.getClassLoader().getResourceAsStream("test-entity-registry.yaml"));
final AspectSpec keyAspectSpec = configEntityRegistry.getEntitySpec(Constants.ACCESS_TOKEN_ENTITY_NAME).getKeyAspectSpec();
Mockito.when(mockService.getKeyAspectSpec(Mockito.eq(Constants.ACCESS_TOKEN_ENTITY_NAME))).thenReturn(keyAspectSpec);
Mockito.when(mockService.exists(Mockito.any(Urn.class))).thenReturn(true);
final DataHubTokenAuthenticator authenticator = new DataHubTokenAuthenticator();
authenticator.init(ImmutableMap.of(SIGNING_KEY_CONFIG_NAME, TEST_SIGNING_KEY, SALT_CONFIG_NAME,
TEST_SALT, SIGNING_ALG_CONFIG_NAME, "HS256"),
new AuthenticatorContext(ImmutableMap.of(ENTITY_SERVICE, mockService)));
final Actor datahub = new Actor(ActorType.USER, "datahub");
final String validToken = authenticator._statefulTokenService.generateAccessToken(
TokenType.PERSONAL,
datahub,
"some token",
"A token description",
datahub.toUrnStr()
);
final String authorizationHeaderValue = String.format("Bearer %s", validToken);
final AuthenticationRequest context = new AuthenticationRequest(
ImmutableMap.of(AUTHORIZATION_HEADER_NAME, authorizationHeaderValue)
);
final Authentication authentication = authenticator.authenticate(context);
// Validate the resulting authentication object
assertNotNull(authentication);
assertEquals(authentication.getActor().getType(), ActorType.USER);
assertEquals(authentication.getActor().getId(), "datahub");
assertEquals(authentication.getCredentials(), authorizationHeaderValue);
Map<String, Object> claimsMap = authentication.getClaims();
assertEquals(claimsMap.get(TOKEN_VERSION_CLAIM_NAME), 2);
assertEquals(claimsMap.get(TOKEN_TYPE_CLAIM_NAME), "PERSONAL");
assertEquals(claimsMap.get(ACTOR_TYPE_CLAIM_NAME), "USER");
assertEquals(claimsMap.get(ACTOR_ID_CLAIM_NAME), "datahub");
}
}
|
package chylex.hee.render.block;
import net.minecraft.client.renderer.entity.RenderTNTPrimed;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityTNTPrimed;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class RenderBlockEnhancedTNTPrimed extends RenderTNTPrimed{
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTickTime){
doRender((EntityTNTPrimed)entity, x, y+0.49D, z, yaw, partialTickTime);
}
}
|
<reponame>brenopessoa/diana-driver
/*
* Copyright (c) 2017 <NAME> and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* <NAME>
*/
package org.jnosql.diana.hazelcast.key;
import jakarta.nosql.key.BucketManagerFactory;
import org.jnosql.diana.hazelcast.key.model.ProductCart;
import org.jnosql.diana.hazelcast.key.util.KeyValueEntityManagerFactoryUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class ListTest {
private static final String FRUITS = "fruits";
private ProductCart banana = new ProductCart("banana", BigDecimal.ONE);
private ProductCart orange = new ProductCart("orange", BigDecimal.ONE);
private ProductCart waterMelon = new ProductCart("waterMelon", BigDecimal.TEN);
private ProductCart melon = new ProductCart("melon", BigDecimal.ONE);
private BucketManagerFactory keyValueEntityManagerFactory;
private List<ProductCart> fruits;
@BeforeEach
public void init() {
keyValueEntityManagerFactory = KeyValueEntityManagerFactoryUtils.get();
fruits = keyValueEntityManagerFactory.getList(FRUITS, ProductCart.class);
}
@Test
public void shouldReturnsList() {
assertNotNull(fruits);
}
@Test
public void shouldAddList() {
assertTrue(fruits.isEmpty());
fruits.add(banana);
assertFalse(fruits.isEmpty());
ProductCart banana = fruits.get(0);
assertNotNull(banana);
assertEquals(banana.getName(), "banana");
}
@Test
public void shouldSetList() {
fruits.add(banana);
fruits.add(0, orange);
assertTrue(fruits.size() == 2);
assertEquals(fruits.get(0).getName(), "orange");
assertEquals(fruits.get(1).getName(), "banana");
fruits.set(0, waterMelon);
assertEquals(fruits.get(0).getName(), "waterMelon");
assertEquals(fruits.get(1).getName(), "banana");
}
@Test
public void shouldRemoveList() {
fruits.add(banana);
}
@Test
public void shouldReturnIndexOf() {
fruits.add(new ProductCart("orange", BigDecimal.ONE));
fruits.add(banana);
fruits.add(new ProductCart("watermellon", BigDecimal.ONE));
fruits.add(banana);
assertTrue(fruits.indexOf(banana) == 1);
assertTrue(fruits.lastIndexOf(banana) == 3);
assertTrue(fruits.contains(banana));
assertTrue(fruits.indexOf(melon) == -1);
assertTrue(fruits.lastIndexOf(melon) == -1);
}
@Test
public void shouldReturnContains() {
fruits.add(orange);
fruits.add(banana);
fruits.add(waterMelon);
assertTrue(fruits.contains(banana));
assertFalse(fruits.contains(melon));
assertTrue(fruits.containsAll(Arrays.asList(banana, orange)));
assertFalse(fruits.containsAll(Arrays.asList(banana, melon)));
}
@SuppressWarnings("unused")
@Test
public void shouldIterate() {
fruits.add(melon);
fruits.add(banana);
int count = 0;
for (ProductCart fruiCart: fruits) {
count++;
}
assertTrue(count == 2);
fruits.remove(0);
fruits.remove(0);
count = 0;
for (ProductCart fruiCart: fruits) {
count++;
}
assertTrue(count == 0);
}
@AfterEach
public void end() {
fruits.clear();
}
}
|
import React, { Component } from 'react';
import './forget.css';
class Forget extends Component {
render() {
return (
<div>
忘记密码页面!!!
</div>
);
}
}
export default Forget |
<filename>test/test_helper.rb<gh_stars>1-10
require "rubygems"
require "test/unit"
# require "context"
require "matchy"
require "shoulda"
# require "mocha"
require File.dirname(__FILE__) + '/../lib/poolparty' |
#!/bin/bash
#
# Build librdkafka on a bare-bone Debian host, such as the microsoft/dotnet:2-sdk
# Docker image.
#
# Statically linked
# WITH openssl 1.0, zlib
# WITHOUT libsasl2, lz4(ext, using builtin instead)
#
# Usage (from top-level librdkafka dir):
# docker run -it -v $PWD:/v microsoft/dotnet:2-sdk /v/packaging/tools/build-debian.sh /v /v/librdkafka-debian9.tgz
#
set -ex
LRK_DIR=$1
OUT_TGZ=$2
if [[ ! -f $LRK_DIR/configure.self || -z $OUT_TGZ ]]; then
echo "Usage: $0 <librdkafka-root-direcotry> <output-tgz>"
exit 1
fi
set -u
apt-get update
apt-get install -y gcc g++ zlib1g-dev python3 git-core make
# Copy the librdkafka git archive to a new location to avoid messing
# up the librdkafka working directory.
BUILD_DIR=$(mktemp -d)
pushd $BUILD_DIR
DEST_DIR=$PWD/dest
mkdir -p $DEST_DIR
(cd $LRK_DIR ; git archive --format tar HEAD) | tar xf -
./configure --install-deps --disable-gssapi --disable-lz4-ext --enable-static --prefix=$DEST_DIR
make -j
examples/rdkafka_example -X builtin.features
make -C tests run_local_quick
make install
# Tar up the output directory
pushd $DEST_DIR
ldd lib/*.so.1
tar cvzf $OUT_TGZ .
popd # $DEST_DIR
popd # $BUILD_DIR
rm -rf "$BUILD_DIR"
|
#!/bin/sh
#
# mymnt.sh a semi-auto mount script
#
# Copyright (c) 1992-2011 Zhihao Yuan. All rights reserved.
# This file is distributed under the 2-clause BSD License.
: ${MNTBASE:="$HOME/mnt"}
OPTIONS=""
ALL=0
DEBUG=0
NAME="$(basename "$0")"
usage () {
echo "Usage: $NAME [OPTIONS] LABEL [NODE]"
echo " $NAME [SWITCHES]"
}
help () {
usage
echo -n "
LABEL: volume or device name under /dev/
NODE: alternative mount point under MNTBASE
OPTIONS:
-p path overwrite the default MNTBASE
-L locale overwrite the default LC_CTYPE
-o options file system specific options
-r disable locale
-D show mount command only
SWITCHES:
-a mount all devices
-l list available labels
-h show this help
"
}
error () {
echo "$NAME: $1" >&2
exit 1
}
warn () {
echo "warning: $1" >&2
return 1
}
issue () {
if [ "$DEBUG" -ne 0 ]; then
echo "$@"
else
"$@"
fi
}
mount_with () {
if [ ! -e "$node" ]; then
issue mkdir -p "$node" || exit 1
fi
if [ -z "$OPTIONS" ]; then
issue "$@" "$device" "$node"
else
issue "$@" -o "$OPTIONS" "$device" "$node"
fi
if [ $? -ne 0 ]; then
st=$?
issue rmdir -p "$node" 2> /dev/null
exit $st
fi
}
getgeom () {
name="$(echo "$1" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g')"
echo "$(glabel status -s | awk "{sub(/[^\/]*\//,\"\");split(\$0,a,/[[:space:]]*N\/A[[:space:]]*/);if(a[1]==\"$name\"||a[2]==\"$name\"){print a[2];exit}}")"
}
labelof () {
echo "$(glabel status -s "$1" | awk '{sub(/[^\/]*\//,"");split($0,a,/[[:space:]]*N\/A[[:space:]]+/);print a[1]}')"
}
fstypeof () {
echo "$(glabel status -s "$1" | cut -d/ -f1)"
}
mount_target () {
geom="$(getgeom "$1")"
if [ -z "$geom" ]; then
error "No such geom label: $1"
fi
fstype="$(fstypeof "$geom")"
label="$(labelof "$geom")"
device="/dev/$geom"
charmap="${LC_CTYPE:+"$(locale charmap)"}"
node="${2:-${MNTBASE}/$label}"
fmask="$(expr 666 - $(umask))"
dmask="$(expr 777 - $(umask))"
case "$fstype" in
ufs|ext2fs|xfs)
mount_with mount -t "$fstype"
;;
msdosfs)
if [ "$MNTCTYPE" -eq 0 ]; then
mount_with mount_$fstype -M "$dmask" -m "$fmask"
else
mount_with mount_$fstype -M "$dmask" -m "$fmask" -L "$LC_CTYPE"
fi
;;
ntfs)
if [ "$MNTCTYPE" -eq 0 ]; then
mount_with mount_$fstype -m "$dmask"
else
mount_with mount_$fstype -m "$dmask" -C "$charmap"
fi
;;
iso9660)
if [ "$MNTCTYPE" -eq 0 ]; then
mount_with mount_cd9660
else
mount_with mount_cd9660 -C "$charmap"
fi
;;
udf)
if [ "$MNTCTYPE" -eq 0 ]; then
mount_with mount_$fstype
else
mount_with mount_$fstype -C "$charmap"
fi
;;
*)
if [ "$ALL" -ne 1 ]; then
error "Unsupported file system: $fstype"
fi
;;
esac
}
# process options
while getopts 'p:L:o:raDlh' flag; do
case "$flag" in
p)
MNTBASE="${OPTARG%%/}" ;;
L)
LC_CTYPE="$OPTARG" ;;
o)
OPTIONS="$OPTARG" ;;
r)
MNTCTYPE=0 ;;
a)
ALL=1 ;;
D)
DEBUG=1 ;;
l)
glabel status -s | awk '{if(!match($0,/^[[:space:]]*gpt/)){sub(/[^\/]*\//,"");split($0,a,/[[:space:]]*N\/A[[:space:]]+/);print a[1]}}'
exit ;;
h)
help
exit ;;
*)
usage
echo "Try \`$NAME -h' for more information."
exit 2
esac
done
if ! kldstat -qm iconv; then # no kiconv
if [ -n "$MNTCTYPE" ] && [ "$MNTCTYPE" -ne 0 ]; then
warn "Locale support is disabled; check your kiconv availability"
fi
MNTCTYPE=0
else
: ${MNTCTYPE:=1}
fi
# if -a is specified, call itself recursively
if [ "$ALL" -eq 1 -a $# -eq $((OPTIND-1)) ]; then
glabel status -s | awk '{sub(/[^\/]*\//,"");split($0,a,/[[:space:]]*N\/A[[:space:]]*/);print a[2]}' | while read -r dev; do
"$0" "$@" "$dev"
done
exit
fi
shift $((OPTIND-1))
if [ $# -eq 0 ]; then
mount | while read -r ln; do
ls -d "$MNTBASE"/* 2> /dev/null | while read -r nd; do
if echo "$ln" | grep -wF "$nd"; then
break
fi
done
done
else
mount_target "$@"
fi
|
module Yt
module Models
class GroupInfo < Base
attr_reader :data
def initialize(options = {})
@data = options[:data]['snippet'].merge options[:data]['contentDetails']
@auth = options[:auth]
end
has_attribute :title, default: ''
has_attribute :item_count, type: Integer
has_attribute :published_at, type: Time
end
end
end |
<reponame>Mechap/ODFAEG<filename>ExtLib/Aurora/Examples/SimpleTest/SplashScreen.cpp
//
// Copyright (c) 2010-2011 <NAME> and <NAME>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#include "ISplashScreen.h"
#include "../../RuntimeObjectSystem/ObjectInterfacePerModule.h"
#include "../../RuntimeCompiler/IFileChangeNotifier.h"
#include "../../Systems/SystemTable.h"
#include "../../Systems/IEntitySystem.h"
#include "../../Systems/IAssetSystem.h"
#include "../../Systems/ILogSystem.h"
#include "../../RuntimeObjectSystem/ISimpleSerializer.h"
#include "../../Systems/IGUISystem.h"
#include "../../Systems/IGame.h"
#include "../../Systems/IAssetSystem.h"
#include <assert.h>
#include <stdio.h>
#include <algorithm>
class SplashScreen: public ISplashScreen, public IFileChangeListener, public IGUIEventListener
{
public:
SplashScreen()
: m_pSplashElement(0)
, m_pDocument(0)
, m_fMinViewTime(0.0f)
, m_fFadeInTime(0.0f)
, m_fFadeOutTime(0.0f)
, m_fTimeDisplayed(0.0f)
, m_fFadeOutStartTime(0.0f)
, m_bAutoClose(false)
, m_bCloseRequested(false)
, m_bReadyToClose(false)
{
}
virtual ~SplashScreen()
{
if( m_pEntity )
{
m_pEntity->SetUpdateable(NULL);
}
if ( m_pSplashElement )
{
m_pSplashElement->RemoveEventListener( "click", this );
m_pSplashElement->RemoveReference();
}
if ( m_pDocument )
{
if (!IsRuntimeDelete())
{
m_pDocument->Hide();
}
m_pDocument->RemoveReference();
}
}
// IEntityObject
virtual void Serialize(ISimpleSerializer *pSerializer)
{
AU_ASSERT(pSerializer);
IEntityObject::Serialize(pSerializer);
SERIALIZE(m_ImageFile);
SERIALIZE(m_fMinViewTime);
SERIALIZE(m_fFadeInTime);
SERIALIZE(m_fFadeOutTime);
SERIALIZE(m_fTimeDisplayed);
SERIALIZE(m_fFadeOutStartTime);
SERIALIZE(m_bAutoClose);
SERIALIZE(m_bCloseRequested);
SERIALIZE(m_bReadyToClose);
}
virtual void Init( bool isFirstInit )
{
m_pEntity->SetUpdateable( this );
InitWatch();
InitDocument(false);
if (!m_ImageFile.empty())
{
SetImage(m_ImageFile.c_str());
}
}
// ~IEntityObject
// IAUUpdateable
virtual void Update( float deltaTime )
{
if( !m_pSplashElement || !m_pDocument )
{
return;
}
if (!m_bReadyToClose)
{
m_pDocument->Show(); // HACK - recompiling with visible splashscreen seems to make it vanish for some reason
char buff[32];
// Check if window has re-szie and move splash screen
float currWindowSize[2];
PerModuleInterface::g_pSystemTable->pGame->GetWindowSize( currWindowSize[0], currWindowSize[1] );
if( currWindowSize[0] != m_WindowSize[0] || currWindowSize[1] != m_WindowSize[1] )
{
m_WindowSize[0] = currWindowSize[0];
m_WindowSize[1] = currWindowSize[1];
int left;
left = (int)( (m_WindowSize[0] - m_pSplashElement->GetClientWidth()) * 0.5f );
_snprintf_s(buff, sizeof(buff), _TRUNCATE, "%d",left);
m_pSplashElement->SetProperty("left", buff);
int top;
top = (int)( (m_WindowSize[1] - m_pSplashElement->GetClientHeight()) * 0.5f );
_snprintf_s(buff, sizeof(buff), _TRUNCATE, "%d",top);
m_pSplashElement->SetProperty("top", buff);
}
m_fTimeDisplayed += deltaTime;
if (m_fTimeDisplayed < m_fFadeInTime)
{
// Fade In
float t = m_fTimeDisplayed / m_fFadeInTime;
_snprintf_s( buff, sizeof(buff), _TRUNCATE, "rgba(255,255,255,%d)", (int)(255 * t) );
m_pSplashElement->SetProperty( "color", buff );
}
else if (m_fTimeDisplayed < (m_fFadeInTime + m_fMinViewTime) ||
(!m_bAutoClose && !m_bCloseRequested))
{
// Regular View
m_fFadeOutStartTime = m_fTimeDisplayed;
m_pSplashElement->SetProperty( "color", "rgba(255,255,255,255)" );
}
else if (m_fTimeDisplayed < (m_fFadeOutStartTime + m_fFadeOutTime))
{
// Fade Out
float t = (m_fFadeOutStartTime + m_fFadeOutTime - m_fTimeDisplayed) / m_fFadeOutTime;
_snprintf_s( buff, sizeof(buff),_TRUNCATE , "rgba(255,255,255,%d)", (int)(255 * t) );
m_pSplashElement->SetProperty( "color", buff );
}
else
{
m_bReadyToClose = true;
}
}
}
// ~IAUUpdateable
// IFileChangeListener
virtual void OnFileChange(const IAUDynArray<const char*>& filelist)
{
// Reload RML document and clear RCSS cache
InitDocument(true);
}
// ~IFileChangeListener
// IGUIEventListener
virtual void OnEvent( const IGUIEvent& event_info )
{
m_bCloseRequested = true;
}
// ~IGUIEventListener
// ISplashScreen
virtual void SetImage( const char* imageFile )
{
AU_ASSERT(imageFile);
m_ImageFile = imageFile;
if (m_pSplashElement)
{
m_pSplashElement->SetAttribute("src", imageFile);
// Position element correctly so that it is centered
PerModuleInterface::g_pSystemTable->pGame->GetWindowSize( m_WindowSize[0], m_WindowSize[1] );
char buff[16];
int left;
left = (int)( (m_WindowSize[0] - m_pSplashElement->GetClientWidth()) * 0.5f );
_snprintf_s(buff, sizeof(buff), _TRUNCATE, "%d",left);
m_pSplashElement->SetProperty("left", buff);
int top;
top = (int)( (m_WindowSize[1] - m_pSplashElement->GetClientHeight()) * 0.5f );
_snprintf_s(buff, sizeof(buff), _TRUNCATE, "%d",top);
m_pSplashElement->SetProperty("top", buff);
}
}
virtual void SetMinViewTime( float fSeconds )
{
m_fMinViewTime = std::max(0.0f, fSeconds);
}
virtual void SetFadeInTime( float fSeconds )
{
m_fFadeInTime = std::max(0.0f, fSeconds);
}
virtual void SetFadeOutTime( float fSeconds )
{
m_fFadeOutTime = std::max(0.0f, fSeconds);
}
virtual void SetAutoClose( bool bAutoClose )
{
m_bAutoClose = bAutoClose;
}
virtual bool ReadyToClose() const
{
return m_bReadyToClose;
}
// ~ISplashScreen
private:
void InitWatch()
{
IFileChangeNotifier* pFileChangeNotifier = PerModuleInterface::g_pSystemTable->pFileChangeNotifier;
// Set watches on the data files we rely on for drawing GUI
std::string path = PerModuleInterface::g_pSystemTable->pAssetSystem->GetAssetDirectory();
path += "/GUI/splashscreen.rml";
pFileChangeNotifier->Watch(path.c_str(), this);
path = PerModuleInterface::g_pSystemTable->pAssetSystem->GetAssetDirectory();
path += "/GUI/splashscreen.rcss";
pFileChangeNotifier->Watch(path.c_str(), this);
}
void InitDocument(bool forceLoad)
{
// may be serializing an already initialized object, ensure we handle reference
// counting correctly.
if (m_pSplashElement)
{
m_pSplashElement->RemoveEventListener( "click", this );
m_pSplashElement->RemoveReference();
m_pSplashElement = 0;
}
if (m_pDocument)
{
m_pDocument->RemoveReference();
m_pDocument = 0;
}
// Load and show the splashscreen
IGUISystem* pGUI = PerModuleInterface::g_pSystemTable->pGUISystem;
if (forceLoad)
{
// Clear style sheet cache so any changes to RCSS files will be applied
pGUI->ClearStyleSheetCache();
}
//Always load document in order to reset its state correctly
m_pDocument = pGUI->LoadDocument("/GUI/splashscreen.rml", "Splashscreen");
if (m_pDocument != NULL)
{
m_pDocument->Show();
m_pSplashElement = m_pDocument->Element()->GetElementById("splash");
m_pSplashElement->AddEventListener( "click", this );
}
}
// Private Members
IGUIElement* m_pSplashElement;
IGUIDocument* m_pDocument;
std::string m_ImageFile;
float m_fMinViewTime;
float m_fFadeInTime;
float m_fFadeOutTime;
float m_fTimeDisplayed;
float m_fFadeOutStartTime;
bool m_bAutoClose;
bool m_bCloseRequested;
bool m_bReadyToClose;
float m_WindowSize[2];
};
REGISTERCLASS(SplashScreen);
|
import React, { useState, useEffect } from 'react'
import * as JsSearch from 'js-search'
import { createClient } from 'contentful'
import SearchCard from '../components/SeachCard'
import Container from '../components/Container'
import styled from '@emotion/styled'
const Form = styled.form`
max-width: ${props => props.theme.sizes.maxWidthCentered};
margin: 0 auto;
display: flex;
flex-flow: row wrap;
justify-content: space-between;
align-items: flex-start;
input,
textarea {
font-family: inherit;
font-size: inherit;
background: ${props => props.theme.colors.tertiary};
color: ${props => props.theme.colors.text};
border-radius: 2px;
padding: 1em;
&::-webkit-input-placeholder {
color: gray;
}
&::-moz-placeholder {
color: gray;
}
&:-ms-input-placeholder {
color: gray;
}
&:-moz-placeholder {
color: gray;
}
&:required {
box-shadow: none;
}
}
&::before {
content: '';
background: black;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 1;
transition: 0.2s all;
opacity: ${props => (props.overlay ? '.8' : '0')};
visibility: ${props => (props.overlay ? 'visible' : 'hidden')};
}
`
const Search = styled.textarea`
margin: 0 0 1em 0;
width: 100%;
@media (min-width: ${props => props.theme.responsive.small}) {
width: 100%;
}
`
const SearchContainer = () => {
const [postData, setPostData] = useState({
posts: [],
foundPosts: [],
search: [],
searchResults: [],
isLoading: true,
isError: false,
searchQuery: ''
})
const {posts, search, searchResults, searchQuery, isLoading } = postData
const basePath = '/'
const spaceId = process.env.GATSBY_SPACE_ID
const accessToken = process.env.GATSBY_ACCESS_TOKEN
const client = createClient({
space: spaceId,
accessToken: accessToken
})
useEffect(() => {
client
.getEntries({
content_type: 'post',
order: 'sys.createdAt'
})
.then(
result => {
result.items.forEach((item, i) => { item.id = i.toString() })
setPostData({
isLoading: false,
posts: result.items
})
rebuildIndex()
},
error => {
setPostData({
isLoading: false,
error: error
})
}
)
}, [isLoading])
const rebuildIndex = () => {
const dataToSearch = new JsSearch.Search('id')
dataToSearch.indexStrategy = new JsSearch.PrefixIndexStrategy()
dataToSearch.sanitizer = new JsSearch.LowerCaseSanitizer()
dataToSearch.addIndex(['fields', 'title'])
dataToSearch.addDocuments(posts)
setPostData({
...postData,
search: dataToSearch,
isLoading: false
})
}
const searchData = e => {
const queryResult = search.search(e.target.value)
setPostData({
...postData,
searchQuery: e.target.value,
searchResults: e.target.value === '' ? posts : queryResult
})
}
const handleSubmit = e => e.preventDefault
return (
<div>
<Form onSubmit={e => handleSubmit(e)}>
<Search
id="Search"
value={searchQuery}
onChange={e => searchData(e)}
placeholder='Search for food by name'
/>
</Form>
<Container>
<ul>
{searchResults && searchResults.map((post) => (
<SearchCard key={post.sys.id} post={post} basePath={basePath} />
))}
</ul>
</Container>
</div>
)
}
export default SearchContainer |
import { BrandingColors, CdnUrls } from '#utils/constants';
import { parseBulbapediaURL } from '#utils/functions/pokemonParsers';
import type { Type, TypeMatchup, TypesEnum } from '@favware/graphql-pokemon';
import { PaginatedMessage } from '@sapphire/discord.js-utilities';
import { container } from '@sapphire/framework';
import { MessageEmbed } from 'discord.js';
export function typeMatchupResponseBuilder(types: TypesEnum[], typeMatchups: TypeMatchup) {
const externalResources = 'External Resources';
const externalSources = [
`[Bulbapedia](${parseBulbapediaURL(`https://bulbapedia.bulbagarden.net/wiki/${types[0]}_(type)`)} )`,
`[Serebii](https://www.serebii.net/pokedex-sm/${types[0].toLowerCase()}.shtml)`,
`[Smogon](http://www.smogon.com/dex/sm/types/${types[0]})`
].join(' | ');
return new PaginatedMessage({
template: new MessageEmbed()
.setColor(BrandingColors.Primary) //
.setAuthor({ name: `Type effectiveness for ${container.i18n.listAnd.format(types)}`, iconURL: CdnUrls.Pokedex }) //
})
.setSelectMenuOptions((pageIndex) => ({ label: ['Offensive', 'Defensive'][pageIndex - 1] }))
.addPageEmbed((embed) =>
embed
.addField(
'Offensive',
[
`Super effective against: ${parseEffectiveMatchup(typeMatchups.attacking.doubleEffectiveTypes, typeMatchups.attacking.effectiveTypes)}`,
'',
`Deals normal damage to: ${parseRegularMatchup(typeMatchups.attacking.normalTypes)}`,
'',
`Not very effective against: ${parseResistedMatchup(typeMatchups.attacking.doubleResistedTypes, typeMatchups.attacking.resistedTypes)}`,
'',
`${typeMatchups.attacking.effectlessTypes.length ? `Doesn't affect: ${parseRegularMatchup(typeMatchups.attacking.effectlessTypes)}` : ''}`
].join('\n')
)
.addField(externalResources, externalSources)
)
.addPageEmbed((embed) =>
embed
.addField(
'Defensive',
[
`Vulnerable to: ${parseEffectiveMatchup(typeMatchups.defending.doubleEffectiveTypes, typeMatchups.defending.effectiveTypes)}`,
'',
`Takes normal damage from: ${parseRegularMatchup(typeMatchups.defending.normalTypes)}`,
'',
`Resists: ${parseResistedMatchup(typeMatchups.defending.doubleResistedTypes, typeMatchups.defending.resistedTypes)}`,
'',
`${
typeMatchups.defending.effectlessTypes.length ? `Not affected by: ${parseRegularMatchup(typeMatchups.defending.effectlessTypes)}` : ''
}`
].join('\n')
)
.addField(externalResources, externalSources)
);
}
function parseEffectiveMatchup(doubleEffectiveTypes: Type['doubleEffectiveTypes'], effectiveTypes: Type['effectiveTypes']) {
return doubleEffectiveTypes
.map((type): string => `${type} (x4)`)
.concat(effectiveTypes.map((type) => `${type} (x2)`))
.map((type) => `\`${type}\``)
.join(', ');
}
function parseResistedMatchup(doubleResistedTypes: Type['doubleResistedTypes'], resistedTypes: Type['resistedTypes']) {
return doubleResistedTypes
.map((type): string => `${type} (x0.25)`)
.concat(resistedTypes.map((type) => `${type} (x0.5)`))
.map((type) => `\`${type}\``)
.join(', ');
}
function parseRegularMatchup(regularMatchup: Type['normalTypes'] | Type['effectlessTypes']) {
return regularMatchup.map((type) => `\`${type}\``).join(', ');
}
|
#!/bin/bash
dieharder -d 16 -g 28 -S 2059755283
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WebApi.Models;
namespace WebApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CommentController : ControllerBase
{
private readonly DatabaseContext _db;
public CommentController(DatabaseContext db)
{
_db = db;
}
[HttpGet]
[Route("{productId}")]
public IActionResult GetCommentsByProduct(int productId)
{
var comments = _db.Comments.Where(c => c.ProductId == productId).ToList();
return Ok(comments);
}
}
} |
// Copyright 2013 <NAME>
// 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 elastigo
import (
"bytes"
"compress/gzip"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/bmizerany/assert"
)
func TestQueryString(t *testing.T) {
// Test nil argument
s, err := Escape(nil)
assert.T(t, s == "" && err == nil, fmt.Sprintf("Nil should not fail and yield empty string"))
// Test single string argument
s, err = Escape(map[string]interface{}{"foo": "bar"})
exp := "foo=bar"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test single int argument
s, err = Escape(map[string]interface{}{"foo": int(1)})
exp = "foo=1"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test single int64 argument
s, err = Escape(map[string]interface{}{"foo": int64(1)})
exp = "foo=1"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test single int32 argument
s, err = Escape(map[string]interface{}{"foo": int32(1)})
exp = "foo=1"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test single float64 argument
s, err = Escape(map[string]interface{}{"foo": float64(3.141592)})
exp = "foo=3.141592"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test single float32 argument
s, err = Escape(map[string]interface{}{"foo": float32(3.141592)})
exp = "foo=3.141592"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test single []string argument
s, err = Escape(map[string]interface{}{"foo": []string{"bar", "baz"}})
exp = "foo=bar%2Cbaz"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test combination of all arguments
s, err = Escape(map[string]interface{}{
"foo": "bar",
"bar": 1,
"baz": 3.141592,
"test": []string{"a", "b"},
})
// url.Values also orders arguments alphabetically.
exp = "bar=1&baz=3.141592&foo=bar&test=a%2Cb"
assert.T(t, s == exp && err == nil, fmt.Sprintf("Expected %s, got: %s", exp, s))
// Test invalid datatype
s, err = Escape(map[string]interface{}{"foo": []int{}})
assert.T(t, err != nil, fmt.Sprintf("Expected err to not be nil"))
}
func TestDoResponseError(t *testing.T) {
v := make(map[string]string)
conn := NewConn()
req, _ := conn.NewRequest("GET", "http://mock.com", "")
req.Client = http.DefaultClient
defer func() {
req.Client.Transport = http.DefaultTransport
}()
// application/json
req.Client.Transport = newMockTransport(500, "application/json", `{"error":"internal_server_error"}`)
res, bodyBytes, err := req.DoResponse(&v)
assert.NotEqual(t, nil, res)
assert.Equal(t, nil, err)
assert.Equal(t, 500, res.StatusCode)
assert.Equal(t, "application/json", res.Header.Get("Content-Type"))
assert.Equal(t, "internal_server_error", v["error"])
assert.Equal(t, []byte(`{"error":"internal_server_error"}`), bodyBytes)
// text/html
v = make(map[string]string)
req.Client.Transport = newMockTransport(500, "text/html", "HTTP 500 Internal Server Error")
res, bodyBytes, err = req.DoResponse(&v)
assert.T(t, res == nil, fmt.Sprintf("Expected nil, got: %v", res))
assert.NotEqual(t, nil, err)
assert.Equal(t, 0, len(v))
assert.Equal(t, []byte("HTTP 500 Internal Server Error"), bodyBytes)
assert.Equal(t, fmt.Errorf(http.StatusText(500)), err)
// mime error
v = make(map[string]string)
req.Client.Transport = newMockTransport(500, "", "HTTP 500 Internal Server Error")
res, bodyBytes, err = req.DoResponse(&v)
assert.T(t, res == nil, fmt.Sprintf("Expected nil, got: %v", res))
assert.NotEqual(t, nil, err)
assert.Equal(t, 0, len(v))
assert.Equal(t, []byte("HTTP 500 Internal Server Error"), bodyBytes)
assert.NotEqual(t, fmt.Errorf(http.StatusText(500)), err)
}
type mockTransport struct {
statusCode int
contentType string
body string
}
func newMockTransport(statusCode int, contentType, body string) http.RoundTripper {
return &mockTransport{
statusCode: statusCode,
contentType: contentType,
body: body,
}
}
func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
response := &http.Response{
Header: make(http.Header),
Request: req,
StatusCode: t.statusCode,
}
response.Header.Set("Content-Type", t.contentType)
response.Body = ioutil.NopCloser(strings.NewReader(t.body))
return response, nil
}
func TestSetBodyGzip(t *testing.T) {
s := "foo"
// test []byte
expB := []byte(s)
actB, err := gzipHelper(t, expB)
assert.T(t, err == nil, fmt.Sprintf("Expected err to be nil"))
assert.T(t, bytes.Compare(actB, expB) == 0, fmt.Sprintf("Expected: %s, got: %s", expB, actB))
// test string
expS := s
actS, err := gzipHelper(t, expS)
assert.T(t, err == nil, fmt.Sprintf("Expected err to be nil"))
assert.T(t, string(actS) == expS, fmt.Sprintf("Expected: %s, got: %s", expS, actS))
// test io.Reader
expR := strings.NewReader(s)
actR, err := gzipHelper(t, expR)
assert.T(t, err == nil, fmt.Sprintf("Expected err to be nil"))
assert.T(t, bytes.Compare([]byte(s), actR) == 0, fmt.Sprintf("Expected: %s, got: %s", s, actR))
// test other
expO := testStruct{Name: "Travis"}
actO, err := gzipHelper(t, expO)
assert.T(t, err == nil, fmt.Sprintf("Expected err to not be nil"))
assert.T(t, bytes.Compare([]byte(`{"name":"Travis"}`), actO) == 0, fmt.Sprintf("Expected: %s, got: %s", s, actO))
}
type testStruct struct {
Name string `json:"name"`
}
func gzipHelper(t *testing.T, data interface{}) ([]byte, error) {
r, err := http.NewRequest("GET", "http://google.com", nil)
if err != nil {
return nil, err
}
// test string
req := &Request{
Request: r,
}
err = req.SetBodyGzip(data)
if err != nil {
return nil, err
}
gr, err := gzip.NewReader(req.Body)
if err != nil {
return nil, err
}
return ioutil.ReadAll(gr)
}
|
#!/bin/bash
#BSD 3-Clause License
#
#Copyright (c) 2018, xmrminer01102018
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#* Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
#* Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
#* Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Install Ubuntu MATE Linux OS 18.04.1 LTS.
# URL: https://ubuntu-mate.org/ (Only tested version)
# Set up ssh and root user
# $ sudo su -
# [sudo] password for user jdoe: ******** <-- Enter your jdoe's password
# passwd
# Enter new UNIX password: ******** <-- Enter your root's password here
# Retype new UNIX password: ******** <-- Confirm your root's password here
# passwd: password updated successfully
# exit
# logout
# $ su -
# Password: ******** <-- Enter your root's password that you have created above
# Download amdgpu-pro drivers and put them in /root/Downloads
#
# amdgpu-pro-18.30-633530.tar.xz for Ubuntu 18.04.1
# or
# amdgpu-pro-18.30-641594.tar.xz for Ubuntu 18.04.1
# URL: https://www2.ati.com/drivers/
# amdgpu-pro-18.10-572953.tar.xz for Ubuntu 16.04.4
# URL: https://support.amd.com/en-us/kb-articles/Pages/Radeon-Software-for-Linux-18.10-Release-Notes.aspx
# Make sure that network has been configured and connected.
# Download a zip file from GitHub.
# cd
# unzip VegaToolsNConfigs-master.zip
# mv VegaToolsNConfigs-master VegaToolsNConfigs
# mv VegaToolsNConfigs /root/
# If you clone the VegaToolsNConfigs, move the directory to /root/.
# Move all the files from config, tools and PPTDIR folders to VegaToolsNConfigs folder.
# cd VegaToolsNConfigs
# mv config/* .
# mv tools/* .
# mv PPTDIR/* .
# Make the scripts are runnable.
# chmod 770 *.sh
# Now run this script as root by typing cd /root/VegaToolsNConfigs; ./autoConfigure.sh
# Put the driver version that you have, as the last DRIVER_TO_RUN without .tar.xz
# In this case it is amdgpu-pro-18.30-641594
DRIVER_TO_RUN="amdgpu-pro-18.30-633530"
DRIVER_TO_RUN="amdgpu-pro-18.30-641594"
ECHO=/bin/echo
SCRIPT=/usr/bin/script
APTGET=/usr/bin/apt-get
REBOOT=/sbin/reboot
GIT=/usr/bin/git
CAT=/bin/cat
PWD=/bin/pwd
FIND=/usr/bin/find
GREP=/bin/grep
TAIL=/usr/bin/tail
DIRNAME=/usr/bin/dirname
CRONTAB=/usr/bin/crontab
SENSORSDETECT=/usr/sbin/sensors-detect
TAR=/bin/tar
WHICH=/usr/bin/which
MV=/bin/mv
LN=/bin/ln
MKDIR=/bin/mkdir
MAKE=/usr/bin/make
CP=/bin/cp
SLEEP=/bin/sleep
SED=/bin/sed
AWK=/usr/bin/awk
EGREP=/bin/egrep
PS=/bin/ps
KILL=/bin/kill
PERL=/usr/bin/perl
UPDATEGRUB=/usr/sbin/update-grub
POWEROFF=/sbin/poweroff
FNDNAME=$( ${FIND} /root -name "autoConfigure.sh" | ${GREP} Configure | ${TAIL} -n 1 )
STAGE=""
if [ -e /root/stagefile ]
then
STAGE=$( ${CAT} /root/stagefile )
else
${ECHO} "STAGE2" > /root/stagefile
STAGE="STAGE1"
fi
if [[ "$STAGE" == "STAGE1" ]]
then
cd
${ECHO} "Setting up stage 1"
(
${ECHO} "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
${ECHO} "@reboot ${FNDNAME}"
) | ${CRONTAB} -u root -
${ECHO} "crontab modified..."
${APTGET} update
${ECHO} "apt-get updated..."
${APTGET} install -y openssh-server
${ECHO} "ssh server installed..."
${ECHO} "PermitRootLogin yes" >> /etc/ssh/sshd_config
${ECHO} "sshd_config updated..."
${ECHO} "vm.nr_hugepages = 128" >> /etc/sysctl.conf
${ECHO} "sysctl.conf updated..."
${ECHO} "rebooting..."
${REBOOT}
fi
if [[ "$STAGE" == "STAGE2" ]]
then
${ECHO} "STAGE3" > /root/stagefile
cd
${ECHO} "Setting up stage 2"
${APTGET} update
${ECHO} "apt-get updated..."
${APTGET} install -y lm-sensors
${ECHO} "lm-sensors installed..."
${SENSORSDETECT} --auto
${ECHO} "Done sensors-detect..."
cd /root/Downloads
${TAR} -Jxvf amdgpu-pro-18.10-572953.tar.xz
${ECHO} "Done tar amdgpu-pro-18.10-572953.tar.xz..."
cd amdgpu-pro-18.10-572953
${ECHO} "Installing amdgpu-pro-18.10-572953.tar.xz..."
./amdgpu-pro-install -y --opencl=pal
${ECHO} "Done installing amdgpu-pro-18.10-572953.tar.xz..."
${ECHO} "rebooting..."
${REBOOT}
fi
if [[ "$STAGE" == "STAGE3" ]]
then
${ECHO} "STAGE4" > /root/stagefile
cd
${ECHO} "Setting up stage 3"
${APTGET} update
${ECHO} "apt-get updated..."
${APTGET} install -y git libuv1-dev libmicrohttpd-dev libssl-dev cmake build-essential libhwloc-dev opencl-headers
${ECHO} "Tools installed..."
cd; ${MKDIR} git
cd git
GIT=$( ${WHICH} git )
CMAKE=$( ${WHICH} cmake )
${ECHO} "Cloning already modified xmrig-amd for Ubuntu..."
${GIT} clone https://github.com/xmrminer01102018/xmrig-amd.git
cd xmrig-amd
cd src/3rdparty
${MV} CL CL_original
${LN} -s /usr/include/CL CL
cd /root/git/xmrig-amd/
${ECHO} "Compiling xmrig-amd for Ubuntu..."
${MKDIR} build; cd build; ${CMAKE} ..; ${MAKE}
CdJ=$( ${FIND} /root -name "config.json" | ${GREP} config | ${TAIL} -n 1 )
${CP} ${CdJ} .
XMRIGAMD=$( ${FIND} /root -name "startXmrigAmd.sh" | ${GREP} startXmrigAmd | ${TAIL} -n 1 )
${ECHO} "Running xmrig-amd test run..."
( ${XMRIGAMD} & )
${ECHO} "Pausing for 100 seconds to get hash rates..."
${SLEEP} 100
HASHLOG=/root/hashrate
if [ -e ${HASHLOG} ]
then
${ECHO} "Getting hash rate..."
HR=$( ${CAT} ${HASHLOG} | ${GREP} speed | ${TAIL} -n 1 | ${SED} 's/\x1B\[[0-9;]*[JKmsu]//g' | ${AWK} '{print $5}' | ${AWK} -F'.' '{print $1}' )
else
${ECHO} "Hash log does not exist"
fi
${ECHO} "Hash rate is ${HR}."
${ECHO} "Killing xmrig-amd process..."
PSR=$( ${PS} -aef | ${GREP} xmr | ${GREP} -v ${GREP} )
${ECHO} "${PSR}"
PSN=$( ${PS} -aef | ${GREP} xmr | ${GREP} -v ${GREP} | ${AWK} '{print $2}' )
${ECHO} "PSN: ${PSN}"
STATUS=$( ${KILL} -9 ${PSN} )
REGEX='^[0-9]+$'
if [[ ${HR} =~ ${REGEX} ]] ; then
${ECHO} "Initial slow hash rate ${HR}."
/usr/bin/amdgpu-pro-uninstall -y
else
${ECHO} "Something wrong with xmrig-amd program."
${ECHO} "STAGEHASHRATECHECK" > /root/stagefile
${ECHO} "Rebooting..."
${REBOOT}
fi
${ECHO} "rebooting..."
${REBOOT}
fi
if [[ "$STAGE" == "STAGEHASHRATECHECK" ]]
then
${ECHO} "STAGE4" > /root/stagefile
${ECHO} "Re-running xmrig-amd again..."
XMRIGAMD=$( ${FIND} /root -name "startXmrigAmd.sh" | ${GREP} startXmrigAmd | ${TAIL} -n 1 )
${ECHO} "Running xmrig-amd test run..."
( ${XMRIGAMD} & )
${ECHO} "Pausing for 100 seconds to get hash rates..."
${SLEEP} 100
HASHLOG=/root/hashrate
if [ -e ${HASHLOG} ]
then
${ECHO} "Getting hash rate..."
HR=$( ${CAT} ${HASHLOG} | ${GREP} speed | ${TAIL} -n 1 | ${SED} 's/\x1B\[[0-9;]*[JKmsu]//g' | ${AWK} '{print $5}' | ${AWK} -F'.' '{print $1}' )
else
${ECHO} "Hash log does not exist"
fi
${ECHO} "Hash rate is ${HR}."
${ECHO} "Killing xmrig-amd process..."
PSR=$( ${PS} -aef | ${GREP} xmr | ${GREP} -v ${GREP} )
${ECHO} "${PSR}"
PSN=$( ${PS} -aef | ${GREP} xmr | ${GREP} -v ${GREP} | ${AWK} '{print $2}' )
${ECHO} "PSN: ${PSN}"
STATUS=$( ${KILL} -9 ${PSN} )
REGEX='^[0-9]+$'
if [[ ${HR} =~ ${REGEX} ]] ; then
${ECHO} "Initial slow hash rate ${HR}."
/usr/bin/amdgpu-pro-uninstall -y
else
${ECHO} "Something wrong with xmrig-amd program."
${ECHO} "STOP" > /root/stagefile
${ECHO} "Exiting..."
exit
fi
${ECHO} "rebooting..."
${REBOOT}
fi
if [[ "$STAGE" == "STAGE4" ]]
then
${ECHO} "STAGE4PROCESSING..." > /root/stagefile
cd
${ECHO} "Setting up stage 4"
${APTGET} update
${ECHO} "apt-get updated..."
cd /root/Downloads
${TAR} -Jxvf ${DRIVER_TO_RUN}.tar.xz
${ECHO} "Done tar ${DRIVER_TO_RUN}.tar.xz..."
cd ${DRIVER_TO_RUN}
${ECHO} "Installing ${DRIVER_TO_RUN}.tar.xz..."
./amdgpu-pro-install -y --opencl=pal
${ECHO} "Done installing ${DRIVER_TO_RUN}.tar.xz..."
cd /etc/default
${MV} grub grub.original
${CP} grub.original grub
${PERL} -i.bak -npe 's/quiet splash/quiet splash amdgpu.ppfeaturemask=0xffffffff/g' grub
RESULT=$( ${CAT} grub | ${GREP} amdgpu )
${ECHO} "grep result is ${RESULT}."
${UPDATEGRUB}
${ECHO} "Done with updating grub..."
# Cleanup auto script
(
${ECHO} ""
) | ${CRONTAB} -u root -
${ECHO} "Powering off to add GPUs..."
${ECHO} "MINER_INSTALL_SUCCESSFUL" > /root/stagefile
${POWEROFF}
fi
|
export default class EntityError extends Error {
constructor(...args) {
super(...args);
this.code = args[1];
Error.captureStackTrace(this, EntityError);
}
}
|
#!/bin/bash
dieharder -d 201 -g 20 -S 1738973716
|
<gh_stars>1-10
package ExerciciosExtras.exercicios.vendas;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import ExerciciosExtras.exercicios.vendas.implementacoes.Nome;
public class Funcionario extends Usuario implements Nome {
private double salario;
private String banco;
private Date dtAdmissao = new Date();
private List<Venda> vendas = new ArrayList<>();
public Funcionario() {
}
public Funcionario(String userName, String password, String nome, double salario, String banco) {
super(userName, password, nome);
this.salario = salario;
this.banco = banco;
}
public double getSalario() {
return this.salario;
}
public void setSalario(double salario) {
this.salario = salario;
}
public String getBanco() {
return this.banco;
}
public void setBanco(String banco) {
this.banco = banco;
}
public Date getDtAdmissao() {
return this.dtAdmissao;
}
public void setDtAdmissao(Date dtAdmissao) {
this.dtAdmissao = dtAdmissao;
}
public void adicionarVenda(Venda venda){
this.vendas.add(venda);
}
public void qtdCompras() {
System.out.print("Nome: " + this.getNome()+ " ");
System.out.print("Tempo de Contrato: " + tempoContrato() + " ");
System.out.print("Quantidade de Vendas: " + qtdVendas() + "\n");
}
private long tempoContrato() {
return Math.abs(new Date().getTime() - this.dtAdmissao.getTime());
}
private int qtdVendas() {
return this.vendas.size();
}
@Override
public String getNome(){
return super.getNome();
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Funcionario)) {
return false;
}
Funcionario funcionario = (Funcionario) o;
return salario == funcionario.salario && Objects.equals(banco, funcionario.banco) && Objects.equals(dtAdmissao, funcionario.dtAdmissao);
}
@Override
public int hashCode() {
return Objects.hash(salario, banco, dtAdmissao);
}
@Override
public String toString() {
return "Nome: " + getNome();
}
} |
#!/bin/bash
#
for ((i=0; i<=500; i++)); do
python marvin.py >>log/marvin.log 2>&1
sleep 1
done
echo "Exceeded loop count" >>log/marvin.log
exit 1
|
import tensorflow as tf
# Load MNIST dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Neural network model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
# Compile and fit the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10)
# Evaluate the model
model.evaluate(x_test, y_test) |
package com.davidpdev.mygdxtest.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.davidpdev.mygdxtest.MyGdxTest;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width=800;
config.height=800;
new LwjglApplication(new MyGdxTest(), config);
}
}
|
# Script to setup new pi disc image with HappyBrackets and appropriate details
# run from pi, with an internet connection
cd
#Let user decide which JVMs to install
# keep apt-get up to date with mirrors
sudo apt-get -y update
# install zeroconf
sudo apt-get -y --force-yes install libnss-mdns
sudo apt-get -y --force-yes install netatalk
# install i2c tools
sudo apt-get -y --force-yes install i2c-tools
# install java 8
echo "Install Oracle"
sudo apt-get -y --force-yes install oracle-java8-jdk
#install Soft MIDI
sudo apt-get -y --force-yes install amsynth
#we need to installk wiringPI becasue it is not in STretch Lite - Needed for GPIO access
sudo apt-get -y --force-yes install wiringpi
# Enable I2C on raspi, to connect to sensors.
# Counter-intuitively 'do_i2c 0' means 'enable'.
sudo raspi-config nonint do_i2c 0
# get the happybrackets zipped project folder
# get latest filename
FILENAME=$(curl http://www.happybrackets.net/downloads/happy-brackets-runtime.php?version)
echo $FILENAME
curl -O http://www.happybrackets.net/downloads/$FILENAME
unzip $FILENAME
rm $FILENAME
# TODO setup audio if necessary.
# set audio output to max volume, well not quite max but close
amixer cset numid=1 0
# save audio settings
sudo alsactl store
# set up ssh login
sudo update-rc.d ssh enable
sudo invoke-rc.d ssh start
# now we need to see if we are going to start HappyBrackets from rc.local or from GUI Startup
#we should be back to PI user
GUI_FILE=~/.config/lxsession/LXDE-pi/autostart
if [ -f "$GUI_FILE" ]; then
echo "This PI is a GUI Program. We need to append our startup script to it"
START_TEXT="@/usr/bin/sudo /home/pi/HappyBrackets/scripts/run.sh"
#we need to add this startup text to GUI init file
#first see if it exists
if grep -Fxq "$START_TEXT" "$GUI_FILE"
then
# code if found
echo "Startup text already in GUI file";
else
# code if not found
echo "Append startup text to file"
echo $START_TEXT >>$GUI_FILE
fi
else # this is a standard non-gui PI
echo "This is a non gui PI. Add line to /etc/rc.local"
START_TEXT="/usr/bin/sudo /home/pi/HappyBrackets/scripts/run.sh"
RC_FILE=/etc/rc.local
#we need to add this startup text to GUI init file
#first see if it exists
if grep -Fxq "$START_TEXT" $RC_FILE
then
# code if found
echo "Startup text already in RC file";
else
# code if not found
# set up autorun
sudo wget --no-check-certificate -N https://raw.githubusercontent.com/orsjb/HappyBrackets/master/DeviceSetup/rc.local
sudo mv rc.local /etc/
sudo chmod +x /etc/rc.local
fi
fi
# Network Settings
echo "***********************************"
echo "-----------------------------------"
echo "***********************************"
echo "Do you want to alter your WiFi network settings so your Pi automatically connects to 'PINet'?"
echo "If you are currently connected on a working WiFi network you probably don't want to change the network settings."
echo "If you are connected directly or over ethernet, you can change the network settings to connect to a particular wifi network."
echo "if you do wish to change the network settings so that your Pi is setup to automatically connect then do the following commands:"
echo ""
echo "NOTE: Do not run these commands on a normal laptop or computer, only on a Raspberry Pi."
echo ""
echo "wget --no-check-certificate -N https://raw.githubusercontent.com/orsjb/HappyBrackets/master/DeviceSetup/wpa_supplicant.conf"
echo "sudo cp /etc/wpa_supplicant/wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf"
echo "sudo mv wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf"
echo ""
echo "If you make this change, the SSID this PI will search for will be 'PINet'"
echo "Password is 'happybrackets'"
|
<gh_stars>1-10
from rest_framework import serializers
from tempBerry.smarthome.models import Room, SmartHome, Sensor, AbstractDataEntry
class AbstractDataEntrySerializer(serializers.Serializer):
id = serializers.IntegerField()
source = serializers.CharField()
created_at = serializers.DateTimeField()
class SensorSerializer(serializers.ModelSerializer):
"""
Serializer for Sensors
"""
live_data = serializers.SerializerMethodField()
class Meta:
model = Sensor
fields = (
'id', 'name', 'created_at', 'last_updated_at', 'comment', 'public', 'type', 'live_data',
)
def get_live_data(self, obj):
if not hasattr(obj, 'live_data') or not obj.live_data:
return None
from tempBerry.temperatures.models import TemperatureDataEntry
from tempBerry.binarySensor.models import BinarySensorData
from tempBerry.temperatures.rest.serializers import TemperatureDataEntrySerializer
from tempBerry.binarySensor.rest.serializers import BinarySensorDataSerializer
# Convert into appropriate format
if isinstance(obj.live_data, TemperatureDataEntry):
return TemperatureDataEntrySerializer(obj.live_data).data
elif isinstance(obj.live_data, BinarySensorData):
return BinarySensorDataSerializer(obj.live_data).data
else:
return AbstractDataEntrySerializer(obj.live_data).data
class RoomSerializer(serializers.ModelSerializer):
"""
Serializer for rooms
"""
sensors = SensorSerializer(many=True)
class Meta:
model = Room
fields = ('id', 'name', 'comment', 'created_at', 'public', 'sensors',
'has_temperature', 'has_humidity', 'has_air_pressure')
read_only_fields = ('created_at', )
class MinimalisticSmartHomeSerializer(serializers.Serializer):
"""
Minimalistic Serializer for SmartHome
"""
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(read_only=True)
description = serializers.CharField(read_only=True)
|
namespace Platform::Setters
{
template <typename ...> class Setter;
template <typename TResult, typename TDecision> class Setter<TResult, TDecision> : public SetterBase<TResult>
{
private: TDecision _trueValue = 0;
private: TDecision _falseValue = 0;
public: Setter(TDecision trueValue, TDecision falseValue, TResult defaultValue)
{
_trueValue = trueValue;
_falseValue = falseValue;
}
public: Setter(TDecision trueValue, TDecision falseValue) : Setter(trueValue, falseValue, 0) { }
public: Setter(TResult defaultValue) { }
public: Setter() { }
public: TDecision SetAndReturnTrue(TResult value)
{
TResult _result = value;
return _trueValue;
}
public: TDecision SetAndReturnFalse(TResult value)
{
TResult _result = value;
return _falseValue;
}
public: TDecision SetFirstAndReturnTrue(Platform::Interfaces::IList<TResult> auto list)
{
TResult _result = list[0];
return _trueValue;
}
public: TDecision SetFirstAndReturnFalse(Platform::Interfaces::IList<TResult> auto list)
{
TResult _result = list[0];
return _falseValue;
}
};
}
|
<gh_stars>0
/*
* Copyright 2013 The Android Open Source Project
*
* 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.example.android.basicandroidkeystore;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;
import android.text.Html;
import android.widget.TextView;
import android.view.Menu;
import android.widget.Toast;
import com.example.android.common.activities.SampleActivityBase;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogFragment;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;
/**
* A simple launcher activity containing a summary sample description
* and a few action bar buttons.
*/
public class MainActivity extends SampleActivityBase {
public static final String TAG = "MainActivity";
public static final String FRAGTAG = "BasicAndroidKeyStoreFragment";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView sampleOutput = (TextView) findViewById(R.id.sample_output);
sampleOutput.setText(Html.fromHtml(getString(R.string.intro_message)));
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
BasicAndroidKeyStoreFragment fragment = new BasicAndroidKeyStoreFragment();
transaction.add(fragment, FRAGTAG);
transaction.commit();
handlePermissions();
}
private void handlePermissions() {
final Context context = this;
if (ContextCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.USE_FINGERPRINT)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setMessage("Write permission is necessary to use this application");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.USE_FINGERPRINT}, 1);
}
});
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.USE_FINGERPRINT}, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Create a chain of targets that will receive log data */
@Override
public void initializeLogging() {
// Wraps Android's native log framework.
LogWrapper logWrapper = new LogWrapper();
// Using Log, front-end to the logging chain, emulates android.util.log method signatures.
Log.setLogNode(logWrapper);
// Filter strips out everything except the message text.
MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
logWrapper.setNext(msgFilter);
// On screen logging via a fragment with a TextView.
LogFragment logFragment = (LogFragment) getSupportFragmentManager()
.findFragmentById(R.id.log_fragment);
msgFilter.setNext(logFragment.getLogView());
logFragment.getLogView().setTextAppearance(this, R.style.Log);
logFragment.getLogView().setBackgroundColor(Color.WHITE);
Log.i(TAG, "Ready");
}
}
|
<gh_stars>1-10
package com.sensorsdata.analytics.android.plugin;
import com.sun.source.util.Trees;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeTranslator;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
@SuppressWarnings({"unused", "FieldCanBeLocal"})
public class SensorsAnalyticsTreeTranslator extends TreeTranslator {
private Trees trees;
private TreeMaker make;
private Name.Table names;
private Messager messager;
SensorsAnalyticsTreeTranslator(ProcessingEnvironment env) {
messager = env.getMessager();
trees = Trees.instance(env);
Context context = ((JavacProcessingEnvironment)
env).getContext();
make = TreeMaker.instance(context);
names = Names.instance(context).table;
}
private void log(String message) {
messager.printMessage(Diagnostic.Kind.NOTE, message);
}
@Override
public void visitClassDef(JCTree.JCClassDecl jcClassDecl) {
super.visitClassDef(jcClassDecl);
}
private void insertTrackCode(JCTree.JCMethodDecl jcMethodDecl, int paramsCount, SensorsAnalyticsInsertLocation sensorsAnalyticsInsertLocation) {
JCTree.JCExpression sdkExpression = make.Ident(names.fromString("com"));
sdkExpression = make.Select(sdkExpression, names.fromString("sensorsdata"));
sdkExpression = make.Select(sdkExpression, names.fromString("analytics"));
sdkExpression = make.Select(sdkExpression, names.fromString("android"));
sdkExpression = make.Select(sdkExpression, names.fromString("sdk"));
sdkExpression = make.Select(sdkExpression, names.fromString("SensorsDataAutoTrackHelper"));
sdkExpression = make.Select(sdkExpression, names.fromString("trackViewOnClick"));
List<JCTree.JCExpression> paramsList = List.nil();
for (int i = 0; i < paramsCount; i++) {
paramsList = paramsList.append(make.Ident(jcMethodDecl.getParameters().get(i).name));
}
JCTree.JCStatement statement = make.Exec(
make.Apply(List.<JCTree.JCExpression>nil(),
sdkExpression,
paramsList
)
);
if (sensorsAnalyticsInsertLocation == SensorsAnalyticsInsertLocation.AFTER) {
jcMethodDecl.body.stats = jcMethodDecl.body.stats.appendList(List.of(statement));
} else {
jcMethodDecl.body.stats = jcMethodDecl.body.stats.prependList(List.of(statement));
}
}
@Override
public void visitMethodDef(JCTree.JCMethodDecl jcMethodDecl) {
super.visitMethodDef(jcMethodDecl);
try {
List<JCTree.JCAnnotation> annotationList = jcMethodDecl.getModifiers().annotations;
if (annotationList.toString().startsWith("@OnClick") ||
annotationList.toString().contains("@SensorsDataTrackViewOnClick()")) {
insertTrackCode(jcMethodDecl, 1, SensorsAnalyticsInsertLocation.AFTER);
return;
}
SensorsAnalyticsMethodCell methodCell = SensorsAnalyticsConfig.isMatched(jcMethodDecl);
if (methodCell != null) {
insertTrackCode(jcMethodDecl, methodCell.getParamsType().size(), methodCell.getInsertLocation());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
import { RouteMatch } from "../types/route_match";
import { HTTP_METHOD } from "../enums";
export declare function parseAndMatchRoute(url: string, httpMethod: HTTP_METHOD): RouteMatch;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.