content
stringlengths 7
2.61M
|
---|
<gh_stars>0
package software.jevera.service.product;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;
import software.jevera.domain.Bid;
import software.jevera.domain.Product;
@Component
public class StateMachine {
private final Map<ProductStateEnum, ProductState> states = new ConcurrentHashMap<>();
public StateMachine(List<ProductState> productStatus) {
productStatus.forEach(status -> states.put(status.getStatusName(), status));
}
private ProductState getState(Product product) {
return states.get(product.getStatus());
}
public void publish(Product product) {
getState(product).publish(product);
}
public void delete(Product product) {
getState(product).delete(product);
}
public void finish(Product product) {
getState(product).delete(product);
}
public void addBid(Product product, Bid bid) {
getState(product).addBid(product, bid);
}
}
|
// import React, { Component, HTMLAttributes } from 'react'
// import classNames from 'classnames'
// import moment from 'moment'
// import Card, { CardBody } from '../Card'
// import Listing, { ListingScroll } from '../Listing'
// import { Book, BookChapter, BookPage, BookStatus } from '../../../classes/Book'
// import { SourceManager } from '../../../classes/Source'
// import './Reader.scss'
// interface Props extends Pick<HTMLAttributes<HTMLDivElement>, 'style' | 'className'> {
// }
// interface ReaderModuleProps {
// sourceIndex: string;
// book?: Book;
// isLoading?: boolean;
// onBack?: () => void;
// }
// interface ReaderModuleState extends Book {
// // coverOpacity: number;
// navigationHeight: number;
// activeChapter?: BookChapter;
// activeChapterPages: BookPage[];
// activePage?: BookPage;
// chapterLoading: boolean;
// }
// export default class ReaderModule extends Component<ReaderModuleProps & Props, ReaderModuleState> {
// static DEFAULT_COVER_SIZE: number = 100;
// cacheChapterPages: { [key: string]: BookPage[] };
// constructor(props: Readonly<ReaderModuleProps & Props>){
// super(props);
// this.cacheChapterPages = {};
// this.state = {
// author: [],
// chapters: [],
// description: '',
// cover: '',
// genre: [],
// relased: '',
// title: '',
// title_alt: [],
// type: '',
// index: '',
// status: BookStatus.UNDEFINED,
// // coverOpacity: 1,
// navigationHeight: 0,
// activeChapter: undefined,
// activeChapterPages: [],
// activePage: undefined,
// chapterLoading: false,
// }
// }
// getActiveChapterPage = async (chapterIndex: string) => {
// let data = this.cacheChapterPages[chapterIndex];
// if (!!data) {
// return data;
// }
// else {
// const sourceIndex = this.props.sourceIndex;
// const bookIndex = this.state.index;
// if (!sourceIndex || !bookIndex || !chapterIndex) return [];
// var result = await SourceManager.getChapter(sourceIndex, bookIndex, chapterIndex);
// if (!result) return [];
// result.forEach(data => {
// var img = new Image();
// img.src = `${data.url}`;
// });
// this.cacheChapterPages[chapterIndex] = result;
// return result;
// }
// }
// componentDidMount() {
// const navigationHeight = document.getElementById('reader-navigation')?.clientHeight || 0;
// this.setState({ navigationHeight, ...(this.props.book as unknown as Book) });
// }
// componentDidUpdate(prevProps: ReaderModuleProps) {
// if (prevProps.book?.index !== this.props.book?.index) {
// this.setState({ ...this.state, ...(this.props.book) })
// }
// }
// changeChapter = (chapterIndex: string) => {
// this.setState({ chapterLoading: true });
// var chapter = this.state.chapters.find(e=>e.index === chapterIndex);
// this.setState({ activeChapter: chapter, activePage: undefined }, async () => {
// var pages = await this.getActiveChapterPage(chapterIndex);
// this.setState({
// activeChapterPages: pages,
// chapterLoading: !(true && (this.state.activeChapter && this.state.activeChapter.index === chapterIndex))
// });
// });
// }
// changeChapterPage = (activePage: BookPage) => {
// this.setState({ activePage });
// }
// closeChapter = () => {
// this.setState({ activeChapter: undefined, activePage: undefined });
// }
// // onChapterScroll = (event: React.UIEvent<HTMLDivElement, UIEvent>) => {
// // const data = event.currentTarget;
// // if (data.scrollTop <= ReaderModule.DEFAULT_COVER_SIZE) {
// // this.setState({ coverOpacity: 1 - (data.scrollTop / ReaderModule.DEFAULT_COVER_SIZE) });
// // }
// // else {
// // this.setState({ coverOpacity: 0 });
// // }
// // }
// render() {
// const { className, style } = this.props;
// const activeChapter = this.state.activeChapter;
// const activePage = this.state.activePage;
// return (
// <div id="book-reader" className={classNames(className, 'd-flex align-items-stretch')} style={style}>
// <div id="reader-menu" className="book-element reader-menu flex-shrink-1">
// <div className="menu-cover blur" style={{
// backgroundImage: `url('${this.state.cover}')`
// }} />
// {/* <div className="menu-cover" style={{
// backgroundImage: `url('${this.state.cover}')`,
// opacity: this.state.coverOpacity,
// }} /> */}
// <div className="menu-wrapper d-flex flex-column">
// <div className="flex-shrink-1">
// <div className="menu-element menu-header">
// <HeaderToggleNav onBackClick={this.props.onBack as any}>
// {this.state.title}
// </HeaderToggleNav>
// </div>
// </div>
// <ListingScroll className="menu-element menu-body flex-grow-1"
// //onScroll={this.onChapterScroll}
// >
// <div style={{ height: ReaderModule.DEFAULT_COVER_SIZE }} />
// <Listing
// className="chapters"
// innerClassName={classNames('chapters-inner')}
// columnSize={1} gapSize={4}
// >
// {this.state.chapters.map((chapter) => (
// <Card key={chapter.index}
// className={classNames('chapter-item', { active: chapter.index === this.state.activeChapter?.index })}
// onClick={() => this.changeChapter(chapter.index)}
// >
// <CardBody className="d-flex align-items-center justify-content-between">
// <div className="label">{chapter.label}</div>
// <div className="date">{moment(chapter.date).format('DD/MM/YYYY')}</div>
// </CardBody>
// </Card>
// ))}
// </Listing>
// <div style={{ height: ReaderModule.DEFAULT_COVER_SIZE }} />
// </ListingScroll>
// </div>
// </div>
// {
// typeof activeChapter != 'undefined' && (
// <div id="reader-page" className="book-element reader-menu flex-shrink-1">
// <div className="menu-wrapper d-flex flex-column">
// <div className="flex-shrink-1">
// <div className="menu-element menu-header">
// <HeaderToggleNav onBackClick={this.closeChapter}>
// <span>{activeChapter.label}</span>
// {
// this.state.chapterLoading && (
// <span>(loading...)</span>
// )
// }
// </HeaderToggleNav>
// </div>
// </div>
// <ListingScroll className="menu-element menu-body flex-grow-1">
// <div style={{ height: ReaderModule.DEFAULT_COVER_SIZE }} />
// <Listing
// className="book-pages"
// innerClassName={classNames('m-reader-book-page', 'page-list')}
// columnSize={1} gapSize={4}
// >
// {this.state.activeChapterPages.map((page) => (
// <Card key={`${this.state.activeChapter?.index}${page.label}`}
// onClick={() => this.changeChapterPage(page)} className={classNames('book-page-item', { active: page.index === this.state.activePage?.index })}
// style={{ backgroundImage: `url(${page.url})` }}>
// <CardBody className="book-page-inner" style={{ textAlign: 'center' }}>
// <span className="book-page-label">{page.label}</span>
// </CardBody>
// </Card>
// ))}
// </Listing>
// <div style={{ height: ReaderModule.DEFAULT_COVER_SIZE }} />
// </ListingScroll>
// </div>
// </div>
// )
// }
// <div id="reader-content" className="book-element flex-grow-1 d-flex align-items-center justify-content-center">
// {
// typeof activePage !== 'undefined' ? (
// <img alt="uwufication" src={activePage.url} style={{maxWidth: '100%', maxHeight: '100%'}} />
// ) : (
// <div>
// <h3>No Preview Available</h3>
// </div>
// )
// }
// </div>
// </div>
// )
// }
// }
// const HeaderToggleNav = (props: {
// onBackClick: () => void;
// children: any;
// }) => (
// <div className="flex-full d-flex align-items-stretch border-bottom">
// <div className="d-flex align-items-center border-right" onClick={props.onBackClick}>
// <div style={{ width: 40, textAlign: 'center', fontWeight: 'bold' }}><<</div>
// </div>
// <div className="flex-grow-1">
// <div className="flex-full d-flex flex-column align-items-center justify-content-center">
// {props.children}
// </div>
// </div>
// </div>
// )
|
//===================== 2018 ISPuddy reversed engineering =====================//
// Reverse Engie Training Annotations
// An in-world location-specific information bubble.
//=============================================================================//
#include "cbase.h"
#include "tf_gamerules.h"
#include "tf_shareddefs.h"
#include "tf_player.h"
#include "tf_team.h"
#include "engine/IEngineSound.h"
#include "entity_training_annotations.h"
#include "basecombatcharacter.h"
#include "in_buttons.h"
#include "tf_fx.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DATADESC( CTrainingAnnotation )
DEFINE_KEYFIELD( m_displayText, FIELD_STRING, "display_text" ),
DEFINE_KEYFIELD( m_flLifetime , FIELD_TIME, "lifetime" ),
DEFINE_KEYFIELD( m_flVerticalOffset , FIELD_FLOAT, "offset" ),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Show", InputShow ),
DEFINE_INPUTFUNC( FIELD_VOID, "Hide", InputHide ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( training_annotation, CTrainingAnnotation );
CTrainingAnnotation::CTrainingAnnotation()
{
m_displayText = "";
m_flLifetime = 10.0f;
m_flVerticalOffset = 0.0f;
}
//-----------------------------------------------------------------------------
// Purpose: Spawn function
//-----------------------------------------------------------------------------
void CTrainingAnnotation::Spawn( void )
{
Precache();
BaseClass::Spawn();
}
//-----------------------------------------------------------------------------
// Purpose: Precache function
//-----------------------------------------------------------------------------
void CTrainingAnnotation::Precache( void )
{
}
void CTrainingAnnotation::InputShow( inputdata_t &inputdata )
{
Show( inputdata.pActivator );
}
void CTrainingAnnotation::InputHide( inputdata_t &inputdata )
{
Hide( inputdata.pActivator );
}
void CTrainingAnnotation::Show( CBaseEntity *pActivator )
{
IGameEvent *pEvent = gameeventmanager->CreateEvent( "show_annotation" );
if ( pEvent )
{
pEvent->SetInt( "id", entindex() );
pEvent->SetString( "text", m_displayText );
pEvent->SetInt( "lifetime", m_flLifetime );
//pEvent->SetInt( "v", m_flVerticalOffset );
pEvent->SetString( "play_sound", NULL );
pEvent->SetFloat( "worldPosX", GetAbsAngles().x );
pEvent->SetFloat( "worldPosY", GetAbsOrigin().y );
pEvent->SetFloat( "worldPosZ", GetAbsOrigin().z );
gameeventmanager->FireEventClientSide( pEvent );
}
}
void CTrainingAnnotation::Hide( CBaseEntity *pActivator )
{
IGameEvent *pEvent = gameeventmanager->CreateEvent( "hide_annotation" );
if ( pEvent )
{
pEvent->SetInt( "id", entindex() );
gameeventmanager->FireEventClientSide( pEvent );
}
} |
<filename>tools/llvm-pdbutil/OutputStyle.h
//===- OutputStyle.h ------------------------------------------ *- C++ --*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVMPDBDUMP_OUTPUTSTYLE_H
#define LLVM_TOOLS_LLVMPDBDUMP_OUTPUTSTYLE_H
#include "llvm/Support/Error.h"
namespace llvm {
namespace pdb {
class OutputStyle {
public:
virtual ~OutputStyle() {}
virtual Error dump() = 0;
};
}
}
#endif
|
Attack Resilient Distributed Control for AC Microgrids with Distributed Robust State Estimation In this paper, we propose an attack resilient distributed control for islanded AC microgrid (MG) systems. The distributed control on an MG is implemented based on a sparse communication network where each agent only has access to the information of itself and the neighboring distributed generators (DGs). Although distributed control has several advantages compared with its centralized counterpart, the increased dependence on communication and lack of access to global information make it vulnerable to cyber threats from malicious entities. To increase the resiliency of the distributed control, we propose to incorporate a distributed robust state estimation scheme. In the proposed scheme, the voltage and frequency references are calculated based on the results of the distributed estimator instead of directly using the local measurements. The performance of the proposed attack resilient control approach is validated through simulation results on a test microgrid system under false data injection attack. |
<gh_stars>0
import BrickTiling from "./tiling/BrickTiling";
import config from "./config";
import ParallelogramTiling from "./tiling/ParallelogramTiling";
import Tiling from "./tiling/Tiling";
import TriangleTiling from "./tiling/TriangleTiling";
import TwoSquareTiling from "./tiling/TwoSquareTiling";
export type FormID =
| "set-iters"
| "parallelogram"
| "triangle"
| "triangle-angles"
| "brick"
| "two-square";
export type FormParameter = {
name: string;
placeholder: string;
id: string;
minInclusive: number;
minExclusive: number;
maxInclusive: number;
maxExclusive: number;
};
export type FormData = {
parameters: FormParameter[];
message: string;
name: string;
newTiling: boolean;
tiling: (params: number[]) => Tiling;
};
const FormConfig: Record<FormID, FormData> = {
"set-iters": {
name: "Set Iterations",
message:
`This sets the number of iterations computed, N. The default is ${config.trajectoryIters}.` +
" We won't enforce a maximum, but even 10,000 takes a while.",
parameters: [
{
name: "Iterations",
placeholder: "N",
id: "N",
minInclusive: 0,
minExclusive: 0,
maxInclusive: Number.POSITIVE_INFINITY,
maxExclusive: Number.POSITIVE_INFINITY,
},
],
newTiling: false,
tiling: (): never => {
throw new Error("no tiling");
},
},
parallelogram: {
name: "Parallelogram Tiling",
message:
"This window sets the tiling to the standard tiling by parallelograms with " +
" sides of length 1 and L, and an angle θ measured in degrees.",
parameters: [
{
name: "Length",
placeholder: "L",
id: "L",
minInclusive: 0,
minExclusive: 0,
maxInclusive: Number.POSITIVE_INFINITY,
maxExclusive: Number.POSITIVE_INFINITY,
},
{
name: "Angle",
placeholder: "θ",
id: "theta",
minInclusive: 0,
minExclusive: 0,
maxInclusive: 180,
maxExclusive: 180,
},
],
newTiling: true,
tiling: ParallelogramTiling.prototype.fromParameters,
},
triangle: {
name: "Triangle Tiling",
message:
"This window sets the tiling to the standard tiling by triangulated " +
"parallelograms with sides of length 1 and L, and an angle θ measured in " +
" degrees. The diagonal is opposite θ.",
parameters: [
{
name: "Length",
placeholder: "L",
id: "L",
minInclusive: 0,
minExclusive: 0,
maxInclusive: Number.POSITIVE_INFINITY,
maxExclusive: Number.POSITIVE_INFINITY,
},
{
name: "Angle",
placeholder: "θ",
id: "theta",
minInclusive: 0,
minExclusive: 0,
maxInclusive: 180,
maxExclusive: 180,
},
],
newTiling: true,
tiling: TriangleTiling.prototype.fromParameters,
},
"triangle-angles": {
name: "Triangle Tiling",
message:
"This window sets the tiling to the standard tiling by triangulated " +
"parallelograms with angles φ and θ (both measured in degrees), and a " +
"base length of 1. The diagonal is opposite θ.",
parameters: [
{
name: "Angle φ",
placeholder: "φ",
id: "phi",
minInclusive: 0,
minExclusive: 0,
maxInclusive: 180,
maxExclusive: 180,
},
{
name: "Angle θ",
placeholder: "θ",
id: "theta",
minInclusive: 0,
minExclusive: 0,
maxInclusive: 180,
maxExclusive: 180,
},
],
newTiling: true,
tiling: TriangleTiling.prototype.fromAngles,
},
brick: {
name: "Brick Tiling",
message:
"This window constructs the tiling by square bricks with offset T, a real " +
"number between zero and one.",
parameters: [
{
name: "Offset",
placeholder: "T",
id: "T",
minInclusive: 0,
minExclusive: Number.NEGATIVE_INFINITY,
maxInclusive: 1,
maxExclusive: Number.POSITIVE_INFINITY,
},
],
newTiling: true,
tiling: BrickTiling.prototype.fromParameters,
},
"two-square": {
name: "Two Square Tiling",
message:
"This window sets the tiling to two-square tiling with side-lengths " +
"L<sub>1</sub> and L<sub>2</sub>.",
parameters: [
{
name: "Length 1",
placeholder: "L_1",
id: "L_1",
minInclusive: 0,
minExclusive: 0,
maxInclusive: Number.POSITIVE_INFINITY,
maxExclusive: Number.POSITIVE_INFINITY,
},
{
name: "Length 2",
placeholder: "L_2",
id: "L_2",
minInclusive: 0,
minExclusive: 0,
maxInclusive: Number.POSITIVE_INFINITY,
maxExclusive: Number.POSITIVE_INFINITY,
},
],
newTiling: true,
tiling: TwoSquareTiling.prototype.fromParameters,
},
};
export default FormConfig;
|
/* called when the new button is clicked
*/
void handler_new_button_clicked(GtkButton *button, gpointer data)
{
game_reset();
gui_update(UPDATE_TRUE);
} |
The company, County Ambulance, violated federal regulations by billing Medicare and MainCare for an employee who was not eligible for federal programs because of a prior licensing penalty for diverting controlled substances.
County Ambulance of Ellsworth on Tuesday entered into a settlement agreement with the federal and Maine state governments for submitting false claims to the Medicare and Medicaid programs.
County Ambulance will pay $16,776 to resolve allegations that it submitted bills to pay for an ambulance employee – from January 2015 through April 2016 – who was prohibited from receiving federal pay or benefits. Medicare is a federal program while Medicaid is a federal program operated by the states, using a blend of federal and state dollars.
Before joining County Ambulance, the employee had been excluded after surrendering her license to practice as a pharmacy technician due to the diversion of controlled substances, but County Ambulance failed to check publicly available exclusion databases to determine if she was excluded, according to a statement by U.S. Attorney Halsey B. Frank.
Frank said County Ambulance cooperated throughout the investigation.
The settlement comes about five months after Maine Medical Center in Portland and the state’s largest ambulance provider agreed to pay $1.4 million in February to the federal government to settle allegations that the ambulance provider submitted reimbursement claims for ambulance rides that were not medically necessary.
North East Mobile Health Services of Scarborough agreed to pay $825,000 to resolve allegations that spanned between 2007 and 2015, while Maine Med paid $600,000 for documentation errors, according to Frank’s office. |
ATPG for 2D/3D wider Kogge-Stone Adder circuit It is an well established fact that 3D design has a number of benefits over corresponding 2D design, albeit with somewhat more design complexity. One key advantage is the reduced set of Test Vectors needed to test a 3D circuit as the design is spread over multiple planes, each plane having reduced size than the original design. When all the TVs across these layers are combined we still get a smaller set as the TV complexity increases super linearly with the size of the circuit. In this paper we designed 4-, 8-, 16-, 32- and 64-bit 2D KSA adder circuits. We created the 3D version of the corresponding KSA circuits using two planes, inserting necessary control points in the form of Scan flip-flops. We then used TetraMax to create ATPG set of Test Vectors for these circuits to detect stuck at and transition faults. We find that the 3D version enables us to use effectively a much reduced set of Test Vectors for pre-bond testing compared to the 2D counterpart at the same time with increasing fault coverage. This is in confirmation with some of the results published in the literature on this. |
//
// FJInputPanelView.h
// FriendCircleDemo
//
// Created by MacBook on 2018/1/27.
// Copyright © 2018年 nuanqing. All rights reserved.
//
#import <UIKit/UIKit.h>
@class FJInputPanelView;
@protocol FJInputPanelViewDelegate<NSObject>
- (void)inputPanelViewKeyBoardShow:(FJInputPanelView *)inputPanelView;
- (void)textViewSendClicked;
@end
@interface FJInputPanelView : UIView
+ (instancetype)inputPanelView;
@property (nonatomic,strong) YYTextView *textView;
@property (nonatomic,assign) CGFloat recordHeight;
@property (nonatomic,weak) id<FJInputPanelViewDelegate> delegate;
@end
|
“In the beginning, it was annoying,” McCrea said, about Bellinger’s visits. “It took time for me to realize he was actually helping me.”
Living in a community, rather than living independently on the streets, can be life-changing. BCHS focuses on building a community in their buildings, and making sure residents feel comfortable there, with both neighbors and staff. Residents slowly begin to get to know social workers and their neighbors. They join in-house groups like a horticultural society or a coffee club or a group for FUSE members. They attend holiday dinners or monthly floor meetings, all of which are optional. If someone disappears for a few days, their neighbors can tell the social workers they are concerned, and the social workers can check in.
Buildings are structured to promote shared spaces where people can spend time and talk to friends and neighbors, encouraging people to leave their rooms and socialize, Nemetsky said. McCrea shares a kitchen and bathroom with other tenants, and Bellinger has meetings with them to talk about the challenges that arise.
Critics of so-called Housing First programs like this one, which give people homes without requiring them to first get sober or deal with their mental illnesses, say that people will become homeless again because housing alone doesn’t solve all the problems people face. But supportive-housing organizations like BCHS address this criticism by strongly focusing on building the community and networks so that people feel safe and secure, and are motivated to address the underlying issues that made them homeless.
“In additional to concrete services, we’re really trying to create a sense of community for all of the formerly homeless residents,” Nemetsky said. “We really use this as a programmatic model and a clinical approach."
For most people coming into supportive housing from the streets, the first six months can be challenging. Sometimes, they’ll continue to sleep on the streets and use their bed infrequently, Nemetsky said. They may test boundaries, since when they were homeless they had to develop survival skills to push people away. But the social workers have patience, and usually, residents settle down and become like almost any other tenant.
“If you think about any of us living in the community, when we had a bad day, we have somebody we can talk to, it doesn’t have to be a worker, it can be a neighbor or friend,” Nemetsky said. “That’s part of what we’re doing, and what supportive housing is doing, is creating those interpersonal relationships so those crises don’t build up. When someone’s having a bad day, they can talk to their neighbor, their friend.”
I also visited the Prince George, a historical hotel on East 27th street in Manhattan that has been turned into a mixed supportive-housing and low-income-housing building. I spoke to Calvin Bennett, who has been in a wheelchair since a kidney transplant last year, in the ornate lobby, which has intricately decorated columns and wood paneling on the walls. Bennett says he had been caught up in getting and using drugs when he lived on the streets, and had ignored the outreach workers who came around trying to get him and others into shelters. Then one day, an outreach worker with Breaking Ground told Bennett that in the time since they’d last seen each other, the worker had helped another man find permanent housing. That struck Bennett as significant. So he started the long process of going through the paperwork to apply for an apartment in the Prince George. He moved in about seven years ago. |
Almost twice as many people cast ballots in B.C., as did in the last federal election, according to numbers just released by Elections Canada.
Preliminary figures show 507,920 ballots were cast in the advance vote, up 96 per cent from 259,278 in the 2011 advance polls.
Some individual ridings, including Merritt, B.C., saw advance polls run out of ballots, despite a supply from Elections Canada of double the number required in 2011.
The greatest provincial increase was in Alberta, where advance voter turnout was up 124 per cent. In Nunavut, turnout more than tripled last election's advance polls, but was only 1109.
Across Canada, voter turnout in the advance polls was 3.63 million, up 73 per cent compared to the 2011 federal election.
Chart of advance voter turnout across Canada |
A man carrying a table leg was tasered by armed police when he caused a disturbance after a car accident on a busy Norwich road.
Norwich Crown Court heard Nicholas James, 45, came out of his home armed with the table leg after hearing the noise of the collision.
He then became abusive to a small group gathered to help at the scene.
He challenged one of the men to a fight and a police armed response team was called and James had to be tasered and then arrested.
He said James was found to have a knuckle-duster and an extendable baton in his pocket, although these weapons were not produced.
James, of Thorpe Road, admitted affray on October 14 and possession of two offensive weapons, the knuckle-duster and the extendable baton.
Gavin Cowe, defending, said James, who has a broken hip and is taking 13 different types of prescribed medication for his health problems, had been plagued by noise problems at his address as motorcyclists regularly gathered near his home and he thought the noise was something to do with his property being damaged.
He said that James had not produced the weapons found in his pocket.
However he accepted James had a number of health problems and was on 13 different prescribed medications which he had mixed with alcohol that evening.
He imposed a 12-month jail sentence suspended for 12 months and ordered him to take part in an alcohol treatment programme and a thinking skills programme.
However he warned if he breached it he would go straight to prison. |
Promotion of Hernia Repair with High-Strength, Flexible, and Bioresorbable Silk Fibroin Mesh in a Large Abdominal Hernia Model. The use of synthetic surgical meshes for abdominal hernia repair presents numerous challenges due to insufficient mechanical strength, nonabsorbability, and implant rigidity that leads to complications including chronic inflammatory reactions and adhesions. In this study, a naturally derived, high-strength, flexible, and bioresorbable silk fibroin mesh was developed by knitted textile engineering and biochemical manipulation. The mechanical properties of the mesh were optimized with the trial of different surface coating methods (thermal or chemical treatment) and 12 different knit patterns. Our silk fibroin mesh showed sufficient tensile strength (67.83 N longitudinally and 62.44 N vertically) which afforded the high mechanical strength required for abdominal hernia repair (16 N). Compared to the commonly used commercial nonabsorbable and absorbable synthetic meshes (Prolene mesh and Ultrapro mesh, respectively), the developed silk fibroin mesh showed advantages over other meshes, including lower elongation rate (47.14% longitudinally and 67.15% vertically, p < 0.001), lower stiffness (10-1000 fold lower, p < 0.001), and lower anisotropic behavior ( = 0.32, p < 0.001). In a rat model of large abdominal hernia repair, our mesh facilitated effective hernia repair with minimal chronic inflammation which gradually decreased from 15 to 60 days postoperation, as well as lower adhesion formation rate and scores compared to control meshes. There was more abundant and organized collagen deposition, together with more pronounced neovascularization in the repaired tissue treated with silk fibroin mesh as compared to that treated with synthetic meshes. Besides, the silk fibroin mesh gradually transferred load-bearing responsibilities to the repaired host tissue as it was bioresorbed after implantation. Its isotropic architecture favored an ease of use during operations. In summary, our findings indicate that the use of knitted silk fibroin mesh provides a safe and effective alternative solution for large abdominal hernia repairs as it overcomes the prevailing limitations associated with synthetic meshes. |
<filename>quarkus/addons/kubernetes/runtime/src/main/java/org/kie/kogito/addons/quarkus/k8s/CachedServiceAndThenRouteEndpointDiscovery.java
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* 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 org.kie.kogito.addons.quarkus.k8s;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.kie.kogito.addons.k8s.CacheNames;
import org.kie.kogito.addons.k8s.Endpoint;
import org.kie.kogito.addons.k8s.KnativeRouteEndpointDiscovery;
import org.kie.kogito.addons.k8s.KubernetesServiceEndpointDiscovery;
import org.kie.kogito.addons.k8s.ServiceAndThenRouteEndpointDiscovery;
import io.quarkus.cache.CacheResult;
/**
* Cached version of the discovery service.
* Each cache can be individually configured in the users' application.
*
* @see <a href="https://quarkus.io/guides/cache">Quarkus Cache Guide</a>
*/
public class CachedServiceAndThenRouteEndpointDiscovery extends ServiceAndThenRouteEndpointDiscovery {
public CachedServiceAndThenRouteEndpointDiscovery(KubernetesServiceEndpointDiscovery kubeDiscovery, KnativeRouteEndpointDiscovery knativeDiscovery) {
super(kubeDiscovery, knativeDiscovery);
}
@Override
@CacheResult(cacheName = CacheNames.CACHE_BY_LABELS)
public List<Endpoint> findEndpoint(String namespace, Map<String, String> labels) {
return super.findEndpoint(namespace, labels);
}
@Override
@CacheResult(cacheName = CacheNames.CACHE_BY_NAME)
public Optional<Endpoint> findEndpoint(String namespace, String name) {
return super.findEndpoint(namespace, name);
}
}
|
Dispute Settlement Mechanisms Under Free Trade Agreements and the WTO: Stakes, Issues and Practical Considerations: A Question of Choice? Choice of forumclauses in free trade agreements (FTAs)might lead to overlapping jurisdictions with theWTO. In such cases,which dispute settlementmechanism prevails? How do or couldWTO panels asses their jurisdiction? And how does a party choose between the dispute settlement mechanisms provided by a FTA and the WTO? This article analyses how the WTO jurisprudence and general principles address, respectively might address the issue of conflict of jurisdiction, and outlines the considerations a party has to keep in mind when selecting a forum. To date, there is no clear-cut solution nor answer to the questions above. |
<filename>Application/src/Application/ImGui/GameWindows/RobotCreationWindow.cpp
#include "RobotCreationWindow.hpp"
#include "Application/Game/Ingame/RobotsManagement.hpp"
#include "mypch.hpp"
using namespace Application;
namespace Application::GameWindows
{
void RobotCreationWindow::Render()
{
this->SetNextPos();
this->SetNextSize();
bool createRobot = false;
bool destroyRobot = false;
bool canCreateRobot = m_RobotsManagement->canAddRobots();
bool canDestroyRobot = m_RobotsManagement->canRemoveRobots();
ImGui::Begin("Robot management", NULL, m_WindowFlags);
{
//First line
ImGui::Text("Total Robot count: %lu", m_RobotsManagement->getTotRobots());
ImGui::Text("Free Robots: %lu/%lu", m_RobotsManagement->getFreeRobots() , m_RobotsManagement->getTotRobots());
//Third line
//TODO: remove robs and diable if cant
ImGui::Text("Production cost: %lu", m_RobotsManagement->getProdCost());
if (!canCreateRobot) {
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.5f);
createRobot = ImGui::ButtonEx("Create robot", {0,0}, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_Disabled);
ImGui::PopStyleVar();
} else createRobot = ImGui::ButtonEx("Create robot", {0,0}, ImGuiButtonFlags_Repeat);
if (!canDestroyRobot) {
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.5f);
destroyRobot = ImGui::ButtonEx("Destroy robot", {0,0}, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_Disabled);
ImGui::PopStyleVar();
} else destroyRobot = ImGui::ButtonEx("Destroy robot", {0,0}, ImGuiButtonFlags_Repeat);
}
if (createRobot && canCreateRobot) {
m_RobotsManagement->createRobots(1);
} else if (destroyRobot && canDestroyRobot) {
m_RobotsManagement->destroyRobots(1);
}
ImGui::End();
}
} // namespace Application
|
The effects of nutrition on the reproductive performance of Finn x Dorset ewes. II. Post-partum ovarian activity, conception and the plasma concentration of progesterone and LH. After lambing forty-five ewes were allocated to three groups, two of sixteen and one of thirteen ewes. The lambs of the two groups of sixteen ewes were weaned on Day 1 after lambing and the ewes were fed a diet of 100% (Group H) or 50% (Group R) of maintenance energy requirements. The thirteen ewes in the third group (Group L) suckled twin lambs and were fed freely. During the first 3 weeks after lambing, oestrus was observed for 11/16 (Group H) and 8/16 (Group R) ewes; of the ewes which had shown oestrus in the two groups, ovulation occurred in 5/8 and 5/7 respectively. Only 1/13 Group-L ewes showed oestrus and ovulated during the same period. The mean plasma concentrations of progesterone and LH were unaffected by the treatments and were around 0-4 and 1-5 ng/ml, respectively. Restricted feeding had no effect on oestrus, ovulation or the hormone levels during the oestrus cycle following synchronization. The onset of oestrus and the start of the preovulatory discharge of LH were 3 and 6 hr later, respectively, in the lactating ewes (Group L) than in those in Groups H and R. Ewes in Group L also had a higher ovulation rate, 2-8 +/- 0-2 versus 2-1 +/- 0-2 (P less than 0-05). Restricted feeding reduced the number of ewes lambing; only 1/11 ewes in Group R, considered to have conceived because of the presence of high progesterone levels 17 days after mating, subsequently lambed compared with 6/12 in Group H and 5/9 in Group L. |
The effector domain of Rab6, plus a highly hydrophobic C terminus, is required for Golgi apparatus localization C-terminal lipid modifications are essential for the interaction of Ras-related proteins with membranes. While all Ras proteins are farnesylated and some palmitoylated, the majority of other Ras-related proteins are geranylgeranylated. One such protein, Rab6, is associated with the Golgi apparatus and has a C-terminal CXC motif that is geranylgeranylated on both cysteines. We show here that farnesylation alone cannot substitute for geranylgeranylation in targeting Rab6 to the Golgi apparatus and that whereas Ras proteins that are farnesylated and palmitoylated are targeted to the plasma membrane, mutant Rab proteins that are both farnesylated and palmitoylated associate with the Golgi apparatus. Using chimeric Ras-Rab proteins, we find that there are sequences in the N-terminal 71 amino acids of Rab6 which are required for Golgi complex localization and show that these sequences comprise or include the effector domain. The C-terminal hypervariable domain is not essential for the Golgi complex targeting of Rab6 but is required to prevent prenylated and palmitoylated Rab6 from localizing to the plasma membrane. Functional analysis of these mutant Rab6 proteins in Saccharomyces cerevisiae shows that wild-type Rab6 and C-terminal mutant Rab6 proteins which localize to the Golgi apparatus in mammalian cells can complement the temperature-sensitive phenotype of ypt6 null mutants. Interestingly, therefore, the C-terminal hypervariable domain of Rab6 is not required for this protein to function in S. cerevisiae. |
<reponame>chrisxue815/leetcode_python<filename>problems/test_0254.py
import unittest
from typing import List
import math
import utils
# O(?) time. O(?) space. Backtracking, integer factorization, combination.
class Solution:
def getFactors(self, n: int) -> List[List[int]]:
result = []
def dfs(target, start, factors):
for i in range(start, int(math.sqrt(target)) + 1):
if target % i == 0:
factors.append(i)
clone = list(factors)
clone.append(target // i)
result.append(clone)
dfs(target // i, i, factors)
factors.pop()
dfs(n, 2, [])
return result
class Test(unittest.TestCase):
def test(self):
cases = utils.load_test_json(__file__).test_cases
for case in cases:
args = str(case.args)
actual = Solution().getFactors(**case.args.__dict__)
self.assertCountEqual(case.expected, actual, msg=args)
if __name__ == '__main__':
unittest.main()
|
Today's millennials and Generation Z face starkly different financial realities than their parents did at their age. As a parent of a young adult, how can you help your children understand their financial options to build a foundation for their futures? The first step may be to appreciate where they’re coming from and how their attitudes may differ from yours. Your assumptions about finances based on your experience at their age may no longer hold true. Once you understand your millennial children's situation, you may better be equipped to help them make sound financial decisions.
Consider these recent findings about millennials and credit from VantageScore Solutions before advising your adult children.
Now more than ever, credit scores impact everything from getting an apartment or home, acquiring loans with decent interest rates and more. A poor credit score makes it harder for young adults to get ahead. Because standard credit scoring models assess the length of time credit accounts are maintained and the number of accounts, millennials and their younger siblings are at an immediate disadvantage. It takes longer for them to build a credit history worthy of decent interest rates and large loans such as a home mortgage.
What you can do: Explain that establishing good credit now will increase their ability to borrow later, though it may take a couple of years to establish that history before they're considered creditworthy of assuming substantial debt such as a mortgage. Help them find a good revolving credit account by checking out sites that assess credit cards in terms of interest rates, annual fee (if any), rewards programs and more.
Most millennials carry higher amounts of student loan debt than their parents did. As a result, they are reluctant to acquire more debt. For this reason, they may have fewer revolving credit accounts. This behavior is actually smarter and less financially risky on their part, but it results in them having a “thin file,” the term for a history with three or fewer credit accounts. In fact, many thin-file millennials have average income levels and assets similar to their thicker-file counterparts. And because they do have the income, they actually have the capacity to handle new accounts. Fortunately, VantageScore Solutions, a rival to the FICO score, includes trended credit data. According to their recent online article, Millennial Credit Habits: A Major Shift, trended data attributions “change the focus of credit scoring models to better understand actual credit management behaviors over time versus static snapshots." In other words, it takes into account the typical millennial's prudent behavior when it comes to acquiring new debt. Lenders with this understanding of the bigger picture will be more likely to give your millennials the opportunity to borrow.
What you can do: Tell your adult children to utilize credit in a safe and sound manner, and to apply for new credit carefully in order to build a more robust credit history. Stress that they should never spend more on the card than they can afford. Setting up automatic minimum payments on cards can help them avoid late payments, but also advise that they can — and should — pay more than the minimum each month, and in full whenever possible.
Because of millennials’ reluctance to assume debt, they may put off major life events such as buying a home until their student loans are paid off. Recent data from VantageScore “shows (millennials) are writing their own story when it comes to using credit,” says the company’s president, Barrett Burns. Some lenders won’t loan to would-be borrowers with thin credit histories, while others offer them more expensive subprime-like products. But the research found that millennials “are anything but conventional.” VantageScore credit scores, which take these behavioral differences into account, are used by lenders, landlords, utility companies, telecom companies and many others to determine creditworthiness. However, many mortgage lenders may be missing out on thousands of potential clients by relying solely on traditional scoring models.
What you can do: Reassure your adult children that, while some larger life goals may seem out of reach now, their responsible actions such as paying down their student loans will pay off, sooner than they might expect. Encourage them to make more than minimum payments on their student loans to save on interest and eradicate that debt sooner.
So what’s the upshot? While you may be eager to see your adult children settling down in a home filled with grandchildren, they are actually trying hard to put their financial ducks in a row. You can help by advising them on smart tactics to manage their money and improve their credit scores. |
import java.util.*;
public class CF2A {
static class Record {
int score;
int round;
Record(int score, int round) {
this.score = score;
this.round = round;
}
public String toString() {
return "(" + score + " " + round + ")";
}
}
public static void main(String[] args) {
Map<String, List<Record>> map = new HashMap<String, List<Record>>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String name = sc.next();
List<Record> list = map.get(name);
if (list == null) {
list = new ArrayList<Record>();
map.put(name, list);
}
list.add(new Record(sc.nextInt(), i));
}
String name = null;
int score_ = 0;
int round_ = 0;
for (Map.Entry<String, List<Record>> player : map.entrySet()) {
List<Record> list = player.getValue();
int round = n;
int score1 = 0;
for (Record record : list)
score1 += record.score;
int score2 = 0;
for (Record record : list) {
score2 += record.score;
if (score2 >= score1) {
round = record.round;
break;
}
}
if (name == null || score_ < score1
|| score_ == score1 && round_ > round) {
name = player.getKey();
score_ = score1;
round_ = round;
}
}
System.out.println(name);
}
}
|
Samantha Bee will be on hand to needle the nascent presidency of Donald Trump throughout 2017. Time Warner’s TBS said Wednesday that it picked up her scathing comedy program, “Full Frontal,” for a second season, which will start next year. The show will move to Wednesdays at 10:30 p.m., moving from its present roost on Mondays at the same time.
“Of course we’re picking up the show,” said Thom Hinkle, senior vice president of original programming for TBS, in a prepared statement. “In less than a year, Sam has become one of the most talked-about personalities in all of television and ‘Full Frontal’s’ audience continues to grow.”
The decision speaks to the rise of comedy programs that have a serious purpose at their core: Analyzing and investigating the news. Bee, John Oliver and Bill Maher have all thrived with programs that dig deep into hot political and cultural topics. Seth Meyers, host of NBC’s “Late Night,” has seen attention to his program grow after adopting a newsier bent for his opening segments. And Comedy Central is continuing to burnish Trevor Noah on “The Daily Show” as a voice for millennials who want to poke at politics and national issues with comedy.
Bee and executive producer Jo Miller have infused “Full Frontal” with a take-no-prisoners attitude. The show opens with a montage of Bee entering an arena, ready to take on the Statue of Liberty and Jesus Christ. The host eagerly incorporates wicked profanity into her monologues on politics, culture and gender. “We do a show to please ourselves,” said, Bee, in an interview with Variety earlier this year. “This gives us an opportunity to say the things we want in the exact way we want to say them.” According to both Bee and Miller, the internal emails sent between producers and TBS’ standards and practices team about the language and graphics used in the show’s segments are voluminous enough to fill a very large book.
Over the course of its first season, “Full Frontal” has examined the horrifying effects of a national backlog of rape-kit evidence, and made use of a graphic showing an elephant being sexually penetrated by a cross. President-elect Trump, Jimmy Fallon and Matt Lauer are among the people who have been unable to escape the program’s sharp elbows.
“Full Frontal’ currently reaches an average of 3.3 million viewers per episode across multiple platforms, according to TBS, which noted the show’s reach among adults between 18 and 49, the demographic coveted most by advertisers, had risen 37% for the quarter to date.
Executives decided to renew the program in the early fall, according to people familiar with the situation, but wanted to wait until after the presidential election to make an official announcement. The move to Wednesday was made to help production and some of the creativity behind the program, according to a person familiar with the matter. Producers at the show have often had to work furiously over weekends to update the Monday-night program to accommodate the latest developments in what has recently been a punishing cycle of news about politics, mass shootings and other events that draw outsize attention.
“I am only sorry that this renewal leaves me unavailable for a cabinet position in the new administration,” Bee said in a statement. “I will, however, be available to host the White House Correspondents Dinner, seeing as I already bought the dress.”
“Full Frontal” is executive-produced by Bee, Miller, Jason Jones, Miles Kahn and Tony Hernandez. It will begin to air regularly on Wednesdays starting January 11. |
<filename>src/Components/Common/Avatar/Avatar.tsx
import React from "react"
import Blockies from "Hooks/Blockies"
import styles from "./Avatar.module.css"
interface PropsTypes {
randomString: string
}
export default ({ randomString }: PropsTypes) => {
const src = Blockies(randomString)
return <img className={styles.avatar} src={src} />
}
|
package com.graly.mes.prd.designer.common.command;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;
import com.graly.mes.prd.designer.common.notation.BendPoint;
import com.graly.mes.prd.designer.common.notation.Edge;
import com.graly.mes.prd.designer.common.notation.Node;
public abstract class AbstractEdgeMoveCommand extends Command {
private Node oldTarget;
private Node oldSource;
private Node target;
private Node source;
private Edge edge;
private boolean bendPointsAdded = false;
protected abstract void doMoveSource(Node oldSource, Node newSource);
protected abstract void doMoveTarget(Node target);
public void execute() {
if (oldTarget == null) {
oldTarget = edge.getTarget();
}
if (oldSource == null) {
oldSource = edge.getSource();
}
if (source != null && source != edge.getSource()) {
doMoveSource(oldSource, source);
}
if (target != null && target != edge.getTarget()) {
doMoveTarget(target);
}
if (edge.getSource() == edge.getTarget() && edge.getBendPoints().isEmpty()) {
addBendPoints();
}
}
public void undo() {
if (bendPointsAdded) {
removeBendPoints();
}
if (target != null) {
doMoveTarget(oldTarget);
}
if (source != null) {
doMoveSource(source, oldSource);
}
}
private void removeBendPoints() {
List<BendPoint> list = new ArrayList<BendPoint>(edge.getBendPoints());
for (int i = 0; i < list.size(); i++) {
edge.removeBendPoint((BendPoint)list.get(i));
}
}
private void addBendPoints() {
bendPointsAdded = true;
Rectangle constraint = source.getConstraint();
int horizontal = - (constraint.width / 2 + 25);
int vertical = horizontal * constraint.height / constraint.width;
BendPoint first = new BendPoint();
first.setRelativeDimensions(new Dimension(horizontal, 0), new Dimension(horizontal, 0));
BendPoint second = new BendPoint();
second.setRelativeDimensions(new Dimension(horizontal, vertical), new Dimension(horizontal, vertical));
edge.addBendPoint(first);
edge.addBendPoint(second);
}
public boolean canExecute() {
if (source == null && target == null) {
return false;
} else {
return true;
}
}
public void setSource(Node newSource) {
source = newSource;
}
public void setEdge(Edge newEdge) {
edge = newEdge;
}
protected Edge getEdge() {
return edge;
}
public void setTarget(Node newTarget) {
target = newTarget;
}
}
|
/**
Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.
**/
export interface Revision_Test {
run_all();
run_test(id:number);
}
export interface CESP_Test_Info {
url:string;
window_size:number;
baseline:number;
percentage:number;
margin:number;
warning_timeframe:number; //Timeframe to get previous warnings to determine blocks, in days
warning_threshold:number;
revID_list:Array<number>;
} |
Philadelphia wants to become the first U.S. city to allow supervised drug injection sites as a way to combat the opioid epidemic, officials announced Tuesday, saying they are seeking outside operators to establish one or more in the city.
Safe injection sites are locations where people can shoot up under the supervision of a doctor or nurse who can administer an overdose antidote if necessary. Critics have argued the sites may undermine prevention and treatment, and seem to fly in the face of laws aimed at stopping use of deadly illicit drugs.
Philadelphia has the highest opioid death rate of any large U.S. city. More than 1,200 people fatally overdosed in Philadelphia in 2017, one-third more than 2016.
The city hopes to hear from operators interested in setting up the injection sites — which they are calling comprehensive user engagement sites — where the city would provide outreach services.
Officials from Philadelphia visited Seattle and safe injection sites in Vancouver, where Farley said they have reduced overdose deaths, the spread of diseases like HIV and hepatitis C, and created safer neighbourhoods that are free of used-needle litter.
It’s not clear how the federal government would respond if Philadelphia gets a safe-injection site. The U.S. Department of Justice declined to comment on the plan. Nearly three months ago, President Donald Trump declared the U.S. opioid crisis a public health emergency.
Mayor Jim Kenney wasn’t at the news conference but Farley said the Democrat supports the recommendation.
“This crisis requires us to think differently and comprehensively about how to reach everybody impacted by the opioid crisis,” the Democrat said.
House Speaker Mike Turzai, who is running for the Republican nomination to challenge Democratic Gov. Tom Wolf, called Philadelphia’s safe injection plan misguided and a violation of federal law. |
export interface Event {
from: string,
to: string,
task: string,
required?: boolean
}
export interface Subject {
abr: string,
name: string,
class?: string,
color?: string,
items?: Array<Event>
} |
//Na saida verifica se quer salvar
private void doExit() {
if (hasChanged) {
int state = JOptionPane.showConfirmDialog(this,
"O Arquivo foi moficado. Quer salva antes de sair?");
if (state == JOptionPane.YES_OPTION) {
saveFile();
} else if (state == JOptionPane.CANCEL_OPTION) {
return;
}
}
System.exit(0);
} |
Cooperative optimal control: broadening the reach of bio-inspiration Inspired by the process by which ants gradually optimize their foraging trails, this paper investigates the cooperative solution of a class of free final time, partially constrained final state optimal control problems by a group of dynamical systems. We propose an iterative, pursuit-based algorithm which generalizes previously proposed models and converges to an optimal solution by iteratively optimizing an initial feasible trajectory/control pair. The proposed algorithm requires only short-range, limited interactions between group members, avoids the need for a global map of the environment in which the group evolves, and solves an optimal control problem in small pieces, in a manner which will be made precise. The performance of the algorithm is illustrated in a series of simulations and laboratory experiments. |
News that Russia is working in cooperation with Iran and Iraq to back the regime of Syrian President Bashar Assad signals a continuing collapse of President Barack Obama's foreign policy, says former House Speaker Newt Gingrich.
"You have Russia, Iran and Iraq working together with Syria. All these are things that three or four years ago the president would have deeply opposed," Gingrich said Monday on Fox News Channel's "On the Record with Greta Van Susteren." "Now he is going to have to accommodate a reality that he can't change."
Obama's famous "red line" warning issued to Assad in 2012 against using chemical weapons went unheeded and Syria wasn't punished for breaking it a year later.
It was the beginning of a steady decline of American influence in the Middle East, Gingrich said.
"The Iranians have been trying to develop a regional hegemony. The Russians have become their ally. What you are seeing is a tremendous shift of the power away from the United States and Western Europe towards Russia and Iran," he said. "And it's a strategic defeat – a very dramatic defeat in historical terms."
Putin now intends to cooperate with Iran and sell weapons to Iraq, Gingrich said. "If we want to hang around, that's fine. We just don't matter very much to him." |
Multimodal imaging of micron-sized iron oxide particles following in vitro and in vivo uptake by stem cells: down to the nanometer scale. In this study, the interaction between cells and micron-sized paramagnetic iron oxide (MPIO) particles was investigated by characterizing MPIO in their original state, and after cellular uptake in vitro as well as in vivo. Moreover, MPIO in the olfactory bulb were studied 9 months after injection. Using various imaging techniques, cell-MPIO interactions were investigated with increasing spatial resolution. Live cell confocal microscopy demonstrated that MPIO co-localize with lysosomes after in vitro cellular uptake. In more detail, a membrane surrounding the MPIO was observed by high-angle annular dark-field scanning transmission electron microscopy (HAADF-STEM). Following MPIO uptake in vivo, the same cell-MPIO interaction was observed by HAADF-STEM in the subventricular zone at 1week and in the olfactory bulb at 9months after MPIO injection. These findings provide proof for the current hypothesis that MPIO are internalized by the cell through endocytosis. The results also show MPIO are not biodegradable, even after 9months in the brain. Moreover, they show the possibility of HAADF-STEM generating information on the labeled cell as well as on the MPIO. In summary, the methodology presented here provides a systematic route to investigate the interaction between cells and nanoparticles from the micrometer level down to the nanometer level and beyond. |
/**
* Copyright 2013 <NAME><<EMAIL>>
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 chess.utils;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class MusicPlayer {
private Clip clip = null;
public MusicPlayer() {
try {
clip = AudioSystem.getClip();
// File soundFile = new File("res/sound/qq/back.mid");
File soundFile = new File("res/sound/bgmusic.wav");
// / AudioInputStream inputStream =
// AudioSystem.getAudioInputStream(
// Main.class.getResourceAsStream("/path/to/sounds/" +
// url));
AudioInputStream inputStream = AudioSystem
.getAudioInputStream(soundFile);
clip.open(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeMusic() {
clip.stop();
}
public void playMusic() {
clip.loop(-1);
}
}
|
Beautiful Ivory town home ready for new home owners. This home features main floor living with room to grow in the finished basement. Home is upgraded through out and has great views. Come see all the amenities that homeowners enjoy in Hidden Valley. |
n = int(input())
happy = 0
if n%500 == 0:
print(2*n)
else:
while n > 0:
if n == 0:
break
n-=500
if n<0:
n+=500
n-=5
if n<0:
n+=5
break
else:
happy+=5
else:
happy+=1000
print(happy)
|
Milk-fed calves: 2. The effect of length of milk feeding period and milk intake upon herbage intake and performance of grazing calves SUMMARY Forty-eight Hereford Friesian steer calves purchased at 710 days of age were reared on reconstituted milk substitute and groups of 12 were weaned at 86, 128, 170 or 212 days. Six calves at each weaning age were fed high (H) and low (L) quantities of milk normally associated with 240-day lactation yields of 2000 or 1000 kg. Calves were housed until day 63 of the experiment and then strip-grazed on swards of Loliun perenne with a daily allocation of herbage dry matter equivalent to 60 g/kg LW. Herbage intake per unit live weight prior to weaning was consistently greater for the calves receiving low quantities of milk. Following weaning there was a rapid rise in herbage intake towards a maximum of 30 g OM/kg LW when sward conditions were non-limiting. The amount of milk fed prior to weaning affected herbage intake after weaning, and H groups did not achieve similar intakes to their L contemporaries until some weeks after weaning. The H groups grew faster from birth to weaning than the L groups but they experienced a more severe check in live-weight gain after weaning which nullified the advantage of better weight gains between the start of the grazing period and weaning. In consequence, there was no significant effect of the quantity of milk consumed prior to weaning upon live-weight gain during the grazing season. The results indicate a marked benefit from distributing a given quantity of milk over a longer feeding period as similar growth rates occurred for the H86 v. L128, H128 v. L170 and H170 v. L212 groups. Calves receiving milk consumed less herbage and spent a smaller proportion of the day grazing than weaned contemporaries, which suggests that metabolic rather than physical or behavioural factors are likely to limit their intake. |
Cryopreservation of sievers wormwood (Artemisia sieversiana Ehrh. Ex Willd.) seeds by vitrification and encapsulation Abstract Artemisia sieversiana is being used for the medicinal purpose, there are not many conservation objects, and the species is registered as a rare plant in Korea. There is also no research on the preservation of A. sieversiana seeds. In this paper, we investigated the preservation of seeds using cryopreservation. The vitality and germination rate of seeds were investigated with pretreatment, vitrification, and encapsulation. The initial germination rate of the seeds was 95%. PVS3 solution treated for 60min showed the highest vitality, and germination rate. When encapsulation, both vitality and germination rate decreased. Changes in vitality rate during storage period were measured. As a result, the seed-maintained vitality when the vitrification solution used. Encapsulation is unavailable because of too much change. Therefore, seeds can be safely preserved without deterioration of vitality at cryopreservation by using PVS 3 solution and it will be helpful in future studies. Introduction The common species, Artemisia sieversiana Ehrh. Ex Willd is an annual or biennial herbaceous rhizome plant of the Compositae family and grows in sandy clay, moist habitats, and distributes. A. sieversiana is a plant belonging to Artemisia, which is distributed in Korea, Japan and China. The plant grows up to 150 cm long and the stem is thick and straight, and it grows in the field. It has been used for the treatment of outbreak, bronchitis, tonsillitis, dermatitis, mastitis, hepatitis, and urinary inflammation (Park and Chung 2013). The aerial parts of A. sieversiana afforded, in addition to b-sitosterol, stigmasterol and daucosterol, two novel lignans as well as one known and three new guaianolides (). A. sieversiana possesses insecticidal activity against the maize weevil Sitophilus zeamais (). Germplasm preservation plays an important role in the maintenance of biodiversity and avoidance of genetic erosion. It has been amply stated that germplasm preservation is valuable not only for plant improvement and utilization for food, fiber, and medicinal crops, but also for conservation of rare and endangered species (Iriondo and Hond 2008). Cryopreservation has long been considered an important tool for the long-term storage of plant germplasm (). In vitro culture technology is an alternative to seed banking and is a good way to cryopreserve plant somatic cells or plant tissues for long-term storage. Cryopreservation can safely and cost-effectively preserve plant genetic resources (Engelmann 2004). In addition, cryopreservation technology can be applied to simple and broad resource plants, with minimal space and maintenance, and long-term preservation of the desired plant material (Kaviani 2011). Cryopreservation technology was developed for vitrification (;) and encapsulation-dehydration technology (Fabre and Dereuddre 1990;). This technique allows storage at very low temperatures by removing frozen cell osmosis through exposure to concentrated vitrification solutions (vitrification procedures) or air drying (encapsulation-dehydration procedures) rather than freezing. Simple and reliable cryogenic protocols such as simple freezing, vitrification, and encapsulation-dehydration have been proven and the number of cryopreserved species or cultivars has increased markedly over the last few years. Successful cryopreservation of embryos has been reported in many plants (;;;). Very limited studies have been carried out on cryopreservation of Artemisia and plants. Artemisia annua L Callus of two lines was treated with three kinds of cryoprotectants, and callus preservation, regeneration field and plant differentiation were reported (). The shoot-tips of Artemisia herba-alba, native to arid and semi-arid climates, were found to have a survival rate of 68% through vitrification and encapsulation (). There have been no cryopreservation studies comparing vitrification and encapsulation methods, respectively. This study was conducted to investigate the optimal cryopreservation conditions for A. sieversiana seed preservation, and to investigate the effect of cryopreservation on plant growth after germination. Plant material Seeds of A. sieversiana Ehrh. ex Willd. were obtained from the Korea National Arboretum, South Korea. The seeds washed with distilled water and stored in a plastic bag with silica gel at 4 C for 6 months. The experiments were carried out at Gyeongsang National University, Jinju in 2017. Before the experiment started, the initial rate of seed germination nad moisture content of seed were 95% and 9%, respectively. The surface of seed was sterilized by immersion in ethanol 70% for 1 min and sodium hypochlorite 1.0% for 1 min. The seeds were rinsed three times with sterile distilled water. In vitro cultivation of cryoprotectant treated seed Surface-sterilized seeds were suspended in MS (Murashige and Skoog 1962) liquid medium with different concentration of sucrose for 0, 0.3, 0.5, 0.7 M for 30 min and pH 5.6 for 0 $ 60 min. Vitrified and encapsulated seeds were cultured on solidified MS medium supplemented with 3% sucrose, 0.2% gel-lite, and pH 5.6. Cultures were maintained under a 16/8(light/dark) hours at 25 C. Vitrification of seed Some modified methods were applied for vitrification (). Seeds were transferred into 1.8 ml cryotube, and then treated with or without loading solution (LS) with 2 M glycerol and 0.4 M sucrose, pH 5.6 at 25 C for 30 min. Following removal of LS, the seeds were dehydrated with plant vitrification solution 2 (PVS2) or plant vitrification solution 3 (PVS3). The PVS2 consisted of 30% glycerol, 15% ethylene glycol, and 15% DMSO in liquid MS medium with 0.4 M sucrose and pH 5.6 for 0 $ 60 min. The PVS3 consisted of 50% glycerol, 50% ethylene glycol in liquid MS medium with 0.4 M sucrose, and pH 5.6 for 0-60 min. The seeds were suspended into 1 ml of vitrification solution in 1.8 ml cryotube and then directly plunged into liquid nitrogen. After storage for period (0, 1 day, 1 week, 2 week, 1 month), the cryotubes were rapidly warmed in a water bath at 40 C for 1 min. Vitrification solution was removed from cryotube and then 1 ml of liquid MS medium supplemented with 1.2 M sucrose were added to each tube and held for 30 min. Encapsulation of seed Encapsulation method has been used with some modifications to the. Seeds were suspended in MS medium supplemented with 3% Naalginate and 0.6 M sucrose for 1 h with slow agitation. Then, seeds were dropped into MS medium containing 100 mM CaCl 2 and 0.1 M sucrose for 1 h with slow agitation. Seeds were washed three times with sterile distilled water. Following removal of distilled water, the capsules were supplemented with 0.75 M sucrose in MS medium and pH 5.6 for 0-3 h. Encapsulation seeds were transferred to empty open petri dishes and desiccated in the laminar flow chamber, then directly plunged into liquid nitrogen (LN). After storage for period (0, 1 day, 1 week, 2 week, 1 month), the cryotubes were rapidly warmed in a water bath at 40 C for 1 min. TTC staining for viability assessment The viability of the seeds following each treatment was evaluated using the 2,3,5-triphenyltetrazolium chloride (TTC) test (). Seeds were incubated in 1% TTC solution for 1 day at 27 ± 2 C in the dark. The number of embryos stained by TTC was counted, and the percentage of TTC-stained seeds represented the survival rate. Thawing and plantlet formation After leaving for 60 min in LN, cryovials were removed and rapidly rewarmed in a 40 Cwater bath for 1 min. Cryopreservation solutions were removed from cryovials with a sterile disposable transfer pipette under a laminar flow hood. Seeds were rinsed with 1 = 2 strength MS culture medium 1.2 M sucrose (pH 5.7) for 15 min, transferred to Petri dishes containing 1 = 2 strength MS medium 0.06 M sucrose (pH 5.7) solidified with 7.0 g/l agar and incubated under controlled environmental conditions (27 ± 2 C; 60 mmol m 2 s 1 ; 16 light/8 dark hours). Petri dishes were visually monitored weekly for seed germination. Germination percentage was assessed from week 4 through 12 for the control and different treatments by counting the number of germinated seeds under a microscope. Seed survival was assessed by counting the number of germinated seeds that survived and which continued growing. Rooting and acclimation The in vitro cultured plants were taken out of the culture bottle and then the agar was removed from the roots. Roots were washed with distilled water and transferred to a plastic pot containing sterilized artificial soil for them to acclimate in the greenhouse. Statistical analysis The survival rate and germination rate of the seeds were analyzed by Duncan's multiple test method and significance level was 5%. Statistical analysis was performed using SPSS statistics 23. (IBM, Corp, USA) Seed viability and germination according to sucrose pretreatment Sucrose concentration significantly influenced the seed viability of A. sieversiana seeds (Table 1). Seed viability was 64% in non-sucrose treatment, and seed viability was increased in sucrose treatment. The viability of A. sieversiana seeds was highest (93.2% at 0.3 M), and 73% and 82% at 0.5 M and 0.7 M treatment, respectively. The seed germination rate of A. sieversiana varied according to sucrose concentration. After 4 weeks of sucrose treatment, the highest germination rate was in 0.3 M, followed by 0.5 M and 0.7 M. However, the germination rate of sucrose untreated seeds was much lower than that of treated seeds. The seed germination rate in sucrose treatments was different according to germination period. Seed germination started after 1 week of incubation with 0.3 M sucrose treatment. However, seed germination at 0.5 M and 0.7 M sucrose treatment started after 4 weeks of culture. The treatment time with sucrose did not affect seed viability. Seed viability immediately before sucrose treatment was 64%, but it increased to 90% after 10 and 30 min of treatment. And it was slightly lower at 80% after 60 min respectively. Sucrose treatment time also affected seed germination rate (Table 2). Seed germination started 1 week after incubation for 30 min and 60 min, but there was no difference in the seed germination rate after that. However, germination was not observed at 10 min treatment. Seed viability and germination rate after vitrification Vitrification solution affected seed viability (Table 3). Seed viability differed according to treatment time. Compared to the control, the vitality of the seed that treated solution increased. When each solution treated for 30 min, it showed the highest vitality. The PVS treatment time also affected seed germination rate. The germination rate of treated seeds was significantly higher than those without treatment. Seed germination rate increased slightly with longer PVS solution treatment time. The germination rate increased rapidly after 2 weeks of incubation for 10 min in PVS2, but there was no difference thereafter. After 30 min treatment, germination rate increased from 1 week after culture and gradually increased thereafter. The highest germination rate was at 60 min after incubation, with 85% germination in 2 weeks. The germination rate at 120 min treatment showed low germination rate after 1 week of culture, but high germination rate after 2 weeks stored. Seed germination rate with PVS3 treatment was higher than that of PVS2 treatment. The highest germination rate was recorded at 60 min. Germination occurred after one week in all treatments, but there was no difference in germination rate. Seed viability and germination rate of cryopreserved seeds in liquid nitrogen after vitrification The viability of the seeds was also significantly different according to the liquid nitrogen storage time (Table 4). Seed viability was lower in the treatment than in the control. The viability of the seeds decreased as the cryopreservation time increased. The germination rate of seeds cryopreserved in liquid nitrogen did not vary according to liquid nitrogen storage time. Seeds that cryopreserved in liquid nitrogen germinated in 1 week of incubation. Seed germination showed little difference due to increasing liquid nitrogen storage time. Seed viability and germination rate according to encapsulation When encapsulated seeds were treated with sucrose solution, seed viability was also affected ( Table 5). The vitality of the encapsulated seeds decreased with the treatment time. However, there were no trends over time. The germination rate of seeds encapsulated in liquid nitrogen did not differ according to incubation period. 1 week treatment showed highest germination rate but the control has highest viability with no germination. The preservation of encapsulated seeds in liquid nitrogen also affected seed viability ( Table 6). The vitality of the encapsulated seeds was not observed in liquid nitrogen due to storage time. When encapsulated seeds were stored in liquid nitrogen, the seeds germination rate was also affected. There was no difference in germination rate of the encapsulated seeds after 3 days of culture. The germination rate was higher than that of 30 min treatment on the 1 h and 3-day treatments. Seeds stored in liquid nitrogen successfully grew after germination (Figure 1). Germinated plants rooted, and multiple shoots were induced. Growth of seedling stored in LN The fresh weight of the germinated plants showed differences growth rate between the plants stored in LN and those not stored in LN (control). The seedlings treated with PVS2 and PVS3 also showed differences in growth (Figure 2). The fresh weight of A. sieversiana seedlings was highest in the control. As the treatment time increased, the actual growth of seedlings decreased. Seedlings treated in PVS3 for 10 min had favorable growth, while PVS2 treated seedlings showed low growth. Comparison of seedling growth between vitrification and encapsulation Seedlings obtained from vitrified and encapsulated seeds showed very different growth (Figure 3). The growth of young seedlings was better than that of vitrified seedlings. The fresh weight of seedlings was highest at 0 min after cryoprotectant was added by vitrification with the liquid nitrogen not treated. This is much higher than for other treatments. On the other hand, the encapsulation method showed the lowest value at 0 min, and the 3 days treatment time was the best, and it was judged that the liquid nitrogen treatment time did not have a great influence on the live weight. Discussion Pre-treatment with cryoprotectants showed an improvement of the viability and germination of A. sieversiana. Our results showed that pretreatment of 0.3 M sucrose increased seed viability and germination rates. Also, pretreatment time of sucrose affected seed germination rate. Pretreatment with 0.3 M sucrose for 3 days before vitrification increased the survival rate of immature seeds of 3-4 MAP (Months after pollination) when cooled in liquid nitrogen during the vitrification process (). However, the difference was not statistically significant as has been previously shown for the mature zygotic embryos of the same species (). The vitrification solution also affected seed viability and germination rate. The vitrification method involves treating the sample with a high concentration of anti-freeze solution, and PVS2 (), and PVS3 (), which induces intracellular dehydration and reduces the chance of intracellular ice formation in liquid nitrogen. With the vitrification method, pretreatment with a medium containing a high level of sorbitol and sugar has been reported to be extremely useful in improving the survival of cryopreserved cells and tissues (;). PVSs solution composed of different concentrations and combinations of the four main components: dimethyl-sulfoxide, sucrose, glycerol and ethylene glycol. The cryoprotective substances should fulfil several basic parameters, such as cell permeability, viscosity, toxicity and the minimum concentration necessary for vitrification, which eliminates the formation of ice crystals. The increased efficiency of vitrification methods was achieved by treating plants in the pre-cultivation step before cryopreservation of plant shoot tips in so called LS (;). Vitrification protocols have been used for the cryopreservation of mature and immature seeds of Doritaenopsis pulcherrima (Thammasiri 2000), mature seeds and pollen of Dendrobium hybrids (), seeds of Phaius tankervilleae (), seeds of Cymbidium species (). The results of this study showed that the encapsulation method was worse than the vitrification method in seed viability and seed germination. All the treatments decreased seed germination rate and viability. The results showed that the germination percentage of cryopreserved seeds treated with loading solution was higher than for the untreated seeds, which is like the findings of Jitsopakul et al.. The growth of seedlings that emerged from cryopreserved seeds differed between the two methods (encapsulation and vitrification). Growth of plants resulting from seeds cryopreserved by encapsulation was better than for vitrification method. These results indicate that the cryopreservation method of the seeds is important, but the growth of the plant after germination should also be considered. Cryopreserved seeds are subject to physical, chemical and physiological stress. The growth of plants that emerged from cryopreserved seeds was lower than that of the control, which seems to be due to cryoinjury. In addition, the difference of further growth of plants obtained from the cryopreservation method is considered due to physico-chemical stress. We have succeeded in cryopreservation of mature seeds of A. sieversiana, a useful resource plant. The results of this study can be widely used for cryopreservation of other recalcitrant seeds of useful plants as well as elite cultivar of A. sieversiana. Disclosure statement No potential conflict of interest was reported by the authors. Funding This work was supported by the Research program (Determination of pre-treatment conditions for cryopreservation of recalcitrant seed (terrestrial orchid)) funded by Korea National Arboretum. |
Improving Interactions: The Effects of Implementing the Fight-Free Schools Violence Prevention Program The purpose of this study was to determine whether the Fight-Free Schools violence prevention process had an effect on the frequency of aggressive acts of elementary school students. Participants included approximately 600 students ranging from Kindergarten to 5th grade in a suburban school in the Midwestern United States. Data were collected over a 2-year period on the frequency and type of aggressive acts committed during the school day. Year 1 baseline was compared to data from Year 2 to determine whether any differences existed after Fight-Free Schools was implemented. Results indicated a 60% decrease in the overall number of aggressive acts from Year 1 to Year 2. In addition, there were decreases in each specific type of aggressive act that ranged from 25% to 84%. |
A 44 point to point router based on microring resonators A new 44 point to point router is investigated with the transfer matrix method. Its routing paths and low loss of power are successfully demonstrated. The proposed design is easily integrated to a larger scale with less microring resonators, and the power loss from the input port to the output port is demonstrated to be lower than 10%. All of the microrings designed here have the identical radii of 6.98 m, and they are all in resonance at a wavelength of 1550 nm. Both the gap between the microring and the bus waveguide and the gap between two neighbouring rings are 100 nm. The width of bus waveguide as well as the microrings is designed to be 200 nm. Free spectral range (FSR) is supposed to be around 17 nm based on the parameters above. A large extinction ratio (ER) is also achieved, which shows the high coupling efficiency to a certain extent. Thermal tuning is employed to make the microrings be in resonance or not, not including the two microring resonators in the middle. In other words, the two microrings are always in resonance and transport signals when the input signals pass by them. Hence, only two microrings are needed to deal with if one wants to route a signal. Although this architecture is blocking and not available for multicasting and multiplexing, it is a valuable effort that could be available for some optical experiments on-chip, such as optical interconnection, optical router. |
1. Cool Off on One of Transylvania County’s Waterfall Hikes
If you don’t mind working for your waterfalls, lace up your hiking boots and journey to Transylvania County. The hikes are strenuous, but the payoff is sublime. Click here for a list of the waterfalls.
2. Vacation in a Secluded and Luxurious Yurt
A yurt resort overlooking Fontana Lake offers campers far more than s’mores. Read more about these unique homes and why we recommend experiencing the Nantahala from the plush digs of a yurt.
3. Enjoy a Memorable Meal at One of These Hot Spots
You don’t have to go far in any direction to find amazing chefs, meals, and restaurants in western North Carolina. Our list has your cravings covered. See the 19 western NC eateries we suggest you try this summer.
Don’t Miss Our Annual Mountain Issue Every October, we release our highly-anticipated NC Mountain Issue. Don’t miss out! Use the link below to save $5 on a subscription today.
Subscribe Now & Save
4. Hike the Roan Balds and Other Sections of the Appalachian Trail
If you’re not able to make the full journey on the Appalachian Trail, or if you’re looking for an exciting day or weekend hiking trip through the mountains, here are five of our favorite Appalachian Trail section hikes in North Carolina.
5. Venture Beyond Asheville
Beyond the lovable quirkiness of downtown Asheville, a different kind of magic is waiting for you. See the list of towns we suggest you visit on your next trip out west. |
#include "hardware-test.hpp"
#include "graphics/color.hpp"
#include "hardware/gpio.h"
#include <cmath>
using namespace blit;
const uint8_t STATUS_V_SPACING = 10;
const uint32_t VBUS_DETECT_PIN = 2;
const uint32_t CHARGE_STATUS_PIN = 24;
const int16_t notes[2][384] = {
{ // melody notes
147, 0, 0, 0, 0, 0, 0, 0, 175, 0, 196, 0, 220, 0, 262, 0, 247, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 175, 0, 0, 0, 0, 0, 0, 0, 175, 0, 196, 0, 220, 0, 262, 0, 330, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 349, 0, 0, 0, 0, 0, 0, 0, 349, 0, 330, 0, 294, 0, 220, 0, 262, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 247, 0, 0, 0, 0, 0, 0, 0, 247, 0, 220, 0, 196, 0, 147, 0, 175, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0,
147, 0, 0, 0, 0, 0, 0, 0, 175, 0, 196, 0, 220, 0, 262, 0, 247, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 175, 0, 0, 0, 0, 0, 0, 0, 175, 0, 196, 0, 220, 0, 262, 0, 330, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 349, 0, 0, 0, 0, 0, 0, 0, 349, 0, 330, 0, 294, 0, 220, 0, 262, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 247, 0, 0, 0, 0, 0, 0, 0, 247, 0, 220, 0, 196, 0, 147, 0, 175, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0,
147, 0, 0, 0, 0, 0, 0, 0, 175, 0, 196, 0, 220, 0, 262, 0, 247, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 175, 0, 0, 0, 0, 0, 0, 0, 175, 0, 196, 0, 220, 0, 262, 0, 330, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 349, 0, 0, 0, 0, 0, 0, 0, 349, 0, 330, 0, 294, 0, 220, 0, 262, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 247, 0, 0, 0, 0, 0, 0, 0, 247, 0, 262, 0, 294, 0, 392, 0, 440, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
},
{ // rhythm notes
294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 392, 0, 523, 0, 659, 0, 523, 0, 392, 0, 523, 0, 659, 0, 523, 0, 698, 0, 587, 0, 440, 0, 587, 0, 698, 0, 587, 0, 440, 0, 587, 0, 523, 0, 440, 0, 330, 0, 440, 0, 523, 0, 440, 0, 330, 0, 440, 0, 349, 0, 294, 0, 220, 0, 294, 0, 349, 0, 294, 0, 220, 0, 294, 0, 262, 0, 247, 0, 220, 0, 175, 0, 165, 0, 147, 0, 131, 0, 98, 0,
294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 392, 0, 523, 0, 659, 0, 523, 0, 392, 0, 523, 0, 659, 0, 523, 0, 698, 0, 587, 0, 440, 0, 587, 0, 698, 0, 587, 0, 440, 0, 587, 0, 523, 0, 440, 0, 330, 0, 440, 0, 523, 0, 440, 0, 330, 0, 440, 0, 349, 0, 294, 0, 220, 0, 294, 0, 349, 0, 294, 0, 220, 0, 294, 0, 262, 0, 247, 0, 220, 0, 175, 0, 165, 0, 147, 0, 131, 0, 98, 0,
294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 294, 0, 440, 0, 587, 0, 440, 0, 392, 0, 523, 0, 659, 0, 523, 0, 392, 0, 523, 0, 659, 0, 523, 0, 698, 0, 587, 0, 440, 0, 587, 0, 698, 0, 587, 0, 440, 0, 587, 0, 523, 0, 440, 0, 330, 0, 440, 0, 523, 0, 440, 0, 330, 0, 440, 0, 349, 0, 294, 0, 220, 0, 294, 0, 349, 0, 294, 0, 220, 0, 294, 0, 262, 0, 247, 0, 220, 0, 175, 0, 165, 0, 147, 0, 131, 0, 98, 0,
},
};
const Pen LED_COLOUR[3] = {
Pen(255, 0, 0),
Pen(0, 255, 0),
Pen(0, 0, 255)
};
uint16_t beat = 0;
uint32_t been_pressed;
void init() {
set_screen_mode(ScreenMode::lores);
gpio_init(VBUS_DETECT_PIN);
gpio_set_dir(VBUS_DETECT_PIN, GPIO_IN);
gpio_init(CHARGE_STATUS_PIN);
gpio_set_dir(CHARGE_STATUS_PIN, GPIO_IN);
channels[0].waveforms = Waveform::SQUARE;
channels[0].attack_ms = 16;
channels[0].decay_ms = 168;
channels[0].sustain = 0xafff;
channels[0].release_ms = 168;
channels[1].waveforms = Waveform::SQUARE;
channels[1].attack_ms = 38;
channels[1].decay_ms = 300;
channels[1].sustain = 0;
channels[1].release_ms = 0;
}
void render(uint32_t time) {
char text_buf[100] = {0};
bool button_a = buttons & Button::A;
bool button_b = buttons & Button::B;
bool button_x = buttons & Button::X;
bool button_y = buttons & Button::Y;
bool dpad_l = buttons & Button::DPAD_LEFT;
bool dpad_r = buttons & Button::DPAD_RIGHT;
bool dpad_u = buttons & Button::DPAD_UP;
bool dpad_d = buttons & Button::DPAD_DOWN;
for(int b = 0; b < screen.bounds.w; b++){
for(int v = 0; v < screen.bounds.h; v++){
screen.pen = hsv_to_rgba(float(b) / (float)(screen.bounds.w), 1.0f, float(v) / (float)(screen.bounds.h));
screen.pixel(Point(b, v));
}
}
screen.pen = dpad_r ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("R", minimal_font, Point(25, 15), false, center_center);
screen.pen = dpad_d ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("D", minimal_font, Point(15, 25), false, center_center);
screen.pen = dpad_u ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("U", minimal_font, Point(15, 5), false, center_center);
screen.pen = dpad_l ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("L", minimal_font, Point(5, 15), false, center_center);
screen.pen = button_a ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("A", minimal_font, Point(screen.bounds.w - 5, 15), false, center_center);
screen.pen = button_b ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("B", minimal_font, Point(screen.bounds.w - 15, 25), false, center_center);
screen.pen = button_x ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("X", minimal_font, Point(screen.bounds.w - 15, 5), false, center_center);
screen.pen = button_y ? Pen(255, 0, 0) : Pen(128, 128, 128);
screen.text("Y", minimal_font, Point(screen.bounds.w - 25, 15), false, center_center);
//LED = hsv_to_rgba(time / 50.0f, 1.0f, 1.0f);
LED = LED_COLOUR[(time / 1000) % 3];
Point location(5, screen.bounds.h - (8 * STATUS_V_SPACING));
std::string label = "";
screen.pen = Pen(255, 255, 255);
uint32_t bit = 256;
while(bit > 0) {
bit >>= 1;
switch(bit) {
case Button::A:
label = "A ";
break;
case Button::B:
label = "B ";
break;
case Button::X:
label = "X ";
break;
case Button::Y:
label = "Y ";
break;
case Button::DPAD_UP:
label = "UP ";
break;
case Button::DPAD_DOWN:
label = "DOWN ";
break;
case Button::DPAD_LEFT:
label = "LEFT ";
break;
case Button::DPAD_RIGHT:
label = "RIGHT";
break;
}
if (been_pressed & bit) {
label += " OK";
}
screen.text(label, minimal_font, location, false);
location.y += STATUS_V_SPACING;
}
bool charge_status = gpio_get(CHARGE_STATUS_PIN);
bool vbus_connected = gpio_get(VBUS_DETECT_PIN);
location = Point(screen.bounds.w / 2, screen.bounds.h - (8 * STATUS_V_SPACING));
label = "CHG: ";
label += charge_status ? "Yes" : "No";
screen.text(label, minimal_font, location);
location.y += STATUS_V_SPACING;
label = "VBUS: ";
label += vbus_connected ? "Yes" : "No";
screen.text(label, minimal_font, location);
}
void update(uint32_t time) {
static uint16_t tick = 0;
static uint16_t prev_beat = 1;
been_pressed |= buttons.pressed;
beat = (tick / 8) % 384; // 125ms per beat
tick++;
if (beat == prev_beat) return;
prev_beat = beat;
for(uint8_t i = 0; i < 2; i++) {
if(notes[i][beat] > 0) {
channels[i].frequency = notes[i][beat];
channels[i].trigger_attack();
} else if (notes[i][beat] == -1) {
channels[i].trigger_release();
}
}
}
|
/**
*
* Created by legend on 2018/2/6.
*/
public class Album implements Serializable{
private int id;
private String album_name;
private long artist_id;
public long getArtist_id() {
return artist_id;
}
public void setArtist_id(long artist_id) {
this.artist_id = artist_id;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
private String artist;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAlbum_name() {
return album_name;
}
public void setAlbum_name(String album_name) {
this.album_name = album_name;
}
} |
Potential Assessment of Oleaginous Fungi for Sustainable Biodiesel Production: Screening, Identification and Lipid Production Optimization The present work, aiming to exploit oleaginous fungi for biodiesel production. Ten fungal strains were isolated from two petroleum polluted soil samples and screened for their abilities to accumulate lipid. Lipid rich three species viz, Aspergillus terreus, Aspergillus niger and Aspergillus flavus were found to be the highest lipid producers. Potential isolates were identified at the species level by morphological (macroscopic and microscopic) examination and molecularly confirmed by using 18S rRNA gene sequencing. Improvement of lipid accumulation by optimization of various parameters of culture conditions. The results reported clearly that the most suitable medium conditions for highest lipid production (38.33%) of Aspergillus terreus as the most potent lipid producer composed of 5% sucrose, 0.5 g/L ammonium nitrate with initial pH 6.0, after seven days of incubation in a static condition. The three promising fungal isolates have been taken for fatty acids analysis by gas chromatograph (GC) after transesterification. Fatty acid methyl esters (FAME) profile indicated the presence of higher saturated fatty acid fractions compared to polyunsaturated fatty acids. The total concentration of fatty acids was 107.98, 38.29, and 37.48 mg/100g of lipid accumulated by A. terreus, A. niger and A. flavus, respectively. Gas chromatograph analysis of A. terreus lipid indicated that oleic acid (C18:1, 18.51%) was the most abundant fatty acid, followed by stearic acid (C18:0, 15.91%) and Myristic acid (C14:0, 14.64%), respectively. Therefore, fatty acid profile of A. terreus has confirmed its potentiality as feedstock for producing lipid for biodiesel manufacturing. |
from enum import Enum
class ColorSpace(Enum):
HSV = "HSV",
RGB = "RGB"
class Color:
"""
Describes a color and its color space.
"""
def __init__(self, color_space: ColorSpace, components: list):
"""
Initialize color.
:param color_space: Color space of the color.
:param components: Components of the color.
"""
assert isinstance(color_space, ColorSpace)
assert isinstance(components, list)
self._color_space = color_space
self._components = components
@property
def color_space(self) -> ColorSpace:
"""
Retrieve colorspace of the color.
:return: Colorspace of the color.
"""
return self._color_space
@property
def components(self) -> list:
"""
Retrieve color components.
:return: Color components.
"""
return self._components
def to_dict(self):
return {
"color_space": self.color_space.name,
"components": self.components
}
|
Debi Daviau is president of the Professional Institute of the Public Service of Canada (PIPSC), which represents some 55,000 scientists and other professionals, including more than 13,000 federal IT workers.
The tears started almost before she'd begun to speak. We were standing outside the Tunney's Pasture federal office complex in Ottawa during National Public Service Week, normally an occasion to celebrate working in the public service. It was a pay week. But the long-unresolved problems with the Phoenix pay system meant many weren't in a mood to celebrate and the woman I was speaking to had just returned from maternity leave. Having fought to recover eight months of unpaid maternity benefits, she had now learned she hadn't received more than two years of retroactive pay. As I handed her a "Fix Phoenix" protest button, the gesture seemed suddenly inadequate. So we hugged instead.
Ottawa has a problem. It's called Phoenix, after IBM's brand-name payroll software that has caused more than a quarter of the public service to be paid too little, too much, or (too often) not at all. But that's just its corporate name. The real name for Ottawa's problem is "outsourcing" and its playing havoc with much more than the public-service payroll.
A massive project to consolidate government e-mail accounts, contracted to tech giants Bell and CGI, is years behind schedule and untold millions of dollars over budget. A project outsourced to Adobe to bring all government websites under one Canada.ca site is also overdue and over budget. And a proposal to migrate most government website content to private, for-profit, cloud-based servers is fraught with what IT workers I represent believe is a looming security risk to government and Canadians' data.
While the current government has been right to criticize the previous one for laying off hundreds of compensation staff before it rolled out Phoenix, it's the decisions around outsourcing such projects in the first place that demand a rethink.
Why weren't federal IT workers consulted on the implementation of Phoenix from the start? Worse, why was IBM allowed to use its own "test bed" – a staging area to catch system flaws before they're deployed – and not the Government of Canada's? Had the government's own test bed and IT workers been used, we could have warned the government the system was programmed to fail.
But, as we've so frequently been told since this fiasco began, it was too late to change course.
Shared Services Canada, the department tasked with supplying the IT needs of 42 federal departments, has been the subject of no fewer than two important reports in the past year. Both were released this spring and reveal much about the doublethink behind Ottawa's decisions to outsource.
As if to add insult to injury, a report commissioned by Treasury Board last August from consultants Gartner Canada Co. proposes, among other things, spinning Shared Services off into a separate "agency, Crown corporation, strategic partnership, [or] joint venture" and outsourcing on an even grander scale. Among its panel of experts was a former vice-president of IBM.
Treasury Board President Scott Brison's frustration was on full display last month when, during a Senate finance committee meeting, he cautioned IBM about the risks to its reputation if it doesn't help fix Phoenix.
But his enthusiasm for even more outsourcing of federal government projects to small and mid-sized companies leaves one wondering if he's drawn the same lessons Shared Services employees have already learned.
Outsourcing within the public service should, by its nature, be short-term, limited and targeted to areas where missing expertise is quickly transferred to permanent employees. That means engaging federal IT workers at the start and promptly training those without the required expertise to take over, or hiring qualified new employees. To do otherwise is to undermine the very purpose of the public service.
That so many public services – from weather forecasts to processing OAS, CPP and EI cheques – depend on constant government IT services to ensure their delivery is a testament to the value of public employees themselves. Phoenix, by contrast, fails public servants routinely.
The Trudeau government may not have invented the problem of outsourcing, but since promising in its fiscal policy document of the 2015 election campaign to reduce spending on outside consultants to 2005-06 levels, spending on outsourcing has grown dramatically.
The official estimate for the current year is $12-billion, up from $10-billion just two years ago – the equivalent of as many as eight federal department budgets combined.
For companies eager to do business with the federal government, this is of course good news. For everyone else, and especially those affected by the disastrous results, it's enough to make you cry. |
KG135 Inhibits COX2 Expression by Blocking the Activation of JNK and AP1 in Phorbol EsterStimulated Human Breast Epithelial Cells Abstract: Ginsenosides, ingredients of ginseng, have a wide array of pharmacologic effects. Especially, ginsenosides Rk1, Rg3, and Rg5 derived from heatprocessed ginseng have been shown to possess substantial antitumorpromoting effects. KG135 is a formulated complex that contains several antitumorigenic ginsenosides, such as Rk1, Rg3, Rg5, Rk2, Rk3, Rs3, Rs4, Rs5, Rs6, Rs7, etc. The present article was aimed at evaluating the chemopreventive as well as antiinflammatory effects of KG135 in the human breast epithelial cell line (MCF10A). One of the wellrecognized molecular targets for chemoprevention is cyclooxygenase2 (COX2) that is abnormally upregulated in many premalignant and malignant tissues and cells. In this study, we found that KG135 inhibited COX2 expression in MCF10A cells stimulated with a prototype tumor promotor 12Otetradecanoylphorbol13acetate (TPA). Since the transcription factor activator protein1 (AP1) plays a role in tumor promotion and is also known to regulate COX2 induction, we attempted to determine the effect of KG135 on TPAinduced activation of AP1. Cotreatment with KG135 resulted in a decrease in TPAinduced DNA binding of AP1. In addition, KG135 inhibited TPAinduced phosphorylation of cJun Nterminal kinases (JNK) that regulates COX2 expression in MCF10A cells. The JNK inhibitor SP600125 attenuated COX2 expression in TPAtreated MCF10A cells. Taken together, the above findings suggest that KG135 inhibits TPAinduced COX2 expression in MCF10A cells by blocking the JNK/AP1 signaling pathway. |
<reponame>azh412/VirtualPianoBot
# Copyright (c) 2021 <NAME>
# Licensed under the MIT License
from termcolor import colored
print(colored("sheet name: ", green), end="")
inp = input()
file = []
has = 2
with open(f"sheets/{inp}.txt", "r") as f:
j = f.readlines()
for i in j:
for x in i.split():
for l in x:
if l == '[':
has = 1
break
x = x.strip("-")
if has == 2 and len(x) > 1:
x = ' - '.join(x[i:i + 1] for i in range(0, len(x), 1))
x = x.strip("[")
x = x.strip(']')
x = x.replace("|", "\n\n")
file.append(x)
has = 2
with open(f"sheets/{inp}.txt", "w") as f:
f.truncate(0)
with open(f"{inp}.txt", "a") as f:
for i in range(6):
f.write("\n")
for i in file:
f.write(i)
f.write(" ")
|
def parse_number_word(text):
for word in extract_words(text):
if word in NUMBER_WORDS:
return int(NUMBER_WORDS[word])
return None |
/*
* dirents_alloc
*
* Allocate a contiguous block of memory with all dirents in it.
*/
static dirent_t *dirents_alloc (disk_t *disk, uint32_t cluster)
{
uint32_t index;
uint32_t next_cluster;
uint32_t sector;
uint32_t sectors;
uint8_t *sectordata;
uint32_t datalen;
uint8_t *data;
dirent_t *d;
d = (typeof(d)) myzalloc(sizeof(*d), __FUNCTION__);
d->cluster = cluster;
sectors = dirent_total_sectors(disk, cluster);
if (!sectors) {
DIE("zero sized dirent");
}
d->dirents =
(typeof(d->dirents))
myzalloc(sector_size(disk) * sectors, __FUNCTION__);
data = (uint8_t*) d->dirents;
index = 0;
for (;;) {
if (cluster == 0) {
if (fat_type(disk) == 32) {
cluster = disk->mbr->fat.fat32.root_cluster;
sector = cluster_to_sector(disk, cluster - 2);
sectors = disk->mbr->sectors_per_cluster;
} else {
sector = sector_root_dir(disk);
sectors = root_dir_size_sectors(disk);
}
} else {
sector = cluster_to_sector(disk, cluster - 2);
sectors = disk->mbr->sectors_per_cluster;
}
d->sector[index] = sector;
d->sectors[index] = sectors;
datalen = sectors * sector_size(disk);
d->number_of_dirents += datalen / FAT_DIRENT_SIZE;
d->number_of_chains++;
sectordata = sector_read(disk, sector, sectors);
if (!sectordata) {
DIE("Failed to read sectors whilst reading block of dirents");
}
memcpy(data, sectordata, datalen);
data += datalen;
myfree(sectordata);
next_cluster = cluster_next(disk, cluster);
if (cluster_endchain(disk, next_cluster)) {
break;
}
cluster = next_cluster;
index++;
if (index >= MAX_DIRENT_BLOCK) {
ERR("too many directory chains");
break;
}
}
return (d);
} |
Non-Gaussian Limit Theorem for Non-Linear Langevin Equations Driven by L\'evy Noise In this paper, we study the small noise behaviour of solutions of a non-linear second order Langevin equation $\ddot x^\varepsilon_t +|\dot x^\varepsilon_t|^\beta=\dot Z^\varepsilon_{\varepsilon t}$, $\beta\in\mathbb R$, driven by symmetric non-Gaussian L\'evy processes $Z^\varepsilon$. This equation describes the dynamics of a one-degree-of-freedom mechanical system subject to non-linear friction and noisy vibrations. For a compound Poisson noise, the process $x^\varepsilon$ on the macroscopic time scale $t/\varepsilon$ has a natural interpretation as a non-linear filter which responds to each single jump of the driving process. We prove that a system driven by a general symmetric L\'evy noise exhibits essentially the same asymptotic behaviour under the principal condition $\alpha+2\beta<4$, where $\alpha\in $ is the ``uniform'' Blumenthal--Getoor index of the family $\{Z^\varepsilon\}_{\varepsilon>0}$. Introduction and motivation In this paper we study a non-linear response of a one-dimensional system to both external stochastic excitation and non-linear friction. In the simplest mathematical setting in the absence of external forcing, one can assume that the friction force is proportional to a power ( ∈ R) of the particle's velocity; that is, the equation of motion has the form t = −| t | sgn t. (1.1) This model covers such prominent particular cases as the linear viscous (Stokes) friction = 1, the dry (Coulomb) friction = 0, and the high-speed limit of the Rayleigh friction = 2 (see Persson ; Popov ; Sergienko and Bukharov ). As usual, the second-order equation (1.1) can be written as a first order system which is a particular case of a (non-linear) Langevin equation. The second equation in this system is autonomous, and the corresponding velocity component can be given explicitly, once its initial value v 0 is fixed: Clearly, for any ∈ R and v 0 ∈ R such a solution tends to 0 as t → ∞; that is, in any case, the velocity component of the system dissipates. The complete picture which also involves the position component, is more sophisticated. Clearly, and one can easily observe that v = (v t ) t≥0 is integrable on R + if < 2. In this case the position component x = (x t ) t≥0 dissipates as well and tends to a limiting value The function F (v) has the meaning of a complete response of the system to the instant perturbation of its velocity by v. For ≥ 2, the integral of v t over R + diverges, and x t tends to ±∞ depending on the sign of v 0. In other words, the friction in the system in the vicinity of zero is too weak to slow down the particle. In this paper we consider the interplay between the non-linear dissipation and the weak random vibrations of the particle, namely we study perturbations of the velocity by a weak (symmetric) Lvy process Z, (1.4) in the small noise limit → 0. Heuristically, we consider a system, which consists of two different components acting on different time scales. The microscopic behaviour of the system is primarily determined by the non-linear model (1.2) under random perturbations of low intensity. It is clear that neither these perturbations themselves nor their impact on the system are visible on the microscopic time scale; that is on any finite time interval , Z t tends to 0, and (x t, v t ) become close to (x t, v t ) as → 0. The influence of random perturbations becomes significant on the macroscopic time scale −1 t which suggests to focus our analysis on the limit behaviour of the pair (X t, V t ) := x −1 t, v −1 t (1.5) satisfying the system of SDEs (1.6) We will look for a non-trivial limit for the position process X as → 0, in dependence on the friction exponent and the properties of the process Z. The case of Stokes friction = 1 is probably the simplest one: the system (1.6) is linear, and under zero initial conditions X 0 = V 0 = 0, its solution X is found explicitly as a convolution integral (1 − e −(t−s)/ ) dZ s. Hintze and Pavlyukevich showed, that for any Lvy forcing Z, X converges to Z in the sense of finite-dimensional distributions. It is worth noticing that although X is an absolutely continuous process, the limit is in general a jump process. In that case, a functional limit theorem requires the convergence in non-standard Skorokhod topologies such as the M 1 -Skorokhod topology. Non-linear ( = 1) stochastic systems of the type (1.6) driven by Brownian motion, Z = B, have been studied in recent years both in physical and mathematical literature, see Lindner (2007Lindner (, 2008Lindner (, 2010; Lis et al. for the analysis for = 1, 2, 3, 5, Baule and Sollich ; Touchette et al. ;de Gennes ; Hayakawa ; Kawarada and Hayakawa ; Mauger for the important case of dry (Coulomb) friction = 0, and Goohpattader and Chaudhury for experiments and simulations for the dry friction = 0 and irregular friction = 0.4. The main goal of these papers was to determine on the physical level of rigour how the so-called effective diffusion coefficient, which is roughly speaking the variance of the particle's position, depends on. In mathematical terms, the result from Hintze and Pavlyukevich gave convergence X ⇒ B for = 1, whereas Eon and Gradinaru proved that for > −1, the scaled process 2(−1)/(+1) X weakly converges in the uniform topology to a Brownian motion whose variance is calculated explicitly. The limiting behaviour of (1.6) with a symmetric -stable Lvy forcing was also the subject of the paper by Eon and Gradinaru. Under the condition + 2 > 4 they proved that the scaled process (+2−4)/2(+−1) X weakly converges to a Brownian motion. The proof is based on the application of the central limit theorem for ergodic processes. In the present paper, we establish a principally different type of the limit behaviour of the process X. We specify a condition on the Lvy noise Z, which ensures that X, without any additional scaling, converges to a non-Gaussian limit. Such a behaviour is easy to understand once Z is a compound Poisson process, which is the simplest model for mechanical or physical shocks. If < 2, the position process X is a composition of individual responses of the deterministic system (1.1) on a series of rare impulse perturbations. Since a general (say, symmetric) non-Gaussian Lvy process Z can be interpreted as limit of compound Poisson processes, one can naively guess that the same effect should be observed for (1.6) in the general case as well. This guess is not completely true for the "large jumps" part of the noise (being, of course, a compound Poisson process) now interferes with the "small jumps" via a non-linear drift |v| sgn v. To guarantee that the "small jump" are indeed negligible, we have to impose a balance condition between the non-linearity index and the proper version of the Blumenthal-Getoor index BG (Z) of the Lvy noise, namely we require that BG (Z) + 2 < 4. (1.7) Combined with the aforementioned analysis of the symmetric -stable case by Eon and Gradinaru, this clearly separates two alternatives available for the system (1.6). Once (1.7) holds true, the small jumps are negligible, and X converges to a non-Gaussian limit; otherwise, the small jumps dominate, and X is subject to the central limit theorem, i.e. after a proper scaling one gets a Gaussian limit for it. Note that since (1.7) necessitate the bound < 2, a non-Gaussian limit for X can be observed only when both the velocity and the position components of (1.2) are dissipative. The rest of the paper is organized as follows. In Section 2, we introduce the setting and formulate the main results of the paper. To clarify the presentation, we separate two preparatory results: Theorem 2.1 for the system (1.6) with the compound Poisson noise, and Theorem 2.2, which describes the asymptotic properties of the velocity component of a general system. The proofs of the preparatory results are contained in Section 3. The proof of the main statement of the paper, Theorem 2.3, is given separately in the regular case and in the non-regular/quasi-ergodic case in Section 4 and Section 5, respectively; see discussion of the terminology therein. Some technical auxiliary results are postponed to Appendix. Notation and preliminaries For a ∈ R, we denote a + = max{a, 0}, a ∧ b = min{a, b} → X denotes convergence in the sense of finite dimensional distributions. Throughout the paper, Z is a one-dimensional symmetric non-Gaussian Lvy process with the Lvy measure. In Section 2.2, we assume that Z is a compound Poisson process with (R) ∈ (0, ∞) which is not necessarily symmetric. In both cases, the Lvy-Hinchin formula for Z reads Note that for an arbitrary Lvy measure the following estimate holds true: We always assume ({0}) = 0. If (R) ∈ (0, ∞), then Z is a compound Poisson process, and in that case we write where { k } k≥1 are jump arrival times of Z, and {J k } k≥1 are jump amplitudes. For Z with infinite Lvy measure, an analogue of this representation is given by the It-Lvy decomposition where N (dz dt) is the Poisson point measure associated with Z, N (dz dt) = N (dz dt) − (dz)dt is corresponding compensated measure. We do not specifically address the question of the existence and uniqueness of solutions of the system (1.6), assuming these solutions to be well defined. Let us briefly mention several facts about that. 1. If Z is a compound Poisson process then the system (1.6) can be uniquely solved path-by-path for any ∈ R. 2. For ∈ R and general Z, it is natural to understand the drift b(v) = |v| sgn v in the following set-valued sense: see, e.g. Pardoux and Rcanu. 3. For ≥ 0, the SDE (1.6) has unique strong solution, which follows by monotonicity of the drift b. In Pardoux and Rcanu, this is proved for an SDE with Brownian noise, for the SDE (1.6) with additive Lvy noise the argument remains literally the same. The simplest non-Gaussian case: compound Poisson impulses Let Z be a compound Poisson process and denote its counting process, so that Let the initial position and velocity x 0, v 0 be fixed, and let (X t, V t ) t≥0 be the solution to the system (1.6) with the initial condition (x 0, v 0 ). Theorem 2.1 For any t > 0, we have the following convergence a.s. as → 0: 1. for < 2, In the above Theorem, the considerably different limits in the case 1 and the cases 2, 3 are caused by the different dissipativity properties of the system (1.2) discussed in the Introduction. For < 2, the complete response to the perturbation of the velocity is finite, and is given by the function Note that the right hand side in (2.2) is just the sum of the initial position x 0, the response which corresponds to the initial velocity v 0, and the responses to the random impulses which had arrived into the system up to the time t. Similar additive structure remains true in the cases 2 and 3 as well, however for ≥ 2 the complete response of the system to every single perturbation is infinite, which explains the necessity to introduce a proper scaling. For > 2, this also leads to necessity to take into account the jump arrival times. Note that in all three regimes, the initial value v 0 of the velocity has a natural interpretation as a single jump with the amplitude J 0 = v 0, which occurs at the initial time instant 0 = 0. General setup In the main part of the paper, we adopt even a more general setup, than the one explained in the Introduction. Namely, we consider a system with a family of Lvy processes {Z } ∈(0,1]. Such a setting allows for taking into account small uncertainties in the random perturbations. It also allows one to avoid certain technical issues, preserving the model's physical relevance. For instance, for < 0 and infinite, it may be difficult to specify the solution to (1.6), but such a solution is well defined for each compound Poisson approximation Z to Z, where all the jumps of Z with amplitudes smaller than some threshold ℓ() are truncated. The first statement in this section actually shows that the velocity component of the system (2.4), under very wide assumptions on the Lvy noise, has a dissipative behaviour similar to the one of v t, discussed in the Introduction. → Z as → 0. Then for any ∈ R the following hold true: (i) for any T > 0 and any initial value v 0, (ii) for any t > 0, any initial value v 0, and any > 0, The main result of the entire paper is presented in the following Theorem. on t ∈ (0, ∞), where N is the compensated Poisson random measure, which corresponds to the Lvy process Z. Inequality (2.7) is a uniform analogue of the one from the definition of the Blumenthal-Getoor index. Namely, if { } consists of a single Lvy measure, (2.7) holds true for any > BG (Z). Condition (2.8) prevents accumulation of small jumps for the family { }, and also holds true once { } consists of one measure. This leads to the following Corollary 2.1 Let Z be a symmetric pure jump Lvy process with the Blumenthal-Getoor index satisfying BG + 2 < 4. Let either Z = Z, or Z be a compound Poisson process, obtained from Z by truncations of the jumps with amplitudes smaller than ℓ(), and let ℓ() → 0, → 0. Then the position component X of the system (2.4) satisfies (2.9). Note that the right hand side in (2.9) is a Lvy process with the Lvy measure X (B) = z : (2.10) Theorem 2.3 actually shows that the Langevin equation (1.4) with small Lvy noise, considered at the macroscopic time scale, performs a non-linear filter of the noise, with the transformation of the jump intensities given by (2.10). Since is symmetric and the response function In other words, the right hand side in (2.9) has exactly the same form as (2.2). Note that the assumption + 2 < 4 again requires < 2, since ≥ 0. Hence, the operation of the aforementioned non-linear filter can be shortly described as follows: every jump z of the input process Z is transformed to the jump F (z) of the output process. From this point of view, the assumption + 2 < 4 can be interpreted as a condition for the jumps to arrive "sparsely" enough, for the system to be able to filter them independently. The following example, in particular, shows that this assumption is sharp, and once it fails, the asymptotic regime for (2.4) may change drastically. Example 2.1 Let Z be a symmetric -stable process with the Lvy measure Then the right hand side in (2.9) is also a symmetric stable process with the Lvy measure Note that the new stability index X is smaller than 2 exactly when + 2 < 4. That is, in the symmetric stable setting, Theorem 2.3 obviously fails when the latter condition fails. This is not surprising because we know from Eon and Gradinaru that, once + 2 > 4, the properly scaled process X has a Gaussian limit. The boundary case + 2 = 4 is yet open for a study. Before proceeding with the proofs, let us give two more remarks. First, it will be seen from the proofs that for any t > 0 in probability, where N denotes the compensated Poisson random measure for the process Z. This is a stronger feature than just the weak convergence stated in Theorem 2.3. Hence the non-linear filter, discussed above, actually operates with the trajectories of the noise rather than with its law. Second, in order to make exposition considerably simple and compact, we restrict ourselves to the f.d.d. weak convergence (actually, the point-wise convergence in probability), rather than the functional convergence. We believe that (2.9) holds true in the M 1 -topology, similarly to the case = 1 studied in Hintze and Pavlyukevich. This guess can be easily verified in the context of Theorem 2.1: the explicit trajectory-wise calculations from its proof can be slightly modified in order to show that the convergence holds true in M 1 -topology for ≤ 2, and in the uniform topology for > 2. Proof of Theorem 2.1 The solution of the system (1.6) can be written explicitly. Namely, denote which is just the velocity component of the system (1.2) with v 0 = v, taken at the macroscopic time scale −1 t; see (1.3). The integral of the velocity can be also easily computed: Then (X t, V t ), defined by (1.6), can be expressed as follows: and where we adopt the notation and I t (v) are given explicitly, we now easily obtain the required statements. First, observe that for each t > 0 and v ∈ R, almost surely. Next, we have for < 2 for any t > 0, v ∈ R Since any fixed time instant t > 0 with probability 1 does not belong to the set { k } k≥0, the latter relation combined with (3.3) gives Combined with (3.3), this gives almost surely. In the case > 2 the argument is completely analogous, and is based on the relation and we omit the details. 3.2 Proof of Theorem 2.2 1. In what follows, we assume that all the processes {Z } ∈(0,1] are defined on the same filtered space (, F, {F t }, P). We will systematically use the following "truncation of large jumps" procedure. For A > 1, denote by Z,A the truncation of the Lvy process Z at the level A, namely For a given T > 0, in a neighbourhood of the origin. This means that the tails of the Lvy measures uniformly vanish at ∞: That is, for any T > 0 and > 0 we can fix A > 0 large enough such that inf ∈(0,1] Assume that for such A we manage to prove statements (i), (ii) of the Theorem for the system (2.4) driven by Z,A instead of Z. Since this system coincides with the original one on a set of probability larger than 1 −, we immediately get the following weaker versions of (2.5) and (2.6): Taking A large enough, we can make arbitrarily small. Hence, in order to get the required statements, it is sufficient to prove the same statements under the additional assumption that, for some A, 2. Let us proceed with the proof of (2.5). By (3.5) and the symmetry of, we have that which is a square integrable martingale. With the help of It's formula applied to the process V we get is a local martingale. The sequence is a localizing sequence for M and thus By the Doob maximal inequality, This yields Thus these exists a constant C > 0, independent on, such that This yields (2.5) by the Chebyshev inequality. 3. To prove (2.6), we note that M defined in (3.7) is a square integrable martingale by (3.8). Then by (3.6) we have For > −1 this yields that, for any > 0, in probability. For ≤ −1, combined with (2.5), this gives even more: in probability. In each of these cases, we have that, for any given > 0, t 0 ≥ 0, the stopping times Figure 1: The set of parameters (, ) ∈ regular corresponding to the regular case, see (4.1) Now we can finalize the proof of (2.6). For a given t > 0, fix t 0 ∈ is uniformly bounded on bounded sets, and that lim v→0 sup ∈(0,1] H (v) = 0. By (2.5) and (3.10), this means that (4.8) holds true in probability and hence the integral term in (4.5) is negligible. Here, we focus on the convergence of martingales (4.6). First, we observe that, because of the principal assumption + 2 < 4 and the truncation assumption (3.5) with the help of (A.1) we estimate that is, M is a square integrable martingale. Denote for > 0 and R > 0 Since F is continuous, we have by (3.10) and the dominated convergence theorem, (4.9) Hence the above estimate provides that for each > 0 If ∈ [1, 2), the function F is Hlder continuous with the index 2 −, and for M we have essentially the same estimate: If < 1, the function F has a locally bounded derivative, which gives for arbitrary R sup In both these cases, we have for arbitrary c > 0 Combining (4.10), (4.11), and (4.12), we complete the proof of (4.6). Each M is a Lvy process. Since (3.4) and (4.11) hold true and F is continuous, we have for any t ≥ 0 and ∈ R which gives (4.7). This completes the proof of the Theorem. Combined with the principal assumption + 2 < 4, this yields > 0, > 0, see Fig. 3 We call this case non-regular and quasi-ergodic. Let us explain the latter name and outline the proof. We make the change of variables with a symmetric jump measure. Such a space-time rescaling transforms the equation for the velocity in the original system (2.4) to a similar one, but without the term 1/. In terms of Y, the expression for X takes the form In the particularly important case where Z = Z and Z is symmetric -stable, each process U has the same law as Z, and thus the law of the solution to (5.1) does not depend on. The corresponding Markov processes Y are also equal in law and ergodic for + > 1, see (Kulik, 2017, Section 3.4). Hence one can expect the limit behaviour of the re-scaled integral functional (5.3) to be well controllable. We confirm this conjecture in the general (not necessarily -stable) case, which we call quasi-ergodic because, instead of one ergodic process Y we have to consider a family of processes {Y }, which, however, possesses a certain uniform stabilization property as t → ∞ thanks to dissipativity of the drift coefficient in (5.1). To study the limit behaviour of X, we will follow the approximate corrector term approach, similar to the one used in Section 4. On this way, we meet two new difficulties. The first one is minor and technical: since we assume (, ) ∈ regular, we are not able to apply the It formula to the function F, see Fig. 2. Consequently we consider a mollified function whereF is an odd continuous function, vanishing outside of , and such that F ∈ C 3 (R, R). Now the It formula is applicable: see the notation in Section 5.2 below. This gives where R (y) = − F (y)|y| sgn y + y + J (y) = −F (y)|y| sgn y + J (y). (5.5) This representation is close to (4.5). This relation becomes even more visible, when one observes that Then (5.4) can be written as SinceF is bounded and < 2, the terms (2−)F (Y t − ) and (2−) F (Y 0 ) are obviously negligible. Also, it will be not difficult to show that the last term in (5.6) is negligible, as well: in probability. Recall that we have (4.6) and (4.7), see Remark 4.1. Eventually, to establish (2.11), it is enough to show that in probability. The second, more significant, difficulty which we encounter now is that this relation cannot be obtained in the same way we did that in Section 4. We can transform it, in order to make visible that it is similar to (4.8): We are now not in the regular case, (, ) ∈ regular, and thus the family {H } ∈(0,1] is typically unbounded in the neighbourhood of the point v = 0, see Fig. 2. We have for each > 0 the proof is postponed to Appendix C. Thus the family { H } ∈(0,1] is unbounded, and one can hardly derive (5.8) from (3.10), like we did that in Section 4. Instead, we will prove (5.8) using the stabilization properties of the family {Y }. Preliminaries to the proof In what follows we assume (3.5) to hold true, i.e. the jumps of the processes Z are bounded by some A > 0. Using the "truncation of large jumps" trick from the previous section, we guarantee that this assumption does not restrict the generality. We denote by the Lvy measure of the Lvy process U introduced in (5.2), and by n and n the corresponding Poisson and compensated Poisson random measures. More precisely, for B ∈ B(R) and s ≥ 0 n (du ds) := n (du ds) − (du) ds. (5.16) Lemma 5.1 Let a non-negative G ∈ C 2 (R, R) be such that for some c 1, c 2 > 0 Then for all t ≥ 0 and > 0 Proof: By the It formula, where M is a local martingale. Let n ∞ be a localizing sequence for M, then We complete the proof passing to the limit n → ∞ and applying the Fatou lemma. Now we specify the functions G and Q which we plug into this general statement. Fix recall that > 0 and therefore the above interval is non-empty. Let a non-negative G ∈ C 2 (R, R) be such that G(y) ≡ 0 in some neighbourhood of 0, The function G satisfies the assumptions of Lemma B.1 with = p + 1 − ; note that assumption (5.18) means that ∈ (0, ). Since we have by Lemma B.1 sup Hence, to prove the bound (5.14) with Q specified above, it is enough to show that, for some p < p (5.22) In the rest of the proof, we verify this relation for properly chosen p. We fix y, and (with a slight abuse of notation) denote by Y, Y,0 the strong solutions to (5.1) with the same process U and initial conditions Y 0 = y, Y,0 0 = 0. Recall that the Lvy process U is symmetric. Since the drift coefficient −|y| sgn y in (5.1) is odd, the law of Y,0 is symmetric as well. By Lemma B.2, the family of functions {R } ∈(0,1] is bounded: if + > 2 this is straightforward, for + = 2 one should recall that in the non-regular case this identity excludes the case = 2, see Fig. 3. It is also easy to verify that functions R are odd, which gives This bound will allow us to prove (5.22) using the dissipation, brought to the system by the drift coefficient −|y| sgn y. In what follows, we consider separately two cases: ∈ is well defined and is uniformly bounded on the set {|y| ≤ D 0 }. We have |A g(y )| since 1 ≤ 1 by construction. This yields (5.34). Summarizing the above calculation, we conclude that Consequently, for some c ↓ > 0 we have (5.36) and By the Burkholder-Davis-Gundy inequality (Kallenberg, 2002, Theorem 23.12), and Jensen's inequality, we have Now we obtain the first inequality in (5.33): if c > 0 is such that c −1 > c ↓, then The proof of the second inequality in (5.33) is similar and simpler. We denote Now s,↑ k ≤ 1 by construction, hence analogues of (5.35) and (5.36) trivially hold true, which gives On the other hand, by (5.32) and the strong Markov property, Then for c < 1/2 we have A Auxiliaries to the proof of Theorem 2.3: regular case In this section, we assume conditions of Theorem 2.3 to hold true, and (3.5) to hold true for some A. First, we give some basic integral estimates. Denote for = 2. The same assertion holds true for < 2 by (A.1). Using (A.2), we can perform integration by parts: For = 2, the same relations hold true by (2.8). From now on, we assume that (, ) ∈ regular. The following lemma describes the local (v → 0) and the asymptotic (v → ∞) behavior of the functions H defined in (4.4). To prove (A.6), we restrict ourselves to the case 0 < |v| ≤ 2A, and decompose The term H 2 admits estimates similar to those we had above. Namely, we have For I 2 analogue of (A.10) holds true, and thus H 2 satisfies (A.11). To estimate H 1 we use the Lipschitz condition (A.12) and assumption v ≤ 2A: Proof: For < 0, F ∈ C 2 (R, R), and the standard It formula holds. For ∈ , for F, which satisfies the following: One particular example of such a family is given by The It formula applied to F yields (A.15) By construction, we have in probability. To analyse the behaviour of the martingale part M, we repeat, with proper changes, the argument used to prove (4.6). Namely, truncating the small jumps, stopping the processes at the time moments R = inf{t : |V t | > R}, R > 0, and using Theorem 2.2, we can show that in probability. Finally, repeating with minor changes the estimates from the proof of Lemma A.1, we can show that H, → H, → 0 uniformly of any bounded set. Taking → 0 in (A.15), we obtain the required It formula. |
#include<stdio.h>
int main()
{
int num,i,x,count=0;
char **phone,temp;
scanf("%d",&num);
phone=malloc(num*sizeof(int));
for(i=0;i<num;i++)
{
phone[i]=malloc(20*sizeof(char));
scanf("%s\n",phone[i]);
}
for(i=0;i<20 && phone[0][i]!='\0';i++)
{
temp=phone[0][i];
for(x=1;x<num;x++)
{
if(phone[x][i]==temp)
continue;
else
break;
}
if(x==num)
count++;
else
break;
}
printf("%d",count);
return 0;
} |
Q:
Operating system on an ARM9 MCU
I have an ARM926EJ MCU (datasheet) that I am learning how to program for a research project. I have been researching, as well as reading a textbook on Professional Embedded ARM Development in order to learn how to program, and I have learned much about bare metal programming for my specific project.
However, I want to learn how to program with an operating system on my MCU. I intend on running a simple program, and I would like for an operating system to do much of the low-level handling for me. From my research, programming in the Linux environment will speed up my learning curve by much.
My question is two part:
How do I download an operating system onto my MCU?
How do I run a program on my MCU after installing an operating system on it?
If you are interested in the details of my project it is very simple: I will use the internal clock to detect the timing of 30 ns pulses received by a GPIO pin with a rough resolution; and I will upload these recorded clock values to another MCU via SPI connection. So, I will have to simultaneously handle the GPIO pulse stream and the SPI upload connection.
A:
Your two questions depends on the operating system.
Choosing the Operating System is a whole new question that is where you might start from.
As your application seems very simple, and might have real time contrains, I suggest you to analyse the possibility of implementing it bare metal.
But, if Operating System is required, take a look at FreeRTOS, might interest you! |
Nimbolide retards tumor cell migration, invasion, and angiogenesis by downregulating MMP2/9 expression via inhibiting ERK1/2 and reducing DNAbinding activity of NFB in colon cancer cells Nimbolide, a plantderived limonoid has been shown to exert its antiproliferative effects in various cell lines. We demonstrate that nimbolide effectively inhibited proliferation of WiDr colon cancer cells through inhibition of cyclin A leading to S phase arrest. It also caused activation of caspasemediated apoptosis through the inhibition of ERK1/2 and activation of p38 and JNK1/2. Further nimbolide effectively retarded tumor cell migration and invasion through inhibition of metalloproteinase2/9 (MMP2/9) expression, both at the mRNA and protein level. It was also a strong inhibitor of VEGF expression, promoter activity, and in vitro angiogenesis. Finally, nimbolide suppressed the nuclear translocation of p65/p50 and DNA binding of NFB, which is an important transcription factor for controlling MMP2/9 and VEGF gene expression. © 2011 Wiley Periodicals, Inc. |
def calculate_user_changes(self) -> Tuple[Set[str], Set[str]]:
newly_joined_or_invited_or_knocked_users = set()
newly_left_users = set()
if self.since_token:
for joined_sync in self.joined:
it = itertools.chain(
joined_sync.timeline.events, joined_sync.state.values()
)
for event in it:
if event.type == EventTypes.Member:
if (
event.membership == Membership.JOIN
or event.membership == Membership.INVITE
or event.membership == Membership.KNOCK
):
newly_joined_or_invited_or_knocked_users.add(
event.state_key
)
else:
prev_content = event.unsigned.get("prev_content", {})
prev_membership = prev_content.get("membership", None)
if prev_membership == Membership.JOIN:
newly_left_users.add(event.state_key)
newly_left_users -= newly_joined_or_invited_or_knocked_users
return newly_joined_or_invited_or_knocked_users, newly_left_users |
package automation.library.cucumber.core;
import automation.library.common.TestContext;
import io.cucumber.core.api.Scenario;
import io.cucumber.java8.En;
public class Hooks implements En{
public Hooks(){
Before(10, (Scenario scenario) -> {
String featureName = (scenario.getId().split(";")[0].replace("-", " "));
String scenarioName = scenario.getName();
TestContext.getInstance().putFwSpecificData("fw.testDescription", featureName + "-" + scenarioName);
TestContext.getInstance().putFwSpecificData("fw.cucumberTest","true");
});
}
}
|
Hundreds of thousands of school students across the world skipping class and taking to the streets to demand politicians take action to tackle climate change.
Prime Minister Jacinda Ardern has signalled a reform to the country’s gun laws in the wake of the mass shootings in Christchurch.
The Camp fire in Northern California has become the deadliest and most destructive in state history, while another major blaze near Los Angeles forced hundreds of thousands to flee.
Get results in key races for state governor, the House, and the Senate across the United States.
This is BuzzFeed News’ live coverage of the 2018 midterm elections.
Four police officers have also been shot and wounded. A suspect has been arrested.
The package — targeted at CNN — was intercepted at a post office in Atlanta hours before 56-year-old Cesar Altieri Sayoc will appear in federal court.
The most intense hurricane to make landfall on the Panhandle has killed at least 26 people from Florida to Virginia.
Live Updates: Brett Kavanaugh Angrily Denied Assault Allegations, Calling The Process A "Disgrace"
Supreme Court nominee Brett Kavanaugh was accused of sexual misconduct by Christine Blasey Ford. They both testified Thursday before the Senate Judiciary Committee.
Hurricane Florence had a devastating impact on coastal North and South Carolina.
Apple debuted three new iPhones and a new Apple Watch.
Watch Live: "AM To DM," The Morning Show From BuzzFeed News!
From fire tweets to interviews with newsmakers, watch us weekdays at 10 a.m. ET!
Omarosa released a secret recording of her White House firing, the latest on the Seattle airplane crash, and the new season of "Insecure." Your BuzzFeed News newsletter, August 13. |
50 Ways to Be A Great Example to a Child Michele Borba
How can adults teach kids good character? Be a great example of character to a child!
Of course we want our children to become good, responsible, respectful and successful human beings! But in our quest to “do it all” we may forget that some of the most powerful ways to help our children aren’t in the things we buy, but in the simple things we say.
Example is everything. In fact, the Greek philosopher, Aristotle, years ago said that the best way to teach character is by modeling good example. (I swear kids come with video recorders planted inside their heads and we know it when they play us back at the most inopportune moments–usually when the relatives arrive).
The bottom line is the kids are watching us and they are copying–the good, the bad, and the very ugly things we say and do. Just in case you need any proof here are a few things our children pick up from watching us:
Behavior. Prejudice. Stress management. How we cope with defeat. Organizational style. Driving safety. Drinking styles. Eating habits. Friendship making. Goal-setting. Values. Sleeping habits. Television viewing. Courtesy. Discourtesy. Punctuality. Religion. Love of reading. Lifestyle choices. Interests. Responsibility. Digital citizenship. If we bounce back. Self-talk. Pessimism. Optimism. Money Management. Procrastination. Frugality. Patriotism. Biases. Friendship keeping. Valuing education. Conflict resolution.
And the list goes on and on!
Here are just 50 things to say to boost our own example to our kids so we become the model we hope they copy. Our children desperately need role models. Let them look to us!
1. “Thank you! I really appreciate that!” (Courtesy)
2. “Excuse me, I need to walk away and get myself back in control.” (Stress and anger management)
3. “I’m going to call Grandma and see how she’s doing. She looked lonely.” (Empathy, compassion)
4. “Mrs. Jones is sad. I’m baking her some cookies. Want to help?” (Charity)
5. “I don’t want to watch this anymore. I don’t like how they are portraying…(women, men, kids, a race, a culture, a religion…). (Values and stereotyping)
6. “Excuse me. I didn’t mean to interrupt you.” (Admitting mistakes. Manners)
7. “That’s my two cents. I’d love to hear yours.” (Communication style)
8. “I lost my temper there. I’m going to work on counting to 10 when I get so stressed.” (Anger management)
9. “I blew it. Next time I’ll….” (Handling mistakes)
10. “I’m going to set a goal for myself this year. I’m working on….” (Goal-setting)
11. “I’m so upset with my friend-remind me not to send her an email until I cool off.” (Online behavior)
12. “Please repeat that. I don’t understand.” (Conflict and communication style).
13. “I’m so stressed lately…I’m going to (start walking, eat healthier, write in a journal, listen to soothing music, or whatever) to help me relax.” (Stress management, coping)
14. “I want to listen. Let me turn off my cell phone.” (Digital citizenship)
15. “I have so many things to do today. I’m going to make a list so I don’t forget anything.” (Organization)
16. “That woman looks like she’s going to drop those packages. Let’s ask if she needs help.” (Kindness)
17. “Apologies…that was my fault. Hope you forgive me.” (Forgiveness)
18. “I’m driving and need to keep my eyes on the road. Please turn off my phone for me.” (Driving safety)
19. “I love watching the Oscars, but let’s not focus on their dress designers but their talent. How do you think Sandra Bullock prepared for her role in space.” (Valuing quality over materialism)
20. “She’s my friend and doesn’t want me to tell anyone. I’m honoring her request.” (Friendship. Loyalty)
21. “I’m getting upset and need to take a time out. Let’s talk in a few minutes.” (Anger management)
22. “Great question-I don’t that answer. But I’ll try to find it for you.” (Admitting shortcomings)
23. “They do look different than us, but they have the same feelings. Let’s think about how we’re the same.” (Prejudice)
24. “Didn’t she just move here? Let’s go introduce ourselves and ask her to sit with us.” (Courtesy. Kindness)
25. “If it’s not respectful I’m not sending it.” (Digital citizenship)
26. “But is that true for all elderly people? Aunt Harriet remembers everything and she’s 87. Let’s think of more examples.” (Stopping prejudice and bias)
27. “Every month I’m going to set a new goal. You’re going to help remind me to stick to it!” (Goal-setting)
28. “We hear so much about the “bad” stuff–let’s look through the paper and find the good things people are doing for each other. We could start ‘Good News’ reports.” (Optimism, attitude)
29. “I need to take care of myself and eat healthier.” (Self-care)
30. “I’m going to walk around the block. Want to come? It always helps me relax.” (Self-care)
31. “I taped ‘No’ on a card on the phone to remind me to not to take on so much. I’m prioritizing my family!” (Priorities)
32. “I’ve got to catch my words-I’m becoming too negative.” (Attitude. Optimism)
33. “Let’s set ‘unplugged times’ for our family. What about from 6 to 8 pm?” (Prioritizing family).
34. “I do like it, but I’m going to wait until it’s on sale.” (Frugality, delaying gratification).
35. “I always try to save half of my paycheck.” (Money management)
36. “Those children lost everything in that fire. Let’s go through our closets and find gently used clothes and toys to bring them.” (charity)
37. “I’d love to eat that now, but I’m going to wait until after dinner.” (Self-control)
38. “I know it sounds fun, but I need to finish my job. My motto is, “Work first, then play.” (Responsibility)
39. “Thanks, but no thanks. I’m driving so I can’t drink.” (Drinking behavior)
40. “My favorite thing to do is read! Let’s go to the library sale and find books to bring on our vacation.” (Instilling a love of reading).
41. “Let’s stay open-minded and give Daniel a turn. We didn’t hear his side.” (Non-judgmental)
42. “That’s not fair. We agreed on the rules so let stick to them.” (Fairness).
43. “I know we wanted to win, but we didn’t. They were better than us, so let’s go congratulate them.” (Sportsmanship)
44. “I need to go write a thank you to Peter before I forget. He put a lot of thought into that present and I want to make sure he knows how much I appreciate it.” (Gratitude)
45. “Thanks, but you don’t need to give me any money. I did it because I wanted to help.” (Charitableness)
46. “I’m going to stop talking about dress sizes and jumping on the scale, and start thinking about eating healthier instead.” (Self-image)
47. “I’ve got to get to the polls before they close. Voting is something I take very seriously.” (Citizenship)
48. “Let’s stop and think about how she feels. She looks sad-let’s get in her shoes for a minute.” (Empathy)
49. “I’m not just going to stand by when someone could get hurt. I’m asking if he wants help.” (Responsibility. No by standing!”)
50. “Everyone can make a difference. Let’s think of something we can do.” (Personal responsibility. Empowerment)
What can you say to a child today to be the example he or she can use for tomorrow?
Beware, the children are copying!
Follow me on twitter @MicheleBorba
UnSelfie: Why Empathetic Kids Succeed in Our All About Me World is now in audio, e-book, and hardcopy after a decade of researching and writing. It has over 300 ways parents and educators can increase our children’s empathy capacities from toddler to teen, describes the latest science that proves we can make a difference and stories in my journey to find those answers. (Just a hint: the best ideas were ones children around the world shared with me. They were always simple, right on, and matched the science!) Here’s to a generation of UnSelfies!!! |
Modified FrantzNodvik equation for CW end-pumped high-repetition-rate picosecond laser amplifier Abstract. The modified FrantzNodvik equation considering the pulse repetition rate (PRR) for continuous-wave end-pumped picosecond laser amplifier is theoretically developed for the first time by analogizing Q-switch theory and solving rate equations. Based on the modified FrantzNodvik equation, a simple finite-element slice model is established to simulate the output characteristics of the end-pumped high-repetition-rate picosecond amplifier. Moreover, the validity of the theory and model is well verified by the experimental results of a two-staged diode-end-pumped Nd:YVO4 amplifiers using a picosecond fiber laser with adjustable PRRs as the seed source. The agreement between the experimental and theoretical results illustrates that the as-developed pulse amplification theory and model are a powerful tool for designing and optimizing adjustable-high-repetition-rate solid-state picosecond laser amplifiers. |
Effects of intravenous administration of tranexamic acid on hematological, hemostatic, and thromboelastographic analytes in healthy adult dogs. OBJECTIVE To assess the effects of tranexamic acid (TA) on hematological, hemostatic, and thromboelastographic analytes in healthy adult dogs. DESIGN Prospective study. SETTING University teaching hospital. ANIMALS Eleven healthy, staff-owned, adult dogs. MEASUREMENTS AND MAIN RESULTS Dogs were administered TA as an IV bolus, followed by a 3-hour constant rate infusion (CRI). Complete blood count, prothrombin time, activated partial thromboplastin time, D-dimer, antithrombin, fibrinogen, and thromboelastography (TEG) were measured prior to, and immediately after TA administration. Vomiting occurred transiently in the first 2 treated dogs, immediately after 20 and 15 mg/kg IV boluses, but not during the CRI. In all other dogs the TA IV bolus dose was reduced to 10 mg/kg, and administered slower, and vomiting did not occur. All measured hemostatic and hematological analytes remained within their reference intervals, however, following TA treatment, significant decreases were recorded in prothrombin time, TEG R and A30 values, Hct, and hemoglobin concentration, while the TEG LY30 significantly increased. CONCLUSIONS Administration of TA as a slow IV bolus at 10 mg/kg, followed by a 10 mg/kg/h CRI over 3 hours to healthy dogs is safe; however, its effect on TEG A30, A60, LY30, and LY60 values was inconsistent with its expected anti-fibrinolytic properties. |
<reponame>w181496/OJ
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
main()
{
int n,m,time=0;
while(cin>>n>>m)
{
time++;
if(n==0&&m==0)break;
int s1[n+1];
int s2[m+1];
int dp[n+1][m+1];
for(int i=0;i<=n;++i)
for(int j=0;j<=m;++j)
if(i==0||j==0)dp[i][j]=0;
s1[0]=s2[0]=0;
for(int i=1;i<=n;++i)cin>>s1[i];
for(int i=1;i<=m;++i)cin>>s2[i];
for(int i=1;i<=n;++i)
{
for(int j=1;j<=m;++j)
{
if(s1[i]==s2[j])dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
cout<<"Twin Towers #"<<time<<endl;
cout<<"Number of Tiles : "<<dp[n][m]<<endl;
}
}
|
Loss of GAS5 tumour suppressor lncRNA: an independent molecular cancer biomarker for short-term relapse and progression in bladder cancer patients Background Bladder cancer (BlCa) heterogeneity and the lack of personalised prognosis lead to patients highly variable treatment outcomes. Here, we have analysed the utility of the GAS5 tumour-suppressor lncRNA in improving BlCa prognosis. Methods GAS5 was quantified in a screening cohort of 176 patients. Hedegaard et al. (n=476) and TCGA provisional (n=413) were used as validation cohorts. Survival analysis was performed using recurrence and progression for NMIBC, or death for MIBC. Internal validation was performed by bootstrap analysis, and decision curve analysis was used to evaluate the clinical benefit on disease prognosis. Results GAS5 levels were significantly downregulated in BlCa and associated with invasive high-grade tumours, and high EORTC-risk NMIBC patients. GAS5 loss was strongly and independently correlated with higher risk for NMIBC early relapse (HR=2.680, p=0.011) and progression (HR=6.362, p=0.035). Hedegaard et al. and TCGA validation cohorts analysis clearly confirmed the association of GAS5 loss with NMIBC worse prognosis. Finally, multivariate models incorporating GAS5 with disease established markers resulted in higher clinical benefit for NMIBC prognosis. Conclusions GAS5 loss is associated with adverse outcome of NMIBC and results in improved positive prediction of NMIBC patients at higher risk for short-term relapse and progression, supporting personalised prognosis and treatment decisions. BACKGROUND Bladder cancer (BlCa) represents the second most common urologic cancer and the fourth most commonly diagnosed malignancy among the male population in developed countries, 1,2 with the majority of the tumours (90%) originating in the bladder urothelium. Urothelial bladder carcinoma is a disease spectrum classified into two main clinical groups, depending on the invasion into the detrusor muscle. Approximately 75% of urothelial bladder carcinomas represent non-muscle-invasive bladder cancer (NMIBC) (Ta, Tis, T1), not invading the detrusor muscle, while the other 25% accounts for muscle-invasive bladder cancer (MIBC) (T2-T4). 3 Disease-specific mortality has been significantly reduced nowadays, due to smoking reduction and to outstanding improvements in disease diagnosis and management-based on evolution of imaging, new diagnostic modalities and advanced surgical techniques. 1,4 Despite however the administration of active treatment, BlCa frequently recurs and become life threatening. 5 NMIBC, although not associated with mortality per se, is characterised by strong recurrence potential and subsequently by progression to muscle-invasive tumours, which are metastatic and lethal. In the clinical setting, disease prognosis relies on tumour stage and grade, as well as on disease multifocality, tumour size and concomitant carcinoma in situ (CIS). 6,7 In this regard, EORTC-risk-group stratification represents the clinically established and used predictor of NMIBC outcome. 8,9 However, tumours' heterogeneity in the cellular and molecular levels is responsible for the highly variable clinical outcome of the same risk-group patients, making disease prognosis a rather demanding task. Consequently, the elucidation of disease molecular hallmarks could effectively improve patients' prognostication and support precision medicine. The growth arrest-specific 5 (GAS5) long non-coding RNA (lncRNA;~0.7 kb), originally identified by Schneider et al. through cDNA cloning of genes overexpressed in growth-arrested cells, is encoded by the intergenic GAS5 gene at the region 1q25.1. 10 GAS5 is comprised of 12 exons, bearing a 5-terminal oligopyrimidine (5-TOP) sequence in exon 1, and beside several mature GAS5 variants, GAS5 encodes 10 C/D box snoRNAs (SNORD44, SNORD47, SNORD74-SNORD81) within its 11 introns. 11 Although a short open reading frame, able to encode for a 50 amino acid polypeptide, has been identified within gene exons, GAS5 sequence is poorly conserved and does not encode any functional protein. 11,12 GAS5 transcription is regulated by the interplay of mTOR and nonsense-mediated decay pathways, resulting in the increased GAS5 levels in growth-arrested cells. The well-characterised tumour suppressor of GAS5 has been documented in a wide variety of human malignancies and loss of GAS5 expression has been implicated both in tumorigenesis and disease progression, 16,17 as well as in patients prognosis. 18,19 A dual complementary function in arresting cell growth by inhibition of cell proliferation and stimulation of apoptosis has been attributed to GAS5, highlighting an active role in growth arrest rather than a passive association. Indeed, GAS5 silencing is associated with increased proportion of cells in the S/G2 phase as well as with attenuated apoptosis upon endogenous stimuli or chemotherapeutic agents. The main molecular mechanisms of GAS5 tumour-suppressor activity are riborepression of glucocorticoid receptor (GR) transcriptional activity and "sponging" of oncogenic miRNAs. 16,17,23 Despite the crucial tumour-suppressive role of GAS5 lncRNA in the molecular background of BlCa establishment and progression, there is no complete evaluation of its clinical utility for the patients. In the present study, for the first time, we have evaluated the clinical value of GAS5 tumour-suppressor lncRNA in improving patients' prognosis and prediction of disease course. Screening cohort The biological samples analysed in the study consisted of 363 fresh-frozen bladder tissue specimens. Bladder tumours obtained from 176 BlCa patients who underwent transurethral resection of bladder tumours (TURBT) for primary NMIBC or radical cystectomy (RC) for primary MIBC at the "Laiko" General Hospital, Athens, Greece, representing our screening patients' cohort. Adjacent normal bladder tissues were also obtained from 144 patients of the screening cohort, following pathologist's evaluation for the absence of dysplasia or CIS. Prior to surgery none of the patients received any form of neoadjuvant treatment. Finally, healthy bladder tissue samples were available from 43 benign prostate hyperplasia patients who underwent transvesical suprapubic prostatectomy. Tissue specimens were incubated in RNAlater Solution (Ambion, Carlsbad, CA, USA) according to the manufacturer's instructions and stored −80°C until analysis. NMIBC patients received adjuvant therapy according to European Association of Urology (EAU) guidelines, while MIBC patients did not receive any form of adjuvant treatment. NMIBC patients' risk-group stratification was performed according to the European Organization for Research and Treatment of Cancer (EORTC) guidelines. NMIBC patients were followed-up by cystoscopy and urinary cytology (for high-grade (HG) tumours) according to EAU guidelines. MIBC patients' follow-up included renal ultrasound at 3 months and thoracoabdominal computed tomography (CT)/magnetic resonance imaging (MRI) every 6 months, while additional kidney ultrasound and thoracoabdominal CT/MRI, as well as bone scan or brain MRI was only performed following symptoms. Disease recurrence (the same or lower stage) and progression (recurrence of higher/invasive stage) of NMIBC patients were confirmed by histology findings of a TURBT that performed after a positive follow-up cystoscopy, while in MIBC patients' disease recurrence was detected by a follow-up CT. The present study was conducted according to ethical standards of the 1975 Declaration of Helsinki, as revised in 2008, and approved by the ethics committee of "Laiko" General Hospital. Informed consent was obtained by all the participated patients. Validation cohorts The cohorts of Hedegaard et al. (n = 476) 28 and TCGA (The Cancer Genome Atlas, provisional) (n = 413) 29 Extraction of total RNA Following pulverisation of 40-150 mg of fresh-frozen tissue specimen, total RNA was extracted using TRI-Reagent (Molecular Research Center, Cincinnati, OH, USA) according to the manufacturer's instructions, dissolved in RNA Storage Solution (Ambion) and stored at −80°C. RNA concentration and purity were determined spectrophotometrically at 260 and 280 nm, while agarose gel electrophoresis was performed to evaluate RNA integrity. First-strand cDNA synthesis Total RNA was reverse transcribed in a 20 l reaction containing 1 g of total RNA template, 50 U MMLV reverse transcriptase (Invitrogen, Carlsbad, CA, USA), 40 U recombinant ribonuclease inhibitor (Invitrogen) and 5 M oligo-dT primers. Reverse transcription took place at 37°C for 60 min, while enzyme inactivation performed at 70°C for 15 min. The 7500 Real-Time PCR System (Applied Biosystems, Carlsbad, CA) was used for the qPCR assays. The 10 l reaction consists of Kapa SYBR ® Fast Universal 2X qPCR MasterMix (Kapa Biosystems, Inc., Woburn, MA), 100 nM of each specific PCR primer, and 10 ng of cDNA template. The thermal protocol consisted of polymerase activation step at 95°C for 3 min, followed by 40 cycles of denaturation at 95°C for 15 s and finally the primer annealing and extension step at 60°C for 1 min. Melting curve analysis and agarose gel electrophoresis were performed following amplification to discriminate specific amplicons from non-specific products or primer dimers. The 2 CT relative quantification (RQ) method was used to quantify GAS5 levels. Duplicate reactions were performed for each tested sample and target, and the average C T was calculated and used for the quantification analysis. RT112 bladder cancer cell line was used as a calibrator and HPRT1 as endogenous reference control for normalisation purposes. Statistical analysis The IBM SPSS Statistics 20 software (IBM Corp., Armonk, New York, USA) was used for the statistical analysis. Non-parametric tests were applied appropriately in order to analyse GAS5 levels differences between tumours and healthy bladder urothelium, as well as to assess the correlation of GAS5 expression with patients' clinicopathological features. The ability of GAS5 to discriminate bladder tumours from normal urothelium was evaluated by the ROC curve and logistic regression analysis. Patients' survival analysis performed by Kaplan-Meier survival curves and Cox proportional regression analysis. Internal validation was performed by bootstrap Cox proportional regression analysis based on 1000 bootstrap samples. Optimal cut-off values of the GAS5 expression levels in NMIBC and MIBC patients' cohorts were determined using the X-tile algorithm. To evaluate the clinical net benefit of the prediction models on disease outcome following treatment, decision curve analysis was performed according to Vickers et al., 31 using the STATA 13 software (StataCorp LLC, College Station, TX, USA). Baseline clinical and experimental data The REMARK diagram of our study is presented in Fig. 1. Patients' screening cohort consisted mostly of males (83.5%) with a median age of 70 years. Concerning disease pathology, 67.6% and 32.4% of the patients were diagnosed and treated for primary NMIBC (TaT1) and MIBC (T2-T4), respectively. Within the T1 cohort, 34.5% and 65.5% of the tumours were of low-grade (LG) and HG, respectively, while the vast majority of the MIBC patients (96.5%) displayed HG tumours. According to EORTC-risk-stratification guidelines, 12.6%, 31.9% and 55.5% of the enrolled NMIBC patients were classified as low, intermediate and high risk, respectively. BlCa patients' clinicopathological characteristics are presented in Supplementary Table 1. Regarding patients' outcome following treatment, 151 patients were successfully followed-up, whereas 25 patients were excluded due to insufficient and unclear monitoring data. The expression GAS5 is significantly reduced in bladder tumours The expression analysis (Fig. 2) revealed that GAS5 levels are significantly downregulated (p = 0.001) in bladder tumours compared to the matched adjacent normal specimens in 67.4% of the screened patients (Fig. 2a). This finding was confirmed in NMIBC patients, where decreased GAS5 expression (p = 0.002) in tumours compared to their matched normal counterparts was detected in approximately 69.5% of the enrolled TaT1 patients ( Supplementary Fig. 1). Reduced GAS5 levels in muscle-invasive tumours, while not statistically significant, were also observed in 63.6% of the MIBC (T2-T4) patients (p = 0.181; Supplementary Fig. 1). ROC curve analysis highlighted the ability of GAS5 reduced levels to discriminate bladder tumours from the matched normal urothelium (AUC: 0.623; 95% CI: 0.562-0.684; p < 0.001; Fig. 2b), which was also confirmed by logistic regression analysis (OR: 0.339; 95% CI: 0.188-0.614; p < 0.001; Supplementary Table 2). Loss of GAS5 is associated with unfavourable prognostic disease features The analysis of GAS5 expression regarding patients' clinicopathological features clearly highlighted the association of GAS5 loss with unfavourable disease prognostic markers (Fig. 2). Significantly lower GAS5 levels (p < 0.001) are expressed in muscle-invasive (T2-T4) and connective tissue-invasive (T1) tumours compared to superficial Ta tumours (Fig. 2c), as well as in HG tumours related to LG ones (p < 0.001; Fig. 2d). Analysis of the validation cohorts confirmed the reduced expression of GAS5 in HG tumours (Hedegaard et al., p = 0.050-PUNLMP not evaluated; Fig. 2e and TCGA, p < 0.001; Fig. 2f), and in advanced tumour stages (Hedegaard et al., p = 0.060; Fig. 2g). Moreover, the TCGA cohort highlighted the loss of GAS5 levels in non-papillary tumours compared to papillary ones (p = 0.004; Fig. 2h). Loss of GAS5 is associated with significantly higher risk for recurrence and progression of NMIBC (TaT1) patients The survival analysis of the screening cohort performed using disease recurrence and disease progression as clinical endpoint events for the DFS and PFS of the NMIBC (TaT1) patients, or patients' death for the OS of the MIBC (T2-T4) patients (Fig. 3). Using the X-tile algorithm, the 50th percentile (median) of GAS5 levels was adopted as the optimal cut-off value for both NMIBC and MIBC patient groups. Kaplan-Meier curves clearly highlight a statistically significant prognostic value for the OS of the MIBC patients (Fig. 3f). The correlation GAS5 loss with the poor treatment outcome of the NMIBC patients was also confirmed by Cox proportional regression analysis (Fig. 4 Fig. 3g). The survival analysis of the MIBC patients of the TCGA cohort (n = 402) did not highlight a statistically significant association of GAS5 levels with patients' OS, in agreement with the survival analysis of the MIBC patients of our screening cohort (Fig. 3h). The evaluation of GAS5 expression improves the clinical value of the established prognostic markers for NMIBC The powerful and independent prognostic significance for NMIBC prompted us to study GAS5 ability to strengthen the clinical value of the established disease prognostic markers. Tumour stage, grade, EORTC-risk group and recurrence at the FFC (for disease progression) represent the established and widely clinically used prognostic markers for NMIBC, whereas T1HG tumours, high-risk EORTC stratification and recurrence at the FFC (3 months) are independent predictors of TaT1 recurrence and progression following treatment. The incorporation of GAS5 levels with the above-mentioned clinically used markers clearly resulted in superior positive prediction of NMIBC patients' adverse outcome (Fig. 5). Indeed, Ta/T1LG patients with lower GAS5 levels were at significantly higher risk for short-term relapse (p = 0.010; Fig. 5a) and progression (p = 0.004; Fig. 5b), similar to T1HG patients' risk. Additionally, GAS5 loss could effectively distinguish patients at higher risk for short-term relapse (p = 0.002; Fig. 5c) and progression (p = 0.015; Fig. 5d) within the highly heterogeneous cohort of intermediate/high-risk patients according to EORTC-risk stratification. Finally, patients with negative FFC and loss of GAS5 expression presented significantly shorter PFS expectancy (p < 0.001; Fig. 5e) compared to those overexpressing GAS5. The evaluation of GAS5 levels results in advanced clinical benefit in NMIBC (TaT1) prognosis To evaluate the clinical benefit of the models including GAS5 along with the established disease prognostic markers, decision curve analysis was performed according to Vickers et al. Decision curves of the prediction models tested are presented in Fig. 6. The analysis highlighted the significantly improved clinical benefit of the model incorporating GAS5 loss in predicting NMIBC relapse for threshold probabilities ≥25%, compared to the tumour stage, grade and EORTC-risk group model (Fig. 6a). Similarly, the model integrating GAS5 loss offers the highest clinical benefit for the prediction of NMIBC progression for threshold probabilities >0%, compared to tumour stage, grade, EORTC-risk group and recurrence at FFC model (Fig. 6b). Considering that NMIBC progression to muscle-invasive tumours represents a particularly aggressive clinical event, demanding more intensive follow-up and treatment adjustment, the superior net benefit even at low threshold probabilities is crucial for the effective prognosis and personalised management of the NMIBC patients. DISCUSSION Despite reduction of disease-specific mortality and improvement in disease diagnosis, 1 urothelial bladder carcinoma remains a clinically heterogeneous malignancy regarding patients' prognosis and treatment outcome. Indeed, patients of the same risk group and sharing similar clinicopathological features could display highly variable clinical outcomes and responses to therapy. 9 The lack of accurate disease prognosis forces the generic and nonpersonalised active treatment and lifelong surveillance of patients, classifying BlCa as the most expensive per-patient-to-treat cancer for the healthcare systems of developed countries. 32 Consequently, the identification of novel disease markers represents a top clinical priority in order to be able to support personalised treatment and monitoring decisions, to limit unnecessary interventions and healthcare costs, and finally to benefit patients quality-of-life. The family of non-coding RNAs (ncRNAs) includes a large number of different entities as approximately 70% of the genome is actively transcribed to ncRNAs. 33 Until recently, miRNAs had received the most attention regarding the role and clinical impact of the family in human malignancies. 34,35 However, the functional role of lncRNAs in gene expression as well as their deregulated levels in the vast majority of human malignancies resulted in the ever-growing interest in assessing their implication in cancer cell homoeostasis and their clinical impact for the patients. 36 The aim of the present study was the first-time complete evaluation of GAS5 lncRNA significance in supporting BlCa personalised prognosis and prediction of disease outcome. The analysis of our screening cohort highlighted the significant reduced expression of GAS5 in bladder tumours compared to their matched adjacent normal urothelium, as well as the ability of GAS5 to discriminate bladder tumours from their normal counterparts. The loss of GAS5 was strongly correlated with unfavourable disease prognostic markers, such as HG carcinomas, as well as muscle-invasive (T2-T4) and T1HG tumours. In this regard, loss of GAS5 expression was significantly associated with high-risk NMIBC according to EORTC stratification and with NMIBC patients displaying recurrence at the FFC. The survival analysis revealed the independent and unfavourable significance of GAS5 loss for NMIBC patients' prognosis. Indeed, NMIBC patients underexpressing GAS5 were at significantly higher risk for disease short-term relapse and progression to invasive tumour stages. Additionally, the adverse outcome of the TaT1 patients with GAS5 loss revealed to be independent of tumour stage and grade, EORTC-risk stratification, age and gender. To confirm our findings, Hedegaard et al. (n = 476) and TCGA provisional (n = 413) bladder urothelial carcinoma cohorts were used as validation cohorts for NMIBC and MIBC, respectively. 28,29 The analysis of the validation cohorts confirmed the correlation of GAS5 loss with tumours of high grade, higher stage and of nonpapillary histology. Moreover, Hedegaard et al. validation cohort for NMIBC clearly verified the significantly worse PFS expectancy of the TaT1 patients underexpressing GAS5. On the other hand, MIBC survival analysis of both the screening cohort and the TCGA validation cohort did not show a statistically significant association with patients' survival outcome. This observed discrepancy of GAS5 clinical value for NMIBC and MIBC patients could possibly be attributed to the well-documented diversity of non-muscleinvasive (superficial) and muscle-invasive tumours, regarding cellular origin and molecular background, and clearly highlights the NMIBC-specific prognostic utility of GAS5. Our findings are in line with the well-documented tumoursuppressor role of GAS5, through the inhibition of cell proliferation and the stimulation of apoptosis, in the wide range of human malignancies studied so far. 16,17, Repression of GR transcriptional activity 15,23 and miRNA sponging, have been proposed as the main molecular mechanisms underlying GAS5 tumoursuppressor function. Focusing on BlCa, silencing of GAS5 resulted in enhanced cell proliferation and increased percentage of cells in S/G2 cell-cycle phase, which was mediated by the increased expression of CDK6 (ref. 24 ) and CCL1, 25 in contrast to cell-cycle arrest in G0/G1 phases following GAS5 ectopic expression. 24 Additionally, overexpression of GAS5 was highlighted to stimulate apoptotic cell death and to reduce cell viability by recruiting E2F4 to EZH2 promoter to repress gene expression, 26 as well as to promote doxorubicin-induced apoptosis through depressed expression of BCL2 (ref. 27 ) in BlCa cells. Taking advantage of GAS5 powerful and independent prognostic value for NMIBC, we have evaluated the ability of GAS5 loss to improve the prognostic performance of established disease markers. Indeed, the integration of GAS5 loss resulted in superior positive prediction of disease relapse and progression within Ta/ T1LG, intermediate/high EORTC-risk, and negative FFC patients' groups, and thus in improved risk-stratification specificity. In this regard, decision curve analysis highlighted the superior clinical benefit of the prediction model incorporating GAS5 loss for NMIBC relapse and progression compared to the model of the established and clinically used prognostic markers alone. Overall, our findings clearly support the use of a NMIBC prognosis prediction model, based on GAS5 expression and the independent clinicalpathologic prognostic markers of NMIBC, namely tumour stage, tumour grade and EORTC-risk stratification, using biopsy specimens of TURBT-treated TaT1 patients. This will benefit the identification of the NMIBC patients with higher risk for disease relapse and progression to invasive disease stages, and thus suitable for early curative RC (mainly for T1 patients) or 36 48 Survival of NMIBC (TaT1) patients according to GAS5 levels and tumor stage/grade advanced adjuvant treatment with BCG for high-risk Ta patients. Moreover, this prognosis prediction model could be of assistance in the adjustment of NMIBC patients' post-treatment monitoring to reflect the individual patient's degree of risk. Similarly, a number of novel molecular prognostic markers for NMIBC have been recently documented; thus, large-scale clinical validation studies, based on independent institutional cohorts, will indicate the best-suited multiplex prediction model/algorithm, incorporating both clinicopathological and molecular disease markers. In conclusion, GAS5 tumour-suppressor lncRNA is significantly downregulated in bladder urothelial carcinoma, to the extent that it is able discriminate bladder tumours from the normal bladder urothelium. GAS5 loss was correlated with unfavourable disease features, such as invasive disease stages and HG tumours, as well as high EORTC-risk group and positive FFC of the NMIBC (TaT1) patients. Considering disease outcome, GAS5 loss was strongly associated with higher risk for NMIBC early relapse and progression to invasive disease stages following tumour resection, independently of tumour stage, grade, EORTC-risk score and patient's age and gender. MIBC survival analysis did not revealed a statistically strong association of GAS5 with patients' survival outcome, indicating the lower impact of GAS5 loss in the biology and the clinical behaviour of muscle-invasive tumours, and supporting the NMIBC-specific prognostic value of GAS5. Hedegaard et al. (n = 476) and TCGA provisional (n = 413) validation cohorts clearly confirmed the association of GAS5 loss with invasive and HG tumours of non-papillary histology, as well as with NMIBC adverse disease outcome compared to patients overexpressing GAS5. Finally, prediction models incorporating GAS5 loss resulted in superior stratification specificity and improved positive prediction of NMIBC patients' poor survival outcome following tumour resection, offering a significantly higher clinical benefit for patients' prognosis and monitoring compared to models of the established and clinically used prognostic markers alone. Fig. 6 Decision curve analysis highlights the superior clinical net benefit of models including GAS5 loss, compared to models of the clinically established prognostic markers, for the prediction of NMIBC (TaT1) patients' relapse and progression. Decision curves of prediction models for NMIBC (TaT1) patients' relapse (a) and progression (b). Net benefit is plotted against various ranges of threshold probabilities |
1. Field of the Invention
This invention relates generally to a heatable backlight panel, and more particularly, to a plastic composite backlight panel for convertible vehicles.
2. Background Art
The use of heatable window assemblies for removing ice and snow from the windows of aircraft and similar vehicles are well-known in the art.
U.S. Pat. No. 3,020,376 discloses a laminated plastic panel for aircraft that is electrically conductive so as to be kept free of ice and fog formations. In addition to the polyvinyl butyral sheet, the panel includes a sealer layer, an adhesive layer, an electrically conductive layer, a second adhesive layer, and a protective layer. The electrically conductive layer is deposited onto the panel by thermal evaporation methods.
U.S. Pat. No. 3,041,436 involves a transparent, electrically conductive window for aircraft for anti-fogging and de-icing applications. The window consists of an outer face sheet, an interlayer, and an inner ply. The inner side of the face sheet is coated with an electrically conductive coating.
U.S. Pat. No. 3,180,781 relates to a composite laminated structure consisting of two sheets of rigid plastic sandwiched around an interposed layer. The composite structure is primarily used for aircraft to prevent fogging and icing. An unbroken, electrically conductive film is applied to one of the laminated sheets, and may consist of a series of layers placed over each other. The interposed layer consists of a sealing layer, an adhesive layer, a conducting film layer, and a second adhesive layer.
U.S. Pat. No. 3,636,311 discloses a heating device for defrosting or deicing automobile windows. The layer of conductive material is printed or sprayed onto the surface of the polyester resin sheet. A self-adhesive border surrounds the sheet which is used to subsequently attache the sheet to a window or a windscreen.
Removing ice and snow from the flexible plastic backlight panels manually with scrapers and the like, is a problem because of the likelihood that the plastic will be scratched or otherwise damaged. Defrosting the backlight panel with blasts of hot air requires considerable time for the air to heat up in cold weather, and generally results in uneven heat distribution across the backlight panel.
Much of this prior art technology although applicable to automobiles, was developed primarily for the aircraft industry. Hence, the laminates are made of rigid plastic panels to withstand the extreme temperature and pressure differentials normally encountered at extreme flight altitudes.
Although rigid glass panels which may be heated through a plurality of electrical members mounted within the panels have been used in automobiles for many years, this technology has not bee refined for application to the thinner, flexible, plastic panels that are used in convertible tops. What is needed is an inexpensive, rugged, flexible, composite plastic backlight panel that provides an even heat distribution across the entire surface of the panel. The flexibility of the panel is critical because when the backlight panel is in the raised position, the panel will assume a curved configuration so as to enable the designer to provide sleek lines and an aerodynamically efficient design, but must lie flat in the retracted position for efficient storage. |
<reponame>iwasakishuto/Keras-Imitation<gh_stars>1-10
# coding: utf-8
import numpy as np
import time
from ..utils import printAlignment
from ..utils import flush_progress_bar
from ..clib import c_maxsets
from ..clib._pyutils import extract_continuous_area
class MSS():
""" Maximum Segment Sum """
def __init__(self):
self.score = None # shape=(2,N) Memorize data shape.
self.isin_sets = None # shape=(2,N) Memorize data shape.
@staticmethod
def max_argmax(s0, sL, offset=0, n_memory=1, limit=1):
""" Return Score and TraceBack Pointer Simultaneously
@params s0,sL : score of S^0_n and S^L_n.
@params n : index.
@params limit : minimum length of segment sets.
@params n_memory : The length of memory.
"""
if s0>=sL:
# if we think about s0, we sets limit=1.
return s0,offset+1-limit
else:
return sL,offset+n_memory
def run(self,R,limit,display=True,verbose=1,width=60):
R = np.asarray(R, dtype=float)
n_sequence = len(R)
n_memory = n_sequence+1
if limit==1:
# There is no problem with passing the following function, but this is faster.
isin_sets = np.where(R>=0, 1, 0)
score = np.sum(np.where(R>=0, R, 0))
else:
S, T = c_maxsets.forward(R, limit, verbose=verbose)
score, tp_init = self.max_argmax(*S[:,-1], offset=n_sequence, n_memory=n_memory)
isin_sets = c_maxsets.traceback(T, tp_init, verbose=verbose).astype(np.int32)
self.score = score
self.isin_sets = isin_sets
self.detected_area = np.asarray(extract_continuous_area(isin_sets), dtype=np.int32)
def display(self, isin_sets=None, score=None, width=60):
if isin_sets is None:
isin_sets = self.isin_sets
score = self.score
printAlignment(
sequences=["".join(np.where(isin_sets==1, "*", "-"))],
indexes=[np.arange(len(isin_sets))],
score=score,
add_info="('*' means in sets)",
scorename="Maximum Sets Score",
seqname=["R"],
model=self.__class__.__name__,
width=width,
)
|
SIM2 maintains innate host defense of the small intestine. The single-minded 2 (SIM2) protein is a basic helix-loop-helix transcription factor regulating central nervous system (CNS) development in Drosophila. In humans, SIM2 is located within the Down syndrome critical region on chromosome 21 and may be involved in the development of mental retardation phenotype in Down syndrome. In this study, knockout of SIM2 expression in mice resulted in a gas distention phenotype in the gastrointestinal tract. We found that SIM2 is required for the expression of all cryptdins and numerous other antimicrobial peptides (AMPs) expressed in the small intestine. The mechanism underlying how SIM2 controls AMP expression involves both direct and indirect regulations. For the cryptdin genes, SIM2 regulates their expression by modulating transcription factor 7-like 2, a crucial regulator in the Wnt/-catenin signaling pathway, while for other AMP genes, such as RegIII, SIM2 directly activates their promoter activity. Our results establish that SIM2 is a crucial regulator in controlling expression of intestinal AMPs to maintain intestinal innate immunity against microbes. |
package org.logstash.instrument.metrics;
import org.jruby.Ruby;
import org.jruby.RubyBasicObject;
import org.jruby.RubyClass;
import org.jruby.RubyTime;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyClass(name = "Snapshot")
public final class SnapshotExt extends RubyBasicObject {
private static final long serialVersionUID = 1L;
private IRubyObject metricStore;
private RubyTime createdAt;
public SnapshotExt(final Ruby runtime, final RubyClass metaClass) {
super(runtime, metaClass);
}
@JRubyMethod(required = 1, optional = 1)
public SnapshotExt initialize(final ThreadContext context, final IRubyObject[] args) {
metricStore = args[0];
if (args.length == 2) {
createdAt = (RubyTime) args[1];
} else {
createdAt = (RubyTime) RubyTime.newInstance(context, context.runtime.getTime());
}
return this;
}
@JRubyMethod(name = "metric_store")
public IRubyObject metricStore() {
return metricStore;
}
@JRubyMethod(name = "created_at")
public RubyTime createdAt() {
return createdAt;
}
}
|
/**
* Send Discovery request to server to get list of available sources
*
* @param timeout Given timeout
* @return Whether succeed to send request
*/
@Override
public boolean sendDiscoveryRequest(int timeout)
{
_Logger.info("Discovering resources on CoAP server...");
this.clientConn.setURI("/.well-known/core");
this.clientConn.setTimeout((long)timeout);
if (resources == null){
resources = new HashSet<>();
}
else{
resources.clear();
}
this.clientConn.get(new CoapHandler() {
@Override
public void onLoad(CoapResponse response) {
String[] resourceList = response.getResponseText().split(",");
for (String resource : resourceList) {
String url = resource.replace("<", "").replace(">", "");
_Logger.info("--> URI: " + url);
resources.add(url);
}
}
@Override
public void onError() {
_Logger.warning("Error processing CoAP response for Discovery Request");
}
});
return true;
} |
Effects of back extensor strength training versus balance training on postural control. PURPOSE Aim of this study was to investigate effects of 1) regular back extensor strength training as opposed to balance training, and 2) the influence of the sequence of both training types on postural control, force, and muscle efficiency. METHODS Twenty-six young, healthy subjects were investigated at baseline, 1 month and 2 months later. At each examination, subjects completed a posturographic, balance skill, and isometric maximum voluntary (MVC) back extension testing, including surface electromyographic (SEMG) recordings. After baseline evaluation, subjects were assigned to either daily strength training or balance training. After 1 month, the type of training was exchanged between groups. RESULTS After 1 month, back extensor strengthening led to decreased postural stability on hard surface, whereas there were no change after balance skill training. Analysis of the low- and high-frequency components of the sway signal revealed that strength training increased control efforts as indicated by an increased high-frequency component in order to maintain postural stability and unchanged low-frequency component. Balance skill training, however, increased postural stability as indicated by a decreased low-frequency component. The control effort remained unchanged. After completing either sequence of training, all postural parameters remained unchanged in both groups. Muscular efficiency as measured by SEMG root mean square during a standardized motor skill task revealed improved muscle economy regardless of the type of training. Back extension torque improved in both groups. CONCLUSION To avoid reduction of postural stability in rehabilitation processes, we recommend to include antagonist muscles in a comprehensive strength training regime or balance skill training. |
<reponame>ILW000/SDL_gui<filename>tests/0100_GUI_App(Skia)/skia/modules/skgui/src/GUI_TextUtil.cpp
//
// GUI_TextUtil.cpp
// GUI_EditText
//
// Created by <NAME> on 17/1/2562 BE.
// Copyright © 2562 Jimmy Software Co., Ltd. All rights reserved.
//
#include "GUI_TextUtil.h"
#include <string>
#include "GUI_Utils.h"
//#include <SDL_ttf.h>
//#include <SDL_image.h>
/*
Each byte starts with a few bits that tell you whether it's a single byte code-point, a multi-byte code point, or a continuation of a multi-byte code point. Like this:
0xxx xxxx A single-byte US-ASCII code (from the first 127 characters)
The multi-byte code-points each start with a few bits that essentially say "hey, you need to also read the next byte (or two, or three) to figure out what I am." They are:
110x xxxx One more byte follows
1110 xxxx Two more bytes follow
1111 0xxx Three more bytes follow
Finally, the bytes that follow those start codes all look like this:
10xx xxxx A continuation of one of the multi-byte characters
Since you can tell what kind of byte you're looking at from the first few bits, then even if something gets mangled somewhere, you don't lose the whole sequence.
Ref: https://stackoverflow.com/questions/1543613/how-does-utf-8-variable-width-encoding-work
*/
int GUI_GetPreviousUTF8Index( std::string str, int i ) {
if( i > 0 && i <= str.length() ) {
while( i > 0 ) {
i--;
int c = (str.at(i));
if( c & 0x80 ) {
if( c & 0x40 ) {
return i;
}
}
else {
return i;
}
}
}
return -1;
}
int GUI_isMainUnicodeChar( int unicode ) {
bool result = (unicode == 0xE31 || (unicode >= 0xE34 && unicode <= 0xE3A) || (unicode >= 0xE47 && unicode <= 0xE4E));
return !result;
}
int GUI_GetPreviousMainUTF8Index( std::string str, int i ) {
if( i > 0 && i <= str.length() ) {
int byte_count = 0;
int byte = 0;
while( i > 0 ) {
i--;
int c = (str.at(i));
if( c & 0x80 ) {
if( c & 0x40 ) {
if( (c & 0xf8) == 0xf0 ) {
byte = byte + ((c & 0x07) << (6 * byte_count));
}
else if( (c & 0xf0) == 0xe0 ) {
byte = byte + ((c & 0x0f) << (6 * byte_count));
}
else if( (c & 0xe0) == 0xc0 ) {
byte = byte + ((c & 0x1f) << (6 * byte_count));
}
if( GUI_isMainUnicodeChar(byte))
return i;
byte = 0;
byte_count = -1;
}
else {
byte = byte + ((c & 0x3f) << (6 * byte_count));
}
byte_count++;
}
else {
return i;
}
}
}
return -1;
}
int GUI_GetUnicodeAtIndex( std::string str, int i, int *nextIndex ) {
if( i >= 0 && i < str.length() ) {
int byte_count = 0;
int byte = 0;
while( i < str.length() ) {
int c = (str.at(i));
if( c & 0x80 ) {
if( c & 0x40 ) {
if( (c & 0xf8) == 0xf0 ) {
byte_count = 3;
byte = (c & 0x07);
}
else if( (c & 0xf0) == 0xe0 ) {
byte_count = 2;
byte = (c & 0x0f);
}
else if( (c & 0xe0) == 0xc0 ) {
byte_count = 1;
byte = (c & 0x1f);
}
}
else {
byte = (byte << 6) + (c & 0x3f);
byte_count--;
if( byte_count == 0 ) {
GUI_Log( "Byte: %04X\n", byte );
if( nextIndex ) {
*nextIndex = i+1;
}
return byte;
}
}
}
else {
byte = c;
if( nextIndex ) {
*nextIndex = i+1;
}
return byte;
}
i++;
}
}
return -1;
}
int GUI_GetNextMainUTF8Index( std::string str, int i ) {
if( i >= 0 && i < str.length() ) {
int byte;
int nextI;
byte = GUI_GetUnicodeAtIndex( str, i, &nextI );
i = nextI;
while( i < str.length() ) {
int b = GUI_GetUnicodeAtIndex( str, i, &nextI );
if( GUI_isMainUnicodeChar(b)) {
return i;
}
i = nextI;
}
return nextI;
}
return -1;
}
int GUI_GetTextIndexFromPosition( SkFont & font, std::string str, int x ) {
int nextI;
int i = 0;
while( i < str.length() ) {
nextI = GUI_GetNextMainUTF8Index( str, i );
int w = 0;
// int h = 0;
// TTF_SizeUTF8( font, str.substr(0,nextI).c_str(), &w, &h );
const char *text = str.substr(0,nextI).c_str();
w = font.measureText(text, strlen(text), SkTextEncoding::kUTF8);
if( w > x ) {
return i;
}
i = nextI;
}
return i;
}
|
Temporal Lobe Epilepsy in Patients Older than 50 Years Surgery for Temporal Lobe Epilepsy in Older Patients Boling W, Andermann F, Reutens D, Dubeau F, Caporicci L, Olivier A J Neurosurg 2001;95:242248 Objective The goal of this study was to evaluate the efficacy of surgery for temporal lobe epilepsy (TLE) in older (older than 50 years) patients. Methods The authors conducted a review of all patients aged 50 years or older with TLE surgically treated at the Montreal Neurological Institute and Hospital since 1981 by one surgeon (A.O.). Only patients without a mass lesion were included. Outcome parameters were compared with those of younger individuals with TLE, who were stratified by age at operation. Results In patients aged 50 years and older, the onset of complex partial seizures occurred 5 to 53 years (mean, 35 years) before the time of surgery. Postoperatively, over a mean follow-up period of 64 months, 15 (83%) patients obtained a meaningful improvement, becoming either free from seizures or experiencing only a rare seizure. Most surgery outcomes were similar in both older and younger individuals, except for a trend to more freedom from seizures and increased likelihood of returning to work or usual activities in the younger patients. Note that a patient's long-standing seizure disorder did not negatively affect the ability to achieve freedom from seizures after surgery. Conclusions Surgery for TLE appears to be effective for older individuals, comparing favorably with results in younger age groups, and carries a small risk of postoperative complications. |
<filename>app/src/main/java/com/xseec/eds/util/Generator.java<gh_stars>0
package com.xseec.eds.util;
import android.content.Context;
import android.widget.EditText;
import android.widget.TextView;
import com.github.mikephil.charting.data.Entry;
import com.xseec.eds.R;
import com.xseec.eds.fragment.ActionListFragment;
import com.xseec.eds.fragment.AlarmListFragment;
import com.xseec.eds.fragment.EnergyFragment;
import com.xseec.eds.fragment.ReportFragment;
import com.xseec.eds.fragment.SettingFragment;
import com.xseec.eds.fragment.WorkorderListFragment;
import com.xseec.eds.model.Custom;
import com.xseec.eds.model.Device;
import com.xseec.eds.model.Function;
import com.xseec.eds.model.deviceconfig.Protect;
import com.xseec.eds.model.servlet.Action;
import com.xseec.eds.model.servlet.Alarm;
import com.xseec.eds.model.servlet.Basic;
import com.xseec.eds.model.servlet.Workorder;
import com.xseec.eds.model.tags.StoredTag;
import com.xseec.eds.model.tags.Tag;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Administrator on 2018/7/25.
*/
public class Generator {
public static final String NULL_VALUE = "#";
public static List<Function> genFunctions(Basic basic) {
List<Function> functions = new ArrayList<>();
functions.add(new Function(R.drawable.ic_workorder, R.string.nav_workorder, R.id
.nav_schedule,
WorkorderListFragment.newInstance()));
functions.add(new Function(R.drawable.ic_report, R.string.nav_report, R.id.nav_trend,
ReportFragment
.newInstance()));
functions.add(new Function(R.drawable.ic_alarm, R.string.nav_alarm, R.id.nav_alarm,
AlarmListFragment
.newInstance()));
functions.add(new Function(R.drawable.ic_meter, R.string.nav_energy, R.id.nav_energy,
EnergyFragment
.newInstance(basic.getEnergy())));
functions.add(new Function(R.drawable.ic_action, R.string.nav_action, R.id.nav_action,
ActionListFragment
.newInstance()));
functions.add(new Function(R.drawable.ic_setting, R.string.nav_setting, R.id.nav_setting,
SettingFragment
.newInstance()));
return functions;
}
public static List<Custom> genSettings() {
List<Custom> customList = new ArrayList<>();
customList.add(new Custom(R.drawable.ic_building_blue_700_24dp, R.string.setting_basic,
Custom.CustomType.AREA));
customList.add(new Custom(R.drawable.ic_devices_other_blue_700_24dp, R.string
.setting_device,
Custom.CustomType.ALIAS));
customList.add(new Custom(R.drawable.ic_users_manage, R.string.setting_user,
Custom.CustomType.USER));
customList.add(new Custom(R.drawable.ic_energy_setting, R.string.setting_energy,
Custom.CustomType.ENERGY));
customList.add(new Custom(R.drawable.ic_overview_tag_setting, R.string.setting_overview,
Custom.CustomType.OVERVIEWTAG));
return customList;
}
public static String getResourceString(String name) {
Context context = EDSApplication.getContext();
int resId = context.getResources().getIdentifier(name, "string", context.getPackageName());
if (resId != 0) {
return context.getString(resId);
} else {
return null;
}
}
public static int getImageRes(String imageName) {
Context context = EDSApplication.getContext();
return context.getResources().getIdentifier(imageName,
"drawable", context.getPackageName());
}
public static List<Entry> convertEntryList(List<String> source, float minValue) {
List<Entry> entryList = new ArrayList<>();
for (int i = 0; i < source.size(); i++) {
entryList.add(new Entry(i + minValue, floatTryParse(source.get(i))));
}
return entryList;
}
public static float getAvgFromEntryList(List<Entry> entryList) {
float tmp = 0;
for (Entry entry : entryList) {
tmp += entry.getY();
}
return Math.round(tmp / entryList.size() * 100) / 100f;
}
public static float getSumFromEntryList(List<Entry> entryList, int limitSize) {
float tmp = 0;
for (int i = 0; i < entryList.size() && i < limitSize; i++) {
tmp += entryList.get(i).getY();
}
return tmp;
}
public static float floatTryParse(String source) {
try {
return Float.parseFloat(source);
} catch (Exception exp) {
return 0;
}
}
public static boolean checkIsOne(String switchValue, int index) {
int value = (int) floatTryParse(switchValue);
return (value & (int) Math.pow(2, index)) > 0;
}
public static boolean checkProtectStateZero(String switchValue, List<String> items, String
item) {
int value = (int) floatTryParse(switchValue);
int index = items.indexOf(item);
int indexNegate = items.indexOf(item + Protect.NEGATE);
if (index >= 0) {
return (value & (int) Math.pow(2, index)) == 0;
} else if (indexNegate >= 0) {
return (value & (int) Math.pow(2, indexNegate)) != 0;
} else {
return false;
}
}
public static int setProtectState(String switchValue, List<String> items, String item,
boolean switchOn) {
int value = (int) floatTryParse(switchValue);
int index = items.indexOf(item);
int indexNegate = items.indexOf(item + Protect.NEGATE);
if (index >= 0) {
return switchOn ? (value | (int) (Math.pow(2, index))) : (value & (int) (Math.pow(2,
16) - 1 - Math.pow(2, index)));
} else if (indexNegate >= 0) {
return (!switchOn) ? (value | (int) (Math.pow(2, indexNegate))) : (value & (int)
(Math.pow(2,
16) - 1 - Math.pow(2, indexNegate)));
} else {
return value;
}
}
public static String getAlarmStateText(String status, List<String> items) {
int value = (int) floatTryParse(status);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
int index = value & (int) Math.pow(2, i);
if (index > 0 && !items.get(i).equals("*")) {
stringBuilder.append(items.get(i) + " ");
}
}
String result = stringBuilder.toString();
return result.trim();
}
public static String getAlarmStateTextWithTag(Tag tag) {
Device device = Device.initWith(tag.getTagName());
return getAlarmStateText(tag.getTagValue(), device.getStatusItems());
}
public static float getAvgTagsValue(List<Tag> tagList) {
float sum = 0;
for (Tag tag : tagList) {
sum += floatTryParse(tag.getTagValue());
}
return Math.round(sum / tagList.size());
}
public static float getMaxDeltaTagsValue(List<Tag> tagList) {
float avg = getAvgTagsValue(tagList);
float max = 0;
for (Tag tag : tagList) {
float tmp = Math.abs(floatTryParse(tag.getTagValue()) - avg) / avg * 100;
max = tmp > max ? tmp : max;
}
return Math.round(max * 10) / 10f;
}
public static List<String> genPerEnergyEntryList(List<String> totals) {
List<String> pers = new ArrayList<>();
for (int i = 1; i < totals.size(); i++) {
float now = floatTryParse(totals.get(i));
float pre = floatTryParse(totals.get(i - 1));
//暂时方案,数据清零等操作造成累加值突变or通信异常造成pre为0
now = (pre == 0 || now == 0) ? 0 : now - pre;
pers.add(String.valueOf(now));
}
return pers;
}
public static String removeFuture(String jsonData) {
return jsonData.replaceAll("(,\"#\")+]", "]");
}
public static List<String> getMonthList(List<String> dayList, Calendar start) {
int index = 0;
int toIndex;
List<String> result = new ArrayList<>();
List<String> tmps = null;
while (index < dayList.size()) {
toIndex = index + start.getActualMaximum(Calendar.DAY_OF_MONTH);
toIndex = toIndex > dayList.size() ? dayList.size() : toIndex;
tmps = dayList.subList(index, toIndex);
result.add(String.valueOf(calSum(tmps)));
index = toIndex;
start.add(Calendar.MONTH, 1);
}
return result;
}
public static int calSum(List<String> yValues) {
int sum = 0;
for (String value : yValues) {
if (value.equals(StoredTag.NULL_VALUE)) {
continue;
}
sum += Generator.floatTryParse(value);
}
return sum;
}
/*
*在数值数组中找到最接近的值
* eg:<items>0.8,0.9,0.95,1</items>
* 630*0.95=598.5,取整599,反馈599/630=0.951,取近值0.95
*/
public static int getNearestIndex(String item, List<String> items) {
if (items.contains(item)) {
return items.indexOf(item);
} else {
float f0 = Generator.floatTryParse(item);
float delta0 = Float.MAX_VALUE;
int index = 0;
for (int i = 0; i < items.size(); i++) {
float f = Generator.floatTryParse(items.get(i));
float delta = Math.abs(f - f0);
if (delta < delta0) {
index = i;
delta0 = delta;
}
}
return index;
}
}
public static List<String> addTwoTagLogs(List<String> first, List<String> secend) {
int length = Math.max(first.size(), secend.size());
List<String> result = new ArrayList<>();
String str1, str2;
for (int i = 0; i < length; i++) {
str1 = getListItem(first, i);
str2 = getListItem(secend, i);
if (str1.equals(StoredTag.NULL_VALUE) && str2.equals(StoredTag.NULL_VALUE)) {
result.add(StoredTag.NULL_VALUE);
} else {
float value = floatTryParse(str1) + floatTryParse(str2);
result.add(String.valueOf(value));
}
}
return result;
}
private static String getListItem(List<String> list, int index) {
return index >= list.size() ? StoredTag.NULL_VALUE : list.get(index);
}
/*
*两个float/double操作,很可能出错,缘由见于网络
*特别注意:value1/value2类型应该为String,若未float/double还是会计算失真
*/
public enum Operator {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
public static String calFloatValue(String value1, String value2, Operator operator) {
BigDecimal d1 = new BigDecimal(value1);
BigDecimal d2 = new BigDecimal(value2);
switch (operator) {
case ADD:
return d1.add(d2).toString();
case SUBTRACT:
return d1.subtract(d2).toString();
case MULTIPLY:
return d1.multiply(d2).toString();
case DIVIDE:
//BigBecimal必须加后两个参数,否则会出错
return d1.divide(d2, 3, BigDecimal.ROUND_HALF_UP).toString();
default:
return null;
}
}
//nj--统计list的尺寸 2018/11/19
public static String countList(List sources) {
return sources != null ? String.valueOf(sources.size()) : "0";
}
//nj--获取报表时间段信息 2018/11/19
public static String getReportTime(String startTime, String endTime) {
Date start = DateHelper.getServletDate(startTime);
Date end = DateHelper.getServletDate(endTime);
Context context = EDSApplication.getContext();
String time = context.getString(R.string.workorder_time, DateHelper.getYMDString(start),
DateHelper.getYMDString(end));
return time;
}
//nj--工单信息筛选 2018/11/19
public static List<Workorder> filterWorkorderListOfState(List<Workorder> sources, int state) {
List<Workorder> workorderList = new ArrayList<Workorder>();
if (state == -1) {
workorderList.addAll(sources);
} else {
for (Workorder workorder : sources) {
if (workorder.getWorkorderState().ordinal() == state) {
workorderList.add(workorder);
}
}
}
return workorderList;
}
public static List<Workorder> filterWorkorderListOfType(List<Workorder> sources, int type) {
List<Workorder> workorderList = new ArrayList<>();
if (type == -1) {
workorderList.addAll(sources);
} else {
for (Workorder workorder : sources) {
if (workorder.getType() == type) {
workorderList.add(workorder);
}
}
}
return workorderList;
}
//nj--异常管理信息筛选 2018/11/19
public static List<Alarm> filterAlarmConfirm(List<Alarm> sources, int confirm) {
List<Alarm> alarmList = new ArrayList<>();
if (confirm == -1) {
alarmList.addAll(sources);
} else {
for (Alarm alarm : sources) {
if (alarm.getConfirm() == confirm) {
alarmList.add(alarm);
}
}
}
return alarmList;
}
public static List<Alarm> filterAlarmDevice(List<Alarm> sources, String device) {
List<Alarm> alarmList = new ArrayList<>();
for (Alarm alarm : sources) {
if (alarm.getDevice().equals(device)) {
alarmList.add(alarm);
}
}
return alarmList;
}
//nj--操作信息筛选 2018/11/19
public static List<Action> filterActionsType(List<Action> sources, int type) {
List<Action> actionList = new ArrayList<>();
if (type == -1) {
actionList.addAll(sources);
} else {
for (Action action : sources) {
if (action.getActionType().ordinal() == type)
actionList.add(action);
}
}
return actionList;
}
public static List<Action> filterActionsMethod(List<Action> sources, int method) {
List<Action> actionList = new ArrayList<>();
for (Action action : sources) {
if (action.getActionMethod().ordinal() == method)
actionList.add(action);
}
return actionList;
}
//nj--环境报表数据总数、平均值2018/11/25
public static String getReportMax(List<String> sources) {
float avg = Float.valueOf(getReportAve(sources));
float max = 0;
for (String value : sources) {
float tmp = floatTryParse(value);
max = floatTryParse(value) > max ? floatTryParse(value) : max;
}
return String.valueOf(Math.round(max * 10) / 10f);
}
public static String getReportMin(List<String> sources) {
float avg = Float.valueOf(getReportAve(sources));
float min = 0;
for (String value : sources) {
float tmp = floatTryParse(value);
min = tmp < avg ? tmp : avg;
}
return String.valueOf(Math.round(min * 10) / 10f);
}
public static String getReportSum(List<String> sources) {
float sum = 0;
for (String value : sources) {
sum += Generator.floatTryParse(value);
}
return String.valueOf(sum);
}
public static String getReportAve(List<String> sources) {
float sum = 0;
for (String value : sources) {
sum += floatTryParse(value);
}
float ave = Math.round(Float.valueOf(sum) / sources.size() * 100) / 100f;
return String.valueOf(ave);
}
public static String getPhoneShow(String input){
input=getPhoneValue(input);
Pattern pattern=Pattern.compile("(\\d{3})(\\d{4})(\\d{4})");
Matcher matcher=pattern.matcher(input);
if(matcher.find()){
return String.format("%1$s %2$s %3$s",matcher.group(1),matcher.group(2),matcher.group(3));
}else {
return input;
}
}
public static String getPhoneValue(String input){
return input.replaceAll("\\D","");
}
}
|
As it has for months now, People’s World again this past week carried a headline hailing Bernie Sanders “revolution.” As the successor to the Soviet-funded and directed Daily Worker, and as ongoing house organ of Communist Party USA, People’s World is pleased with the long march of “progress” in the Democratic Party. The far-left lurch of today’s Democratic Party is lovingly in line with what the comrades have long desired. These inheritors of the Soviet experiment see Bernie Sanders as an exciting culmination of what they have been fighting for. And they view Barack Obama’s “fundamental transformation” of the Democratic Party as having made a candidate like Bernie possible.
The campaign of Sen. Bernie Sanders is making a unique contribution to defeating the Republican right and has the potential to galvanize long-term transformative change. The campaign is also a movement. Millions are fed up with the same old establishment politics tied to Wall Street and the 1 per cent. It's reminiscent of the 2008 and 2012 Obama campaigns…. Seeds of change are being sown and foundations are being laid for deeper-going changes in the future….
But Sanders understands if he is elected his radical economic and social agenda including breaking up the big banks, universal health care, tuition-free university, massive jobs creation, expanding Social Security, and repealing Citizen's United will go nowhere given the vice grip the GOP and extreme right has on Congress.
The only way to realize a radical agenda is through a "political revolution."… Sanders sees his campaign as part of a much bigger movement that must be built.
A political revolution rests on building a broad coalition…. A political revolution will be fueled by ongoing shifts in public attitudes. Majorities of Americans now favor taxing the rich, raising the minimum wage, immigration reform, abortion rights, marriage equality, criminal justice reform, and action to curb the climate crisis. New social movements are influencing millions at the grassroots including the Fight for 15, Black Lives Matter, The Dreamers, reproductive rights, marriage equality, and climate justice activists.
A political revolution is based on the idea that majorities make change. It is not enough for majorities to believe in an idea, they must actively fight for it…. Movements are acting both within and outside the Democratic Party and comprise many of the key forces in the anti-right alliance.
A political revolution can transform politics if labor, its allies and the broad left put their stamp on the multi-class alliance, shape its politics and frame the issues debated for the elections. The Sanders campaign is helping do this…. It will be transformative if the anti-right coalition is united and mobilized. Polls show that 86% of Clinton supporters will support Sanders in the general election if he is the nominee, and 79% of Sanders supporters will support Clinton if she wins. Sanders will need Clinton's supporters in order to win.
Note, remarkably, the vast support for Sanders that exists not only among his own comrades but among Hillary Clinton backers. This is support, of course, for a man who has long been an avowed, unapologetic socialist, who was fully sympathetic to the communist universe.
Workers of the world, unite — against “transphobia!” Who would have foreseen that one? Karl Marx, call your office.
Some Democrats reading this will lash out at me, as the messenger. But I urge them to again carefully read the words I’m quoting. They come directly from the head of Communist Party USA, a man who is the successor to Gus Hall, to Earl Browder, to William Z. Foster, writing in the house organ of CPUSA, People’s World, successor to the Daily Worker. I ask Democrats: Does it not concern you that your no. 2 for the presidential nomination so fires up these literal communists? Does that not bother you?
Indeed, the Sanders campaign could mass-produce bumper stickers boldly touting “Bolsheviks for Bernie” sandwiched between grinning faces of Marx and Lenin and our contemporary products of the American university would shrug and cheer.
There we are, ladies and gentlemen. The new political revolution that “will continue” must come either with a breakaway from the Democratic Party or with a “takeover of the Democratic Party.” Once upon a time in America, it seemed it could have only come with a breakaway. But now, in the Obama-Bernie America, a takeover of the Democrats has greater promise than ever. Just ask the literal millions of modern Democrats pulling the lever for a 74-year-old socialist as their next president. And just ask Bernie Sanders’ advocates in Communist Party USA. They, too, feel the Bern. |
<gh_stars>0
#!usr/bin/env python3
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2020 Westwood Robotics"
__date__ = "Jan 8, 2020"
__version__ = "0.1.0"
__status__ = "Beta"
import time
import os
import sys
from pathlib import Path
from Play.motor_controller import MotorController
from Play.dynamixel_controller import DynamixelController
from Settings.Robot import *
import matplotlib.pyplot as plt
import math
if EXTERNAL_ENC:
# Only import the following when EXTERNAL_ENC is True as wiringpi and spidev are required.
import Forward_Kinematics.forward_kin as FK
from Play.MPS import MPS_Encoder_Cluster
import pdb
# -----------------------------
# Functions for basic robot motions
# Enable all before sending commands
def read_initials():
# Read initals file
filename = 'Settings/initials.txt'
filepath = os.path.join(str(Path(os.getcwd())), filename)
# filepath = os.path.join(str(Path(os.getcwd()).parent), filename)
initials = open(filepath, 'r')
data = initials.read()
# String to num
# Get rid of \n if any
if data[-1] == '\n':
data = data[:-1]
# Convert to list of int and float
init_data = []
data = list(data.split("\n"))
for data_string in data:
data_list = list(data_string.split(","))
data_list[0] = data_list[0][1:-1]
data_list[1] = int(data_list[1])
data_list[2:] = [float(i) for i in data_list[2:]]
init_data.append(data_list)
return init_data
class RobotController(object):
def __init__(self, robot=None, bypass_DXL=False, bypass_ext_enc=False):
if robot is None:
print("Robot set to DAnTE by default")
robot = RobotDataStructure("DAnTE", "/dev/ttyUSB0", 8000000, "/dev/ttyUSB1", 2000000, PALM, [INDEX, INDEX_M, THUMB])
self.robot = robot
self.MC = MotorController(self.robot.BEAR_baudrate, self.robot.BEAR_port)
# When debug, you might want to bypass Dynamixel
self.bypass_DXL = bypass_DXL
if self.bypass_DXL:
self.DC = None
else:
self.DC = DynamixelController(self.robot.palm.motor_id, self.robot.DXL_port, self.robot.DXL_baudrate)
if not EXTERNAL_ENC:
# Force to bypass external encoders when EXTERNAL_ENC=None
bypass_ext_enc = True
# When debug, you might want to bypass external encoders
self.bypass_ext_enc = bypass_ext_enc
if self.bypass_ext_enc:
self.ext_enc = None
else:
self.ext_enc = MPS_Encoder_Cluster("MA310", BUS, robot.encoders, MAX_SPI_SPEED, SPI_MODE)
# self.robot.DXL_port)
# self.gesture = None
self.mode = None
self.approach_speed = None
self.approach_stiffness = None
self.detect_current = None
self.final_strength = None
self.max_iq = None
self.logging = False
self.contact_position = [0, 0, 0]
self.balance_factor = [1, 1, 1] # Factor for force balance between fingers, update when change gesture
self.welcome_msg()
# self.start_robot()
def welcome_msg(self):
print("=========== DAnTE version 2.0.0 -- Last Updated 2020.06.24 ===")
print("==============================================================")
# ------------------------
# INITIALIZATION FUNCTIONS
# ------------------------
# Functions for initialization of finger(s)
# Read initials.txt and check settings
# Move finger(s) through range of motion according to initials.txt and check for mobility and interference
def start_robot(self):
error = 0b0000 # 4 bit respectively for INDEX, INDEX_M, THUMB, Dynamixel, 0b10000 for overall error.
# Ping all motors
# Specify PING_TRAIL_COUNT in Constants_DAnTE
# BEAR:
for idx, f in enumerate(self.robot.fingerlist):
trail = 0
check = False
print("Pinging %s..." % f.name)
while not check:
if not bool(self.MC.pbm.ping(f.motor_id)):
trail += 1
if trail > PING_TRAIL_COUNT:
# Tried PING_TRAIL_COUNT times and still no luck:
print("ERROR: %s offline." % f.name)
error = error | (1 << idx)
break
# Retry in 0.5s
# print("Retry in 0.5 second.")
time.sleep(0.5)
else:
# Ping succeed
check = True
if trail > int(PING_TRAIL_COUNT / 2):
# WARNING about bad communication
print("WARNING: %s BEAR communication intermittent." % f.name)
# DXL:
if not self.bypass_DXL:
trail = 0
check = False
print("Pinging Palm actuator...")
while not check:
if not self.DC.ping():
trail += 1
if trail > PING_TRAIL_COUNT:
# Tried PING_TRAIL_COUNT times and still no luck:
print("ERROR: Palm actuator offline.")
error = error | (1 << 3)
break
# Retry in 0.5s
# print("Retry in 0.5 second.")
time.sleep(0.5)
else:
# Ping succeed
check = True
if trail > int(PING_TRAIL_COUNT / 2):
# WARNING about bad communication
print("WARNING: Palm actuator communication intermittent.")
# Read initials, fact check and populate robot object
init_data = read_initials() # init_data = [['FINGER', motor_id, homing_offset, travel, encoder_offset]...]
if not self.bypass_DXL and len(init_data) < 4:
print("Length of init_data is too short. Exiting...")
error = 0b10000
return error
for idx, f in enumerate(self.robot.fingerlist):
if f.name != init_data[idx][0]:
print("init_data.name does not match for %s." % f.name)
error = error | (1 << idx)
elif f.motor_id != init_data[idx][1]:
print("init_data.motor_id does not match for %s." % f.name)
error = error | (1 << idx)
else:
f.homing_offset = init_data[idx][2]
f.travel = init_data[idx][3]
if not self.bypass_ext_enc:
f.encoder_offset = init_data[idx][4]
if not self.bypass_DXL:
if self.robot.palm.name != init_data[3][0]:
print("init_data.name does not match for %s." % self.robot.palm.name)
error = error | (1 << 3)
elif self.robot.palm.motor_id != init_data[3][1]:
print("init_data.motor_id does not match for %s." % self.robot.palm.name)
error = error | (1 << 3)
else:
self.robot.palm.home = init_data[3][2]
self.robot.palm.travel = init_data[3][3]
if error:
print("Failed to start robot.")
sys.exit()
else:
# Set Current, Velocity and Position PID as well as safe iq_max and velocity_max, and clear Direct Force PID.
self.MC.init_driver_all()
self.robot.booted = True
print("Welcome aboard, Captain.")
# return error
def get_robot_enable(self):
"""
See if all motors are enabled
:return: bool
"""
if self.bypass_DXL:
enable = sum(self.MC.get_enable_all()) == 3
else:
enable = (sum(self.MC.get_enable_all())+self.DC.get_enable()) == 4
return enable
def set_robot_enable(self, val):
# Enable/disable all actuators
if self.bypass_DXL:
self.MC.torque_enable_all(val)
else:
self.MC.torque_enable_all(val)
self.DC.torque_enable(val)
def idle(self, *fingers):
# Put specified finger into idle.
# If no finger specified, put whole hand in IDLE
# Dynamixel hold current position
# Related BEAR enters position mode and go to home with IDLE gains.
if not self.bypass_DXL:
palm_pos = self.DC.get_present_position()
self.DC.set_goal_position(palm_pos)
if len(fingers) == 0:
fingers = self.robot.fingerlist
for f in fingers:
self.MC.pbm.set_bulk_config((f.motor_id, 'p_gain_position', IDLE_P,
'i_gain_position', IDLE_I,
'd_gain_position', IDLE_D))
self.MC.set_mode(f.motor_id, 'position')
self.MC.torque_enable(f.motor_id, 1)
self.MC.pbm.set_goal_position((f.motor_id, 0))
print("%s in idle." % f.name)
def initialization(self):
# Full hand initialization.
# Check if booted
if self.robot.booted:
pass
else:
print("Run start_robot first.")
return False
abnormal = [0, 0, 0, 0]
# [Fingers, Palm] abnormal code:
# 10000 External encoder offset discrepancy
# 01000 Failed to travel to home
# 00100 Failed to fully close
# 00010 Position out of range
# 00001 home_offset abnormal
# 0. Check PALM first
if not self.bypass_DXL:
# Compare DXL homing_offset
if self.DC.get_homing_offset() != 0:
print("Palm actuator needs calibration.\nCalibrate it first, or run with bypass_DXL option.")
abnormal[3] = 0b00001
return False
else:
# Check if position in range, home ~ home+pi/2
palm_pos = self.DC.get_present_position()
if (self.robot.palm.home-0.2)<palm_pos<(self.robot.palm.home+1.77):
pass
else:
print("Palm actuator needs calibration.\nCalibrate it first, or run with bypass_DXL option.")
abnormal[3] = 0b00010
return False
# bypass_DXL or PALM checked
if self.bypass_DXL:
usr = input("Turn index fingers to parallel gesture then press enter.")
else:
print("Changing to Parallel gesture...")
self.DC.torque_enable(1)
self.DC.set_goal_position(self.robot.palm.home)
time.sleep(0.5)
self.robot.palm.angle = 0
self.MC.init_driver_all()
# 1. Compare home_offset
for i in range(3):
if round(self.robot.fingerlist[i].homing_offset, 2) != round(
self.MC.pbm.get_homing_offset(self.robot.finger_ids[i])[0][0], 2):
abnormal[i] = abnormal[i] | 0b0001
print("%s home_offset abnormal." % self.robot.fingerlist[i].name)
# 2. Current position with in range
present_pos = self.MC.pbm.get_present_position(BEAR_INDEX, BEAR_INDEX_M, BEAR_THUMB)
for i, pos in enumerate(present_pos):
if self.robot.fingerlist[i].mirrored:
if pos[0] < -0.1 or pos[0] > self.robot.fingerlist[i].travel + 0.1:
abnormal[i] = abnormal[i] | 0b0010
print("%s present_pos out of range." % self.robot.fingerlist[i].name)
print(pos[0])
else:
if pos[0] > 0.1 or pos[0] < self.robot.fingerlist[i].travel - 0.1:
abnormal[i] = abnormal[i] | 0b0010
print("%s present_pos out of range." % self.robot.fingerlist[i].name)
print(pos[0])
# # 3. Check for position Limit
# limit_min = self.MC.pbm.get_limit_position_min(m_id)[0]
# limit_max = self.MC.pbm.get_limit_position_max(m_id)[0]
# if limit_min != end_pos or limit_max != 0:
# abnormal = True
# print("Position limit abnoraml")
# Ask user if abnoraml
if sum(abnormal):
usr = input("Fingers seem to need calibration. Do you want to continue anyway?(y/n)")
if usr == "n" or usr == "N":
return False
else:
pass
# Set motor mode and PID
# Set mode and limits
self.MC.set_mode_all('position')
# 4. Move to End -> complete
running = [True, True, True]
self.MC.torque_enable_all(1)
self.MC.pbm.set_goal_position((BEAR_INDEX, self.robot.fingerlist[0].travel),
(BEAR_INDEX_M, self.robot.fingerlist[1].travel),
(BEAR_THUMB, self.robot.fingerlist[0].travel))
start_time = time.time()
while sum(running):
try:
status = self.MC.pbm.get_bulk_status((INDEX.motor_id, 'present_position', 'present_velocity'),
(INDEX_M.motor_id, 'present_position', 'present_velocity'),
(THUMB.motor_id, 'present_position', 'present_velocity'))
err = [data[1] for data in status]
position = [data[0][0] for data in status]
# velocity = [data[0][1] for data in status]
elapsed_time = time.time() - start_time
if elapsed_time < TIMEOUT_INIT:
for i in range(3):
if running[i] and abs(position[i] - self.robot.fingerlist[i].travel) < 0.015:
running[i] = False
self.MC.damping_mode(self.robot.finger_ids[i])
print("%s end travel complete." % self.robot.fingerlist[i].name)
else:
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], self.robot.fingerlist[i].travel))
if err[i] != 128 and err[i] != 144:
print("%s error, code:" % self.robot.fingerlist[i].name, bin(err[i]))
else:
print("Timeout while moving to end. Is there something blocking the finger(s)?")
print("Abnormal:")
for i in range(3):
if running[i]:
abnormal[i] = abnormal[i] | 0b0100
print(self.robot.fingerlist[i].name)
self.MC.damping_mode_all()
running = [False, False, False]
except KeyboardInterrupt:
running = [0]
print("User interrupted.")
time.sleep(0.5)
# 5. Move to Home -> complete
print("Fingers resetting...")
running = [True, True, True]
# Enable torque and go to Home
self.MC.damping_release_all()
self.MC.torque_enable_all(1)
self.MC.pbm.set_goal_position((THUMB.motor_id, 0),
(INDEX.motor_id, 0),
(INDEX_M.motor_id, 0))
time.sleep(2)
# pdb.set_trace()
start_time = time.time()
while sum(running):
try:
status = self.MC.pbm.get_bulk_status((INDEX.motor_id, 'present_position', 'present_velocity'),
(INDEX_M.motor_id, 'present_position', 'present_velocity'),
(THUMB.motor_id, 'present_position', 'present_velocity'))
err = [data[1] for data in status]
position = [data[0][0] for data in status]
# velocity = [data[0][1] for data in status]
elapsed_time = time.time() - start_time
if elapsed_time < TIMEOUT_INIT:
for i in range(3):
if abs(position[i]) < 0.1:
running[i] = False
self.MC.torque_enable(self.robot.finger_ids[i], 0)
else:
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], 0))
if err[i] != 128:
print("%s error, code:" % self.robot.fingerlist[i].name, bin(err[i]))
else:
print("Timeout while resetting. Is there something blocking the finger(s)?")
print("Abnormal:")
for i in range(3):
if running[i]:
abnormal[i] = abnormal[i] | 0b1000
print(self.robot.fingerlist[i].name)
self.MC.torque_enable(self.robot.finger_ids[i], 0)
running = [False, False, False]
except KeyboardInterrupt:
running = [0]
print("User interrupted.")
# 6. Check external encoder reading and offset
if not self.bypass_ext_enc:
self.ext_enc.connect()
time.sleep(0.2)
ext_reading = self.ext_enc.get_angle()
self.ext_enc.release()
for idx, finger in enumerate(self.robot.fingerlist):
if 0.18 < abs(ext_reading[idx] - finger.encoder_offset) < 6.1:
# External encoder reading differs from the record for too much
ext_enc_error = True
abnormal[idx] = abnormal[idx] | 0b10000
print("%s external encoder abnormal." % finger.name)
print("ext_reading: %f" % ext_reading[idx])
print("encoder_offset: %f" % finger.encoder_offset)
# 7. Finger initialization complete
# Disable and finish
self.set_robot_enable(0)
if sum(abnormal):
print("Initialization failed.")
for idx, code in enumerate(abnormal):
if code:
print("%s abnormal, error code: %d" % (self.robot.fingerlist[idx].name, code))
return False
else:
print("Initialization Complete.")
for f in self.robot.fingerlist:
f.initialized = True
self.robot.palm.initialized = True
self.robot.initialized = True
return True
# ------------------------
# MOTION FUNCTIONS
# ------------------------
# Functions for DAnTE motions
# Change gesture
# Control grab and release motion of self.robot
def change_gesture(self, new_gesture):
# TODO: Create shallow_release function so that the index fingers release to slightly away from home for
# gesture change, then fully release.
# Change the gesture of DAnTE
# Will Fully release first.
# Check initialization
if not self.robot.initialized:
error = 3
print("Robot not initialized. Exit.")
return error
# Check enable first
if self.get_robot_enable():
pass
else:
print("WARNING: Robot not enabled, enabling now.")
self.set_robot_enable(1)
# if self.gesture == new_gesture:
if self.robot.palm.gesture == new_gesture:
# No need to change
print('Already in gesture %s.' % new_gesture)
return True
if new_gesture not in ['Y', 'I', 'P']:
# Check for invalid input
print("Invalid input.") # TODO: Throw an exception
return False
else:
# change the new_gesture of self.robot to: tripod(Y), pinch(I) or parallel(P)
# Reset all fingers under present gesture before changing gesture
self.release('F')
# Gesture change operations
if new_gesture == 'Y':
# Change to tripod
print("Changing to Tripod.")
if self.bypass_DXL:
usr = input("Bypass_DXL, please manually change DAnTE to Tripod mode, and press enter.")
else:
DXL_goal_pos = self.robot.palm.home+math.pi/3
self.robot.palm.angle = math.pi/3
self.DC.set_goal_position(DXL_goal_pos)
# self.gesture = 'Y'
# Update balance_factor
self.balance_factor = [1, 1, 1]
elif new_gesture == 'I':
# Change to pinch
print("Changing to Pinch.")
if self.bypass_DXL:
usr = input("Bypass_DXL, please manually change DAnTE to Pinch mode, and press enter.")
else:
DXL_goal_pos = self.robot.palm.home + math.pi / 2 * (15 / 16)
self.robot.palm.angle = math.pi / 2
self.DC.set_goal_position(DXL_goal_pos)
time.sleep(0.5)
# self.gesture = 'I'
# Update balance_factor
self.balance_factor = [1, 1, 1]
# Set THUMB in IDLE
self.idle(THUMB)
else:
# Change to parallel
print("Changing to Parallel.")
if self.bypass_DXL:
usr = input("Bypass_DXL, please manually change DAnTE to Parallel mode, and press enter.")
else:
DXL_goal_pos = self.robot.palm.home
self.robot.palm.angle = 0
self.DC.set_goal_position(DXL_goal_pos)
# self.gesture = 'P'
# Update balance_factor
self.balance_factor = [1, 1, 2]
# Check if DXL still moving before exiting
if not self.bypass_DXL:
running = True
while running:
try:
if self.DC.get_present_velocity()<0.05:
time.sleep(0.25)
running = False
except KeyboardInterrupt:
print("User interrupted.")
running = False
return False
# Update robot.palm
self.robot.palm.gesture = new_gesture
return True
def set_approach_stiffness(self):
# Set the P,D gains for Direct Force mode according to approach_stiffness
force_p = self.approach_stiffness
force_d = 0.1 * force_p
if self.robot.palm.gesture == 'I':
# Leave THUMB along if in pinch mode
# Change the force PID of INDEX fingers
self.MC.pbm.set_p_gain_force((BEAR_INDEX, force_p), (BEAR_INDEX_M, force_p))
self.MC.pbm.set_d_gain_force((BEAR_INDEX, force_d), (BEAR_INDEX_M, force_d))
elif self.robot.palm.gesture == 'Y' or self.robot.palm.gesture == 'P':
# Change the force PID of all fingers
self.MC.pbm.set_p_gain_force((BEAR_THUMB, force_p), (BEAR_INDEX, force_p), (BEAR_INDEX_M, force_p))
self.MC.pbm.set_d_gain_force((BEAR_THUMB, force_d), (BEAR_INDEX, force_d), (BEAR_INDEX_M, force_d))
else:
print("Invalid gesture status.") # TODO: Throw exception
return False
print("Approach Stiffness set.")
return True
def grab(self, gesture, mode, **options):
# Control grab motion of self.robot
# Grab with a gesture, tripod(Y), pinch(I) or parallel(P)
# Specify a grab mode: (H)old or (G)rip
# Optional kwargs: (if not specified, go with a default value)
# - Approach speed (approach_speed)
# - Approach stiffness (approach_stiffness)
# - Detection current (detect_current)
# - Grip force/Hold stiffness (final_strength)
# - Maximum torque current (max_iq)
# - Data log function (logging)
error = 0 # 1 for timeout, 2 for user interruption, 3 for initialization, 9 for Invalid input
# Check initialization
if not self.robot.initialized:
error = 3
print("Robot not initialized. Exit.")
return error
# Check enable and enable system if not.
if not self.get_robot_enable():
self.MC.torque_enable_all(1)
# 0. Prep
# Check input
if gesture not in ['Y', 'I', 'P']:
print("Invalid gesture input.")
error = 9
return error
elif mode not in ['H', 'G']:
print("Invalid mode input.")
error = 9
return error
else:
# Sort out all function input data.
self.mode = mode
# Options:
self.approach_speed = max(options.get("approach_speed", default_approach_speed), approach_speed_min)
self.approach_stiffness = max(options.get("approach_stiffness", default_approach_stiffness),
approach_stiffness_min)
self.detect_current = max(options.get("detect_current", default_detect_current), detect_current_min)
self.final_strength = options.get("final_strength", default_final_strength)
self.max_iq = max(options.get("max_iq", default_max_iq), self.detect_current, default_max_iq)
self.logging = options.get("logging", False)
# Calculate approach_i from approach_stiffness
approach_i = approach_i_func(self.approach_stiffness)
# Set detect_count if detect_current is below confident value
if self.detect_current < confident_detect_current:
detect_count = [detect_confirm, detect_confirm, detect_confirm]
else:
detect_count = [0, 0, 0]
contact_count = 0
# Calculate goal_approach_speed
goal_approach_speed = [-self.approach_speed + 2 * self.approach_speed * f.mirrored for f in
self.robot.fingerlist]
# Start with change into gesture
self.change_gesture(gesture)
# Set fingers' Direct Force PID according to Stiffness
self.set_approach_stiffness()
# Set into Direct Force Mode
self.MC.set_mode_all('force')
# Set iq_max
for f_id in self.robot.finger_ids:
self.MC.pbm.set_limit_iq_max((f_id, self.max_iq))
if self.robot.palm.gesture == 'P':
# Double THUMB iq_limit in Parallel mode
self.MC.pbm.set_limit_iq_max((THUMB.motor_id, 2 * self.max_iq))
# Enforce writing
check = False
while not check:
if round(self.MC.pbm.get_limit_iq_max(THUMB.motor_id)[0][0], 4) == round(2 * self.max_iq, 4):
check = True
# usr = input("Press enter to grab...")
# 3. Fingers close tracking approach_speed, switch to final grip/hold upon object detection
if self.robot.contact:
print("Please release contact first.")
return
else:
print("Approaching...")
# Get start_time
# Python Version 3.7 or above
# start_time = time.time_ns()/1000000000 # In ns unit
start_time = time.time()
present_time = start_time
# Initialize status variables
finger_count = 0
velocity = [0, 0, 0]
prev_velocity = [0, 0, 0]
velocity_error = [0, 0, 0]
velocity_error_int = [0, 0, 0]
acceleration = [0, 0, 0]
iq = [0, 0, 0]
iq_comp = [0, 0, 0]
goal_iq = [0, 0, 0]
position = [0, 0, 0]
approach_command = [0, 0, 0]
# Status logging
velocity_log = []
position_log = []
time_log = []
delta_time_log = []
iq_log = []
iq_comp_log = []
acceleration_log = []
while not (error or self.robot.contact):
try:
previous_time = present_time
# Collect status
if self.robot.palm.gesture == 'I':
status = self.MC.get_present_status_index()
finger_count = 2
else:
status = self.MC.get_present_status_all()
finger_count = 3
# Get time stamp
present_time = time.time()
delta_time = present_time - previous_time
# Process data
# Motor Error
motor_err = [i[1] for i in status]
# Position
position = [i[0][0] for i in status]
# iq
iq = [SMOOTHING * status[i][0][2] + (1 - SMOOTHING) * iq[i] for i in range(finger_count)]
# Velocity
prev_velocity = velocity
velocity = [SMOOTHING * status[i][0][1] + (1 - SMOOTHING) * velocity[i] for i in
range(finger_count)]
# Acceleration
acceleration = [
SMOOTHING * (velocity[i] - prev_velocity[i]) / delta_time + (1 - SMOOTHING) * acceleration[i]
for i in range(finger_count)]
# Get compensated iq
iq_comp = [abs(abs(iq[i] - acceleration[i] * ACC_COMP_FACTOR)
- (abs(position[i]) < SPRING_COMP_START) * 0.2
- (abs(position[i]) > SPRING_COMP_START) * (
0.18 + 0.06 * (abs(position[i]) - SPRING_COMP_START)))
for i in range(finger_count)]
# Approach motion
# Calculate approach_command
# RobotController PID generating position command so that finger tracks approach_speed
# Build approach commands
velocity_error = [goal_approach_speed[i] - velocity[i] for i in range(finger_count)]
velocity_error_int = [velocity_error[i] * delta_time + velocity_error_int[i] for i in range(finger_count)]
# Determine if contact and Switch to torque mode and maintain detect iq upon contact
for idx in range(finger_count):
if not self.robot.fingerlist[idx].contact:
if iq_comp[idx] > self.detect_current:
if detect_count[idx]:
detect_count[idx] -= 1
# Build command
approach_command[idx] = position[idx] + approach_p * velocity_error[idx] + approach_i * velocity_error_int[idx] - approach_d * acceleration[idx]
self.MC.pbm.set_goal_position((self.robot.finger_ids[idx], approach_command[idx]))
else:
self.robot.fingerlist[idx].contact = True
print('Finger contact:', self.robot.fingerlist[idx].name, position[idx])
self.contact_position[idx] = position[idx]
# Calculate iq to maintain
# Get sign and balance factor for the finger
iq_sign_balance = (self.robot.fingerlist[idx].mirrored - (not self.robot.fingerlist[idx].mirrored))*self.balance_factor[idx]
goal_iq[idx] = iq_sign_balance*(self.detect_current + (abs(position[idx]) > SPRING_COMP_START) * (0.18 + 0.06 * (abs(position[idx]) - SPRING_COMP_START)))
# approach_command[idx] = position[idx]
# Send goal_iq
print('Finger iq:', goal_iq[idx])
# Set into torque mode
self.MC.set_mode(self.robot.finger_ids[idx], 'torque')
self.MC.pbm.set_goal_iq((self.robot.finger_ids[idx], goal_iq[idx]))
contact_count += 1
else:
# Build command
approach_command[idx] = position[idx] + approach_p * velocity_error[idx] + approach_i * velocity_error_int[idx] - approach_d * acceleration[idx]
self.MC.pbm.set_goal_position((self.robot.finger_ids[idx], approach_command[idx]))
else:
# This finger has contacted
# Keep sending iq command
self.MC.pbm.set_goal_iq((self.robot.finger_ids[idx], goal_iq[idx]))
self.robot.contact = contact_count == finger_count
# # Clamp approach_command
# approach_command = [max(min(i, approach_command_max), -approach_command_max) for i in approach_command]
# Data logging
if self.logging:
delta_time_log.append(delta_time)
time_log.append(present_time - start_time)
velocity_log.append(velocity)
position_log.append(position)
iq_log.append(iq)
iq_comp_log.append(iq_comp)
acceleration_log.append(acceleration)
# Check for timeout
if present_time - start_time > TIMEOUT_GRAB:
print("Grab motion timeout")
self.MC.torque_enable_all(0)
error = 1
except KeyboardInterrupt:
print("User interrupted.")
running = False
error = 2
# Out of while loop -> error or contact
# Data processing -logging
if self.logging:
# Format all data so that it is in this formation:
# data_log_all = [[INDEX data], [INDEX_M data], [THUMB data]]
velocity_log_all = []
position_log_all = []
iq_log_all = []
iq_comp_log_all = []
acceleration_log_all = []
for i in range(3):
velocity_log_all.append([data[i] for data in velocity_log])
position_log_all.append([data[i] for data in position_log])
iq_log_all.append([data[i] for data in iq_log])
iq_comp_log_all.append([data[i] for data in iq_comp_log])
acceleration_log_all.append([data[i] for data in acceleration_log])
# Plot here
id = 0
plt.plot(time_log, iq_comp_log_all[0], 'r-', time_log, iq_comp_log_all[1], 'k-', time_log, iq_comp_log_all[2], 'b-')
# plt.plot(time_log, delta_time_log)
plt.grid(True)
plt.show()
if error:
self.MC.torque_enable_all(0)
print("Grab error. System disabled.")
else:
# # Debug option
# # Get current status for debug purpose.
# # Get mode for all
# modes = self.MC.pbm.get_mode(1, 2, 3)
# modes = [i[0] for i in modes]
# print('Modes:', modes)
# # Get goal_iq for all
# g_iq = self.MC.pbm.get_goal_iq(1, 2, 3)
# g_iq = [i[0] for i in g_iq]
# print('Goal_iq:', g_iq)
# # Get present_iq for all
# p_iq = self.MC.pbm.get_present_iq(1, 2, 3)
# p_iq = [i[0] for i in p_iq]
# print('Present_iq:', p_iq)
# Switch to final grip/hold upon object detection
# pdb.set_trace()
# usr = input("Press enter to proceed to grab_end...")
self.grab_end()
return error
def grab_end(self, plot=False):
error = 0
# Check mode:
if self.mode == 'H':
# Hold mode, change to big D with small P
# Enforced writing
# Calculate HOLD_D according to final_strength
hold_p = round(HOLD_P_FACTOR * self.final_strength, 2)
hold_d = round(HOLD_D_FACTOR * self.final_strength, 2)
if self.robot.palm.gesture == 'I':
# Pinch mode, use only index fingers
finger_count = 2
else:
# Use all three fingers
finger_count = 3
# Set D gain first
for i in range(finger_count):
self.MC.pbm.set_d_gain_force((self.robot.finger_ids[i], hold_d))
# Enforce writing
check = 0
while check < finger_count:
for i in range(finger_count):
if round(self.MC.pbm.get_d_gain_force(self.robot.finger_ids[i])[0][0], 2) != hold_d:
self.MC.pbm.set_d_gain_force((self.robot.finger_ids[i], hold_d))
else:
check += 1
# Then set P gain
for i in range(finger_count):
self.MC.pbm.set_p_gain_force((self.robot.finger_ids[i], hold_p))
# Enforce writing
check = 0
while check < finger_count:
for i in range(finger_count):
if round(self.MC.pbm.get_p_gain_force(self.robot.finger_ids[i])[0][0], 2) != hold_p:
self.MC.pbm.set_p_gain_force((self.robot.finger_ids[i], hold_p))
else:
check += 1
# Move goal_position forward for a bit more grabbing
# Calculate goal_position
goal_position = [
round(self.contact_position[i] +
(self.robot.fingerlist[i].mirrored - (not self.robot.fingerlist[i].mirrored)) * delta_position, 4)
for i in range(finger_count)]
# Send command
for i in range(finger_count):
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], goal_position[i]))
# Enforce writing
check = 0
while check < finger_count:
for i in range(finger_count):
if round(self.MC.pbm.get_goal_position(self.robot.finger_ids[i])[0][0], 4) != goal_position[i]:
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], goal_position[i]))
else:
check += 1
# Switch into Direct Force mode
for i in range(finger_count):
self.MC.set_mode(self.robot.finger_ids[i], 'force')
else:
# Grab mode, grab to final_strength
detect_count = [grip_confirm, grip_confirm, grip_confirm]
iq_comp_goal = self.final_strength
# Collect status
if self.robot.palm.gesture == 'I':
# Pinch mode, use only index fingers
status = self.MC.get_present_status_index()
finger_count = 2
else:
# Use all three fingers
status = self.MC.get_present_status_all()
finger_count = 3
# Get goal_iq
goal_iq = [
(self.robot.fingerlist[i].mirrored - (not self.robot.fingerlist[i].mirrored)) *
(iq_comp_goal + (abs(self.contact_position[i]) < SPRING_COMP_START) * 0.2 +
(abs(self.contact_position[i]) > SPRING_COMP_START) * (0.18 + 0.06 * (abs(self.contact_position[i]) - SPRING_COMP_START)))
for i in range(finger_count)]
# Clamp goal_iq with max_iq and balance force
goal_iq = [min(max(goal_iq[i], -self.max_iq), self.max_iq)*self.balance_factor[i] for i in range(finger_count)]
print("Grip goal_iq:", goal_iq)
iq = [0, 0, 0]
iq_error_int = [0, 0, 0]
goal_reached = False
goal_reached_count = 0
finger_goal_reached = [False, False, False]
start_time = time.time()
present_time = time.time()
first_cyc = True
# Logging initialize
time_log = []
iq_log = []
position_log = []
grip_command_log = []
iq_error_log = []
# Track goal_iq
while not (error or goal_reached):
try:
previous_time = present_time
# Collect status
if self.robot.palm.gesture == 'I':
status = self.MC.get_present_status_index()
else:
status = self.MC.get_present_status_all()
# Get time stamp
present_time = time.time()
delta_time = present_time - previous_time
# Process data
# Motor Error
motor_err = [i[1] for i in status]
# iq
iq = [SMOOTHING * status[i][0][2] + (1 - SMOOTHING) * iq[i] for i in range(finger_count)]
iq_error = [goal_iq[i] - iq[i] for i in range(finger_count)]
# Determine if goal_reached
for idx in range(finger_count):
if finger_goal_reached[idx]:
pass
else:
if abs(iq_error[idx]) < 0.1:
if detect_count[idx]:
detect_count[idx] -= 1
else:
finger_goal_reached[idx] = True
goal_reached_count += 1
goal_reached = goal_reached_count == finger_count
# Grip motion
# Calculate goal_position
# RobotController PID generating position command so that finger tracks goal_iq
iq_error_int = [iq_error[i] * delta_time + iq_error_int[i] for i in range(finger_count)]
# Build command, stop finger upon contact
grip_command = [self.contact_position[i] +
(grip_p * iq_error[i] + grip_i * iq_error_int[i])
for i in range(finger_count)]
if finger_count == 2:
# Pinch mode, only use INDEX fingers
self.MC.pbm.set_goal_position((BEAR_INDEX, grip_command[0]),
(BEAR_INDEX_M, grip_command[1]))
else:
# Use all fingers
self.MC.pbm.set_goal_position((BEAR_INDEX, grip_command[0]),
(BEAR_INDEX_M, grip_command[1]),
(BEAR_THUMB, grip_command[2]))
if first_cyc:
# Switch into Direct Force mode
for i in range(finger_count):
self.MC.set_mode(self.robot.finger_ids[i], 'force')
first_cyc = False
# Data logging
time_log.append(present_time-start_time)
iq_log.append(iq)
grip_command_log.append(grip_command)
iq_error_log.append(iq_error)
# Check for timeout
if present_time - start_time > TIMEOUT_GRIP:
print("GRIP motion timeout, final_strength can not be reached")
# self.MC.torque_enable_all(0)
error = 1
except KeyboardInterrupt:
print("User interrupted.")
running = False
error = 2
# Out of while loop, final_strength reached or error
if plot:
# Plot functions
iq_log_all = []
grip_command_log_all = []
iq_error_log_all = []
for i in range(finger_count):
iq_log_all.append([data[i] for data in iq_log])
iq_error_log_all.append([data[i] for data in iq_error_log])
grip_command_log_all.append([data[i] for data in grip_command_log])
# Plot here
id = 2
# plt.plot(time_log, iq_comp_log_all[0], 'r-', time_log, iq_comp_log_all[1], 'k-', time_log, iq_comp_log_all[2], 'b-')
plt.plot(time_log, iq_log_all[0], 'r-',
time_log, iq_log_all[1], 'b-',
time_log, iq_log_all[2], 'g-')
plt.grid(True)
plt.show()
# TODO: Check error
def release(self, release_mode, *hold_stiffness):
# Release motion of self.robot
# All fingers run in position mode
# Three release modes:
# - change-to-(H)old = change to hold mode
# - (L)et-go = release a little ,
# - (F)ul-release = fingers reset
# TODO: if original stiffness is too low, it might not trigger full release end sign, thus use separate
# release PID
# Check initialization
if not self.robot.initialized:
error = 3
print("Robot not initialized. Exit.")
return error
# Check input
if release_mode not in ['H', 'L', 'F']:
print("Invalid mode.") # TODO: Throw an exception
return False
if not self.get_robot_enable():
# If robot is not enabled, enable it and only perform Full-release
print("WARNING: Robot not enabled, enabling now.")
self.set_robot_enable(1)
if release_mode != 'F':
print("WARNING: DAnTE can only perform full release in current status.")
print("Switching to Full-release...")
release_mode = 'F'
elif not self.robot.contact:
if release_mode != 'F':
print("WARNING: DAnTE is currently not in contact with object thus can only perform full release.")
print("Switching to Full-release...")
release_mode = 'F'
print("Releasing...")
# Check mode:
if release_mode == 'H':
# Hold mode, change to big D with small P
# Do not release contact
# Enforced writing
if len(hold_stiffness) == 0:
# No hold_stiffness provided, go with default
hold_stiffness = default_hold_stiffness
# Calculate HOLD_D according to hold_stiffness
hold_p = HOLD_P_FACTOR * hold_stiffness
hold_d = HOLD_D_FACTOR * hold_stiffness
if self.robot.palm.gesture == 'I':
# Pinch mode, use only index fingers
finger_count = 2
else:
# Use all three fingers
finger_count = 3
# Set D gain first
for i in range(finger_count):
self.MC.pbm.set_d_gain_force((self.robot.finger_ids[i], hold_d))
# Enforce writing
check = 0
while check < finger_count:
for i in range(finger_count):
if round(self.MC.pbm.get_d_gain_force(self.robot.finger_ids[i])[0][0], 2) != hold_d:
self.MC.pbm.set_d_gain_force((self.robot.finger_ids[i], hold_d))
else:
check += 1
# Then set P gain
for i in range(finger_count):
self.MC.pbm.set_p_gain_force((self.robot.finger_ids[i], hold_p))
# Enforce writing
check = 0
while check < finger_count:
for i in range(finger_count):
if round(self.MC.pbm.get_p_gain_force(self.robot.finger_ids[i])[0][0], 2) != hold_p:
self.MC.pbm.set_p_gain_force((self.robot.finger_ids[i], hold_p))
else:
check += 1
# Move goal_position forward for a bit more grabbing
# Calculate goal_position
goal_position = [
round(self.contact_position[i] +
(self.robot.fingerlist[i].mirrored - (not self.robot.fingerlist[i].mirrored)) * delta_position, 4)
for i in range(finger_count)]
# Send command
for i in range(finger_count):
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], goal_position[i]))
# Enforce writing
check = 0
while check < finger_count:
for i in range(finger_count):
if round(self.MC.pbm.get_goal_position(self.robot.finger_ids[i])[0][0], 4) != goal_position[i]:
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], goal_position[i]))
else:
check += 1
# Switch into Direct Force mode
for i in range(finger_count):
self.MC.set_mode(self.robot.finger_ids[i], 'force')
else:
# Let-go or Full-release
# Uses existing mode and gains
# Reset contact
for f in self.robot.fingerlist:
f.contact = False
self.robot.contact = False
if self.robot.palm.gesture == 'I':
# Pinch mode, use only index fingers
finger_count = 2
else:
# Use all three fingers
finger_count = 3
# Calculate goal_position
if release_mode == 'L':
# Let-go, just release a little
sign = [(self.robot.fingerlist[i].mirrored - (not self.robot.fingerlist[i].mirrored)) for i in range(finger_count)]
goal_position = [self.contact_position[i] - sign[i] * let_go_margin for i in range(finger_count)]
else:
# Full-release
goal_position = [0, 0, 0]
# Send command
for i in range(finger_count):
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], goal_position[i]))
# Enforce writing
check = 0
while check < finger_count:
for i in range(finger_count):
if round(self.MC.pbm.get_goal_position(self.robot.finger_ids[i])[0][0], 4) != goal_position[i]:
self.MC.pbm.set_goal_position((self.robot.finger_ids[i], goal_position[i]))
else:
check += 1
# Make sure fingers stopped
check = 0
while check < finger_count:
for i in range(finger_count):
if abs(self.MC.pbm.get_present_position(self.robot.finger_ids[i])[0][0] - goal_position[i]) < 0.3:
# This finger has come close enough to release point
check += 1
print("Released.")
# Put into IDLE if Full-release
if release_mode == 'F':
self.idle()
time.sleep(0.5)
def update_angles(self):
error = 0 # 1 for timeout, 2 for user interruption, 3 for initialization, 9 for Invalid input
# Check initialization
if not self.robot.initialized:
error = 3
print("Robot not initialized. Exit.")
return error
# Update finger joint angles
data = self.MC.get_present_position_all()
present_pos = [i[0] for i in data] # [Index, Index_M, THUMB]
# Get ext_enc reading:
self.ext_enc.connect()
time.sleep(0.2)
ext_reading = self.ext_enc.get_angle()
self.ext_enc.release()
# Update all joint angles
for idx, finger in enumerate(self.robot.fingerlist):
finger.angles[0] = alpha_0[idx] + present_pos[idx] # Get alpha from present position
finger.angles[1] = ext_reading[idx] - finger.encoder_offset + math.pi/6 # Get beta from external encoders
# Get [gamma, delta] from present position
finger.angles[2:4] = FK.angles(finger, self.robot.palm.angle)
print(finger.name)
# print("alpha_0: %f" % alpha_0[idx])
bear_pos = present_pos[idx]*180/math.pi
print("present_pos: %f" % bear_pos)
# print("alpha: %f" % finger.angles[0])
angles_in_deg = [i*180/math.pi for i in finger.angles]
print(angles_in_deg)
print("Palm: " + str(self.robot.palm.angle))
def forward_kinematics(self, *finger):
# Specify the finger to be calculated, otherwise all fingers will be calculated
error = 0 # 1 for timeout, 2 for user interruption, 3 for initialization, 9 for Invalid input
# Check initialization
if not self.robot.initialized:
error = 3
print("Robot not initialized. Exit.")
return error
palm_angle = self.robot.palm.angle
if len(finger) == 0:
# update all finger kinematics
for f in self.robot.fingerlist:
FK.finger_fk(f, palm_angle)
else:
FK.finger_fk(finger, palm_angle)
def visualization(self):
error = 0 # 1 for timeout, 2 for user interruption, 3 for initialization, 9 for Invalid input
# Check initialization
if not self.robot.initialized:
error = 3
print("Robot not initialized. Exit.")
return error
FK.visual(self.robot)
if __name__ == '__main__':
rc = RobotController(robot=DAnTE)
rc.start_robot()
rc.initialization()
rc.grab('P', 'H', approach_speed=1.8, approach_stiffness=0.35, detect_current=0.3, max_iq=0.25, final_strength=2) |
/**
* Copyright 2018 <NAME> - https://www.stevejrong.top
* 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.stevejrong.airchina.oauth.shiro.realm;
import com.stevejrong.airchina.oauth.model.MenuModel;
import com.stevejrong.airchina.oauth.model.RoleModel;
import com.stevejrong.airchina.oauth.model.UserModel;
import com.stevejrong.airchina.oauth.service.MenuService;
import com.stevejrong.airchina.oauth.service.RoleService;
import com.stevejrong.airchina.oauth.service.UserService;
import com.stevejrong.airchina.oauth.shiro.util.ShiroHashUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* 数据库认证数据源
* 在调用用户授权接口给用户授权生成Token时会用到
*
* @author <NAME>
* @since 1.0 create date: 2018年2月26日 下午11:24:45
*/
public class DatabaseRealm extends AuthorizingRealm {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseRealm.class);
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private MenuService menuService;
public DatabaseRealm() {
super(ShiroHashUtil.getCredentialsMatcher());
setAuthenticationTokenClass(UsernamePasswordToken.class);
}
public void clearCachedAuthorizationInfo(String principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
clearCachedAuthorizationInfo(principals);
}
/**
* 授权方法
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String email = (String) getAvailablePrincipal(principals);
if (email == null) {
throw new NullPointerException("授权时的principal不能为空!");
}
UserModel user = userService.getByEmail(email);
// 根据用电子邮件地址查找此用户的角色和权限
List<RoleModel> totalRoles = roleService.listAllRolesByUserId(user.getUserId()); // 查找所有角色(目前仅支持单角色,获取到了1个以上的角色就取其中的一个)
List<MenuModel> totalMenuPermissions = menuService.listAllMenusByUserId(user.getUserId()); // 查找所有菜单权限
final Set<String> roleNames = new LinkedHashSet<>(totalRoles.size());
final Set<String> permissionNames = new LinkedHashSet<>(totalMenuPermissions.size());
roleNames.add(totalRoles.stream().findFirst().get().getRoleCode());
totalMenuPermissions.forEach(menu -> {
permissionNames.add(menu.getRequestUrl());
});
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRoles(roleNames);
info.addStringPermissions(permissionNames);
return info;
}
/**
* 认证方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
if (token instanceof UsernamePasswordToken) {
String email = ((UsernamePasswordToken) token).getUsername();
return doGetAuthenticationInfo(email);
// UserModel user = userService.getByEmail(email);
// String dbPassword = user.getPassword();
// String authPassword = ShiroMd5Util.encryptPasswordToHex(email, String.valueOf(((UsernamePasswordToken) token).getPassword()));
// if (!authPassword.equals(dbPassword)) {
// throw new IncorrectCredentialsException("密码错误"); // 密码错误
// }
}
throw new UnsupportedOperationException("Implement another method of getting user email.");
}
private AuthenticationInfo doGetAuthenticationInfo(String email) throws AuthenticationException {
UserModel user = userService.getByEmail(email);
//盐值
ByteSource credentialsSalt = ByteSource.Util.bytes(email);
//封装用户信息,构建AuthenticationInfo对象并返回
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(email, user.getPassword(), credentialsSalt, getName());
return authcInfo;
}
} |
There is little stopping Son Heung-min at the moment — except, possibly, the South Korean army.
Five goals in five games this season, a Champions League winner on Tuesday night, a double to down Middlesbrough three days before.
Without Harry Kane, out for several weeks with an ankle ligament injury, one questioned where Tottenham’s goals were going to come from. Turns out that is from a player who considered moving back to Germany in the summer, to where he had played all of his professional football before moving to north London a year ago.
Son Heung-min has scored five goals in just five games for Tottenham so far this season
The latest came as he scored the winner in Spurs' 1-0 Champions League win at CSKA Moscow
But he may have to miss two years of action for Spurs to serve national service in South Korea
And if Son can exhibit the kind of goal-scoring form which earned him the nickname ‘Sonaldo’ at former club Bayer Leverkusen — for his likeness to Cristiano Ronaldo, in case you were wondering — then they have no further to look.
Why is it, then, that as the years creep on for the 24-year-old and he transcends to the peak of his powers his valuation will depreciate by the day?
As it stands, by the age of 28 he must start 21 months of mandatory military service, missing almost two years at a time when Tottenham, if their trajectory continues under Mauricio Pochettino, could be challenging for Premier League titles and in Europe on a regular basis.
Son will be forced to swap a multi-million-pound contract for a maximum of roughly £130-per-month, if he makes it to the highest rank of Sergeant, and draft dodging is not tolerated. It has consumed famous actors, rappers, singers and most South Korean celebrities decide it is better to get it out of the way than avoid it. Failure to serve without exemption leads to imprisonment.
South Korean law says Son, now 24, must serve 21 months in the military before the age of 28
Son moved to Spurs in 2015 having previously been at Hamburg and Leverkusen in Germany
SON HEUNG-MIN'S CAREER 2010-13: Hamburg (73 games 20 goals) 2013-15: Leverkusen (78/26) 2015-: Tottenham (45/13)
Rapper MC Mong was accused of avoiding his military service by having teeth removed. He eventually received a six-month suspended sentence, a year’s probation and community service for deliberately delaying his enlistment. Pop singer Yoo Seung Jun became an American citizen to avoid his and was exiled from the country.
Yet in a weird, almost dystopian twist, South Korean footballers can play their way out of fighting for their country. This is The Hunger Games book four; everyone is up for consideration to fight, unless they are really good at sport.
Swansea midfielder Ki Sung-yueng missed the final game of last season due to serving four weeks of military duty. His term was significantly reduced for winning a bronze medal at London 2012, along with the rest of his team-mates. Park Ji-sung, formerly of Manchester United, and Lee Young-pyo, who also played for Spurs, were exempt after reaching the semi-final of the 2002 World Cup.
Ki Sung-yueng missed the final game of last season due to serving four weeks of military duty
Park Ji-sung and Lee Young-pyo were exempt for reaching the semis of the 2002 World Cup
Gold in the Asian Games will do it. Victory in the Asian Cup will, too, and Son came so close in 2014 when he reached the final and even scored a last-minute equaliser against hosts Australia, but they lost in extra time. In Rio 2016 they were knocked out in the quarter-finals and he has a chance in the Asian Games in 2018 and 2020 Tokyo Olympics, but time is running out and so are competitions.
Or he could turn to an alternative. Park Chu-young, who joined Arsenal in 2011 when he was 26, obtained a 10-year Monaco residency in 2012 to delay his conscription by a decade. He was part of Ki’s side who won an Olympic medal that year and won exemption anyway, but his reputation was still sullied back home.
Or he could be saved by a change in the political landscape. Politician Nam Kyung-pil says he will make the military voluntary if elected president.
If not, Son will be enlisted in the South Korean army at the peak of his Tottenham career. |
<gh_stars>0
'''
Utility functions for reporters
'''
def is_compatable_data_signiture(data_sig_1,data_sig_2):
'''
Test whether data with the signiture data_sig_2 provides the information
required for an operation requiring data_sig_1.
'''
return set(data_sig_1) <= set(data_sig_2)
|
Spatially resolved emitter saturation current by photoluminescence imaging Heavily doped regions (in particular emitters) in silicon wafer solar cells are a major source of recombination which limits the open-circuit voltage, the short-circuit current and hence the efficiency. These regions are typically characterized by the emitter saturation current density, which is commonly calculated from the plot of the inverse effective lifetime (corrected for Auger recombination) as a function of minority carrier concentration. In this paper we present a simple spatially resolved emitter saturation current density measurement method which is based on photoluminescence imaging. The spatially averaged values obtained by the proposed method were found to be in a good agreement with the ones obtained by the standard photoconductance-based method. The application of the method to a selective emitter solar cell structure is demonstrated. |
/**
* cs5520_set_dmamode - program DMA timings
* @ap: ATA port
* @adev: ATA device
*
* Program the DMA mode timings for the controller according to the pio
* clocking table. Note that this device sets the DMA timings to PIO
* mode values. This may seem bizarre but the 5520 architecture talks
* PIO mode to the disk and DMA mode to the controller so the underlying
* transfers are PIO timed.
*/
static void cs5520_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
static const int dma_xlate[3] = { XFER_PIO_0, XFER_PIO_3, XFER_PIO_4 };
cs5520_set_timings(ap, adev, dma_xlate[adev->dma_mode]);
cs5520_enable_dma(ap, adev);
} |
// send request to Twilio SMS API, return status code
int sendSms(String phoneTo, String msg){
WiFiClientSecure client;
client.setFingerprint(_TWILIO_FINGERPRINT);
if(!client.connect(_TWILIO_HOST, _TWILIO_PORT)){
syncPrintfClr("Connection to Twilio API failed\n");
return -1;
}
syncPrintfClr("Connected to\nTwilio API\n");
String reqBody = "To=" + urlEncode(phoneTo) +
"&From=" + urlEncode(String(_TWILIO_FROM)) +
"&Body=" + urlEncode(msg);
String http = "POST /2010-04-01/Accounts/" + String(_TWILIO_ACC) +
"/Messages.json HTTP/1.1\r\n" +
getAuthHeader(_TWILIO_ACC, _TWILIO_AUTH) + "\r\n" +
"Host: " + String(_TWILIO_HOST) + "\r\n" +
"Cache-control: no-cache\r\n" +
"User-Agent: ESP8266 Twilio Example\r\n" +
"Content-Type: " +
"application/x-www-form-urlencoded\r\n" +
"Content-Length: " + reqBody.length() +"\r\n" +
"Connection: close\r\n" +
"\r\n" + reqBody + "\r\n";
client.print(http);
syncPrintf("Request sent\n");
while(client.connected()){
String line = client.readStringUntil('\n');
if(line == "\r"){
syncPrintf("Headers received\n");
break;
}
}
while(client.available()){
char c = client.read();
Serial.print(c);
}
return client.status();
} |
Environmental Aspects of Implementation of Micro Hydro Power Plants A Short Review Abstract The economic importance of micro hydro power plants is obvious around the world and the development trend will continue well into the future. Unfortunately the effects on the local lotic systems habitats and biocoenosis are not studied, and in some cases or are known only to a small degree. A variety of taxa were identified in the study case areas as being significantly affected by the micro hydro power plants: macrophytes, macroinvertebrates and fish. |
<gh_stars>1-10
package katas.maraya;
public class TwoFightersOneWinner {
public static String declareWinner(Fighter fighter1, Fighter fighter2, String firstAttacker) {
//mientras la salud del pelear uno y 2 sea Mayor a 0 se le resta el ataque del peleador contrario
while (fighter1.health >0 && fighter2.health>0){
fighter2.health -= fighter1.damagePerAttack;
fighter1.health -= fighter2.damagePerAttack;
}
if (fighter1.health <=0 && fighter2.health <=0){
return firstAttacker;
}else if(fighter1.health <=0 ){
return fighter2.name;
}else{
return fighter1.name;
}
}
// creae clase estatica para obtener atributos del peleador (observacion separar clases y usar get a set para el codigo)
public static class Fighter {
public String name;
public int health, damagePerAttack;
public Fighter(String name, int health, int damagePerAttack) {
this.name = name;
this.health = health;
this.damagePerAttack = damagePerAttack;
}
}
}
|
string = input().strip()
flag, f1, f2 = False, False, False
ins = []
for _ in range(int(input())):
ins.append(input().strip())
for i in ins:
if i == string or i == string[::-1]:
print('YES')
exit()
if i[0] == string[1]:
f1 = True
if i[1] == string[0]:
f2 = True
if f1 and f2:
print('YES')
else:
print('NO') |
Digestibility and rate of passage by lambs of water-stressed alfalfa. Two lamb digestion experiments were conducted to evaluate the effect of alfalfa grown under varying levels of water deficiency (stress) on the rate of passage and digestibility of various fibrous components. Experiment 1 consisted of a randomized complete block design in which 12 Suffolk X Hampshire crossbred wethers averaging 40 kg were fed alfalfa hay grown at three (10, 15 or 20 cm water/ha) levels of water per harvest. Experiment 2 consisted of a switchback design in which four Hampshire wethers averaging 45 kg were fed alfalfa hay grown at two (5 or 20 cm/ha) levels of water per harvest. Forage yields ranged from 1,420 (10 cm/ha in Exp. 1) to 4,200 (20 cm/ha in Exp. 2) kg/ha. In both experiments, water stress reduced cell wall constituents (neutral detergent fiber), acid detergent fiber, lignin and cellulose content of the alfalfa hay. Organic matter digestibility was decreased when the percentage of leaves fell below 60% at the highest yield. Digestibility of N and the rate of NDF digestibility were not affected by water stress. The second experiment additionally included nutrient balance and rate of passage measurements. Greater (P less than.10) amounts of N and P were absorbed from water-stressed than nonstressed hay. Ruminal retention time of particulate markers tended (P less than.10) to increase with greater water stress. The results of this study are interpreted to indicate that while moderate water stress may have little effect on in vivo digestibility of alfalfa, severe stress may reduce digestibility of fibrous fractions and total organic matter. |
def _create_pod(
self, image, pod_name, job_name, port=80, cmd_string=None, volumes=None
):
if volumes is None:
volumes = []
security_context = None
if self.user_id and self.group_id:
security_context = client.V1SecurityContext(
run_as_group=self.group_id,
run_as_user=self.user_id,
run_as_non_root=self.run_as_non_root,
)
environment_vars = client.V1EnvVar(name="TEST", value="SOME DATA")
launch_args = ["-c", "{0}".format(cmd_string)]
volume_mounts = []
for volume in volumes:
volume_mounts.append(
client.V1VolumeMount(mount_path=volume[1], name=volume[0])
)
resources = client.V1ResourceRequirements(
limits={"cpu": str(self.max_cpu), "memory": self.max_mem},
requests={"cpu": str(self.init_cpu), "memory": self.init_mem},
)
container = client.V1Container(
name=pod_name,
image=image,
resources=resources,
ports=[client.V1ContainerPort(container_port=port)],
volume_mounts=volume_mounts,
command=["/bin/bash"],
args=launch_args,
env=[environment_vars],
security_context=security_context,
)
secret = None
if self.secret:
secret = client.V1LocalObjectReference(name=self.secret)
volume_defs = []
for volume in volumes:
volume_defs.append(
client.V1Volume(
name=volume[0],
persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
claim_name=volume[0]
),
)
)
metadata = client.V1ObjectMeta(name=pod_name, labels={"app": job_name})
spec = client.V1PodSpec(
containers=[container], image_pull_secrets=[secret], volumes=volume_defs
)
pod = client.V1Pod(spec=spec, metadata=metadata)
api_response = self.kube_client.create_namespaced_pod(
namespace=self.namespace, body=pod
)
logger.debug("Pod created. status='{0}'".format(str(api_response.status))) |
<filename>main.go
package main
import (
. "github.com/andysctu/go-tunnel/server"
"log"
"net"
"os"
)
// Start rps server
func main() {
ip := &net.IPAddr{}
if len(os.Args) < 2 {
log.Printf("No Host IP provided\n")
ip.IP = nil
} else {
var err error
ip, err = net.ResolveIPAddr("ip4", os.Args[1])
if err != nil {
log.Printf("Invalid Host IP: %s\n", os.Args[1])
return
}
}
server := GoRpsServer{}
serverTCPAddr, err := server.Start()
if err != nil {
log.Fatal(err)
}
log.Printf("Server running on: %s\n", serverTCPAddr.String())
select {}
}
|
Physical Examination and Ultrasound Evaluation of Patients with Superficial Venous Disease. Systematic and standardized evaluation of superficial venous disease, guided by knowledge of the various clinical presentations, venous anatomy, and pathophysiology of reflux, is essential for appropriate diagnosis and optimal treatment. Duplex ultrasonography is the standard for delineating venous anatomy, detecting anatomic variants, and identifying the origin of venous insufficiency. This article reviews tools and techniques essential for physical examination and ultrasound assessment of patients with superficial venous disease. |
package io.opensphere.csv.config.v2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Objects;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import io.opensphere.core.Toolbox;
import io.opensphere.core.server.HttpServer;
import io.opensphere.core.server.ResponseValues;
import io.opensphere.core.server.ServerProvider;
import io.opensphere.core.util.collections.New;
import io.opensphere.core.util.collections.StreamUtilities;
import io.opensphere.core.util.filesystem.FileUtilities;
import io.opensphere.core.util.io.StreamReader;
import io.opensphere.core.util.lang.HashCodeHelper;
import io.opensphere.core.util.lang.StringUtilities;
import io.opensphere.core.util.net.UrlUtilities;
import io.opensphere.csvcommon.config.v2.CSVParseParameters;
import io.opensphere.importer.config.ImportDataSource;
/**
* Data source configuration for a CSV.
*/
@XmlRootElement(name = "CSVDataSource")
@XmlAccessorType(XmlAccessType.NONE)
public class CSVDataSource extends ImportDataSource
{
/** Logger reference. */
private static final Logger LOGGER = Logger.getLogger(CSVDataSource.class);
/** The parse parameters. */
@XmlElement(name = "parseParameters", required = true)
private CSVParseParameters myParseParameters;
/**
* The local file location. When myFilePath is a local file, these should be
* the same, however they may differ when the file's real location is not
* local.
*/
@XmlTransient
private String myFileLocalPath;
/**
* JAXB Constructor.
*/
public CSVDataSource()
{
}
/**
* Constructor.
*
* @param sourceUri The data source URI
*/
public CSVDataSource(URI sourceUri)
{
super(sourceUri);
myParseParameters = new CSVParseParameters();
}
/**
* Gets the parseParameters.
*
* @return the parseParameters
*/
public CSVParseParameters getParseParameters()
{
return myParseParameters;
}
/**
* Sets the parseParameters.
*
* @param parseParameters the parseParameters
*/
public void setParseParameters(CSVParseParameters parseParameters)
{
myParseParameters = parseParameters;
}
/**
* Common paradigm: assign the local variable and also return its value.
* @param flp new value of myFileLocalPath
* @return see above
*/
private String setFlp(String flp)
{
myFileLocalPath = flp;
return myFileLocalPath;
}
/**
* Get the path to the file on the local file system, creating it if
* necessary. Creation can happen when the file is in a remote location such
* as over the network.
*
* @param toolbox The system toolbox. This is used to for connecting to a
* url to download the file if necessary. When the file is known
* to have already been made available locally, this may be null.
* @return the fileLocalPath
*/
public String getFileLocalPath(Toolbox toolbox)
{
if (StringUtils.isNotEmpty(myFileLocalPath))
{
return myFileLocalPath;
}
String uriStr = getSourceUriString();
if (StringUtils.isEmpty(uriStr))
{
return myFileLocalPath;
}
URI srcUri = getSourceUri();
URL srcUrl;
try
{
srcUrl = srcUri.toURL();
}
catch (MalformedURLException eek)
{
// If this isn't a URL then it is a regular file path.
return setFlp(srcUri.getSchemeSpecificPart());
}
// If this URL is actual a local file, process it like a normal local file.
if (UrlUtilities.isFile(srcUrl))
{
return setFlp(srcUri.getSchemeSpecificPart());
}
StringBuilder builder = new StringBuilder(FileUtilities.getDirectory(null, uriStr.hashCode()));
builder.append(File.separator).append("generated.csv");
myFileLocalPath = builder.toString();
File localFile = new File(myFileLocalPath);
// Only write the file if it doesn't exist.
if (localFile.exists() || toolbox == null)
{
return myFileLocalPath;
}
ResponseValues response = new ResponseValues();
ServerProvider<HttpServer> provider = toolbox.getServerProviderRegistry().getProvider(HttpServer.class);
try (FileOutputStream outStream = new FileOutputStream(localFile);
InputStream inputStream = provider.getServer(srcUrl).sendGet(srcUrl, response))
{
if (response.getResponseCode() == HttpURLConnection.HTTP_OK)
{
new StreamReader(inputStream).readStreamToOutputStream(outStream);
}
}
catch (IOException | URISyntaxException e)
{
LOGGER.error("Write temp file for remote CSV." + e, e);
}
return myFileLocalPath;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = super.hashCode();
result = prime * result + HashCodeHelper.getHashCode(myParseParameters);
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (!super.equals(obj) || getClass() != obj.getClass())
{
return false;
}
CSVDataSource other = (CSVDataSource)obj;
return Objects.equals(myParseParameters, other.myParseParameters);
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder(256);
builder.append("CSVDataSource [myParseParameters=");
builder.append(myParseParameters);
builder.append(", super=");
builder.append(super.toString());
builder.append(']');
return builder.toString();
}
@Override
public CSVDataSource clone()
{
CSVDataSource result = (CSVDataSource)super.clone();
result.myParseParameters = myParseParameters.clone();
return result;
}
/**
* Generate type key.
*
* @return the string
*/
@Override
public String generateTypeKey()
{
return StringUtilities.concat("CSV::", getName(), "::", toString(getSourceUri()));
}
/**
* Convenience method for getting the list of column names to ignore.
*
* @return the column names to ignore
*/
public Set<String> getColumnFilter()
{
return New.set(StreamUtilities.map(myParseParameters.getColumnsToIgnore(),
index -> myParseParameters.getColumnNames().get(index.intValue())));
}
}
|
<gh_stars>0
package com.simplepathstudios.snowgloo.fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.simplepathstudios.snowgloo.R;
import com.simplepathstudios.snowgloo.adapter.AlbumAdapter;
import com.simplepathstudios.snowgloo.adapter.ArtistAdapter;
import com.simplepathstudios.snowgloo.adapter.SongAdapter;
import com.simplepathstudios.snowgloo.api.model.SearchResults;
import com.simplepathstudios.snowgloo.viewmodel.ObservableMusicQueue;
import com.simplepathstudios.snowgloo.viewmodel.SearchResultsViewModel;
import java.util.Timer;
import java.util.TimerTask;
public class SearchFragment extends Fragment {
private static final String TAG = "SearchFragment";
private SearchResultsViewModel searchResultsViewModel;
private ObservableMusicQueue observableMusicQueue;
private EditText searchQuery;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.search_fragment, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
searchQuery = view.findViewById(R.id.search_query);
searchQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_DONE || (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)){
String query = searchQuery.getText().toString();
searchResultsViewModel.load(query);
}
return false;
}
});
searchQuery.addTextChangedListener(new TextWatcher() {
private Timer timer=new Timer();
private final long DELAY = 1000; // milliseconds
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
timer.cancel();
timer = new Timer();
timer.schedule(
new TimerTask() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
searchResultsViewModel.load(s.toString());
}
});
}
},
DELAY
);
}
@Override
public void afterTextChanged(Editable s) {}
});
observableMusicQueue = ObservableMusicQueue.getInstance();
searchResultsViewModel = new ViewModelProvider(getActivity()).get(SearchResultsViewModel.class);
searchResultsViewModel.Data.observe(getViewLifecycleOwner(), new Observer<SearchResults>() {
@Override
public void onChanged(SearchResults searchResults) {
LinearLayout container = getView().findViewById(R.id.lists_container);
container.removeAllViews();
if(searchResults.Artists.size() > 0){
View listView = getLayoutInflater().inflate(R.layout.search_result_list,container,false);
TextView resultKindText = listView.findViewById(R.id.result_kind);
resultKindText.setText("Artists (" + searchResults.Artists.size() +")");
RecyclerView listElement = listView.findViewById(R.id.result_list);
ArtistAdapter adapter = new ArtistAdapter();
listElement.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
listElement.setLayoutManager(layoutManager);
adapter.setData(searchResults.Artists);
adapter.notifyDataSetChanged();
container.addView(listView);
}
if(searchResults.Albums.size() > 0){
View listView = getLayoutInflater().inflate(R.layout.search_result_list,container,false);
TextView resultKindText = listView.findViewById(R.id.result_kind);
resultKindText.setText("Albums (" + searchResults.Albums.size() +")");
RecyclerView listElement = listView.findViewById(R.id.result_list);
AlbumAdapter adapter = new AlbumAdapter();
listElement.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
listElement.setLayoutManager(layoutManager);
adapter.setData(searchResults.Albums);
adapter.notifyDataSetChanged();
container.addView(listView);
}
if(searchResults.Songs.size() > 0){
View listView = getLayoutInflater().inflate(R.layout.search_result_list,container,false);
TextView resultKindText = listView.findViewById(R.id.result_kind);
resultKindText.setText("Songs (" + searchResults.Songs.size() +")");
RecyclerView listElement = listView.findViewById(R.id.result_list);
SongAdapter adapter = new SongAdapter();
listElement.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
listElement.setLayoutManager(layoutManager);
adapter.setData(searchResults.Songs);
adapter.notifyDataSetChanged();
container.addView(listView);
}
}
});
}
}
|
/**
*
* Description:<br>
* Test the <code>UserWebservice</code>
*
* <P>
* Initial Date: 15 apr. 2010 <br>
* @author srosse, [email protected]
*/
public class UserMgmtTest extends OlatRestTestCase {
private static final Logger log = Tracing.createLoggerFor(UserMgmtTest.class);
private static IdentityWithLogin id1;
private static IdentityWithLogin id2;
private static IdentityWithLogin id3;
private static IdentityWithLogin owner1;
private static BusinessGroup g1, g2, g3, g4;
private static String g1externalId, g3ExternalId;
private static ICourse demoCourse;
private static FOCourseNode demoForumNode;
private static BCCourseNode demoBCCourseNode;
private static boolean setuped = false;
@Autowired
private DB dbInstance;
@Autowired
private ForumManager forumManager;
@Autowired
private HomePageConfigManager homePageConfigManager;
@Autowired
private BusinessGroupRelationDAO businessGroupRelationDao;
@Autowired
private BusinessGroupService businessGroupService;
@Autowired
private BaseSecurity securityManager;
@Autowired
private BaseSecurityModule securityModule;
@Autowired
private RepositoryService repositoryService;
@Autowired
private OrganisationService organisationService;
@Autowired
private UserManager userManager;
@Autowired
private DisplayPortraitManager portraitManager;
@Before
public void setUp() throws Exception {
if(setuped) return;
//create identities
owner1 = JunitTestHelper.createAndPersistRndUser("user-rest-zero");
assertNotNull(owner1);
id1 = JunitTestHelper.createAndPersistRndUser("user-rest-one");
id2 = JunitTestHelper.createAndPersistRndUser("user-rest-two");
dbInstance.intermediateCommit();
id2.getUser().setProperty("telMobile", "39847592");
id2.getUser().setProperty("gender", "female");
id2.getUser().setProperty("birthDay", "20091212");
dbInstance.updateObject(id2.getUser());
dbInstance.intermediateCommit();
id3 = JunitTestHelper.createAndPersistRndUser("user-rest-three");
VFSContainer id3HomeFolder = VFSManager.olatRootContainer(FolderConfig.getUserHome(id3.getIdentity()), null);
VFSContainer id3PublicFolder = (VFSContainer)id3HomeFolder.resolve("public");
if(id3PublicFolder == null) {
id3PublicFolder = id3HomeFolder.createChildContainer("public");
}
VFSItem portrait = id3PublicFolder.resolve("portrait.jpg");
if(portrait == null) {
URL portraitUrl = CoursesElementsTest.class.getResource("portrait.jpg");
File ioPortrait = new File(portraitUrl.toURI());
FileUtils.copyFileToDirectory(ioPortrait, ((LocalImpl)id3PublicFolder).getBasefile(), false);
}
OLATResourceManager rm = OLATResourceManager.getInstance();
// create course and persist as OLATResourceImpl
OLATResourceable resourceable = OresHelper.createOLATResourceableInstance("junitcourse",System.currentTimeMillis());
OLATResource course = rm.createOLATResourceInstance(resourceable);
dbInstance.saveObject(course);
dbInstance.intermediateCommit();
//create learn group
// 1) context one: learning groups
RepositoryEntry c1 = JunitTestHelper.createAndPersistRepositoryEntry();
// create groups without waiting list
g1externalId = UUID.randomUUID().toString();
g1 = businessGroupService.createBusinessGroup(null, "user-rest-g1", null, g1externalId, "all", 0, 10, false, false, c1);
g2 = businessGroupService.createBusinessGroup(null, "user-rest-g2", null, 0, 10, false, false, c1);
// members g1
businessGroupRelationDao.addRole(id1.getIdentity(), g1, GroupRoles.coach.name());
businessGroupRelationDao.addRole(id2.getIdentity(), g1, GroupRoles.participant.name());
// members g2
businessGroupRelationDao.addRole(id2.getIdentity(), g2, GroupRoles.coach.name());
businessGroupRelationDao.addRole(id1.getIdentity(), g2, GroupRoles.participant.name());
// 2) context two: right groups
RepositoryEntry c2 = JunitTestHelper.createAndPersistRepositoryEntry();
// groups
g3ExternalId = UUID.randomUUID().toString();
g3 = businessGroupService.createBusinessGroup(null, "user-rest-g3", null, g3ExternalId, "all", -1, -1, false, false, c2);
g4 = businessGroupService.createBusinessGroup(null, "user-rest-g4", null, -1, -1, false, false, c2);
// members
businessGroupRelationDao.addRole(id1.getIdentity(), g3, GroupRoles.participant.name());
businessGroupRelationDao.addRole(id2.getIdentity(), g4, GroupRoles.participant.name());
dbInstance.closeSession();
//add some collaboration tools
CollaborationTools g1CTSMngr = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(g1);
g1CTSMngr.setToolEnabled(CollaborationTools.TOOL_FORUM, true);
Forum g1Forum = g1CTSMngr.getForum();//create the forum
Message m1 = forumManager.createMessage(g1Forum, id1.getIdentity(), false);
m1.setTitle("Thread-1");
m1.setBody("Body of Thread-1");
forumManager.addTopMessage(m1);
dbInstance.commitAndCloseSession();
//add some folder tool
CollaborationTools g2CTSMngr = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(g2);
g2CTSMngr.setToolEnabled(CollaborationTools.TOOL_FOLDER, true);
LocalFolderImpl g2Folder = VFSManager.olatRootContainer(g2CTSMngr.getFolderRelPath(), null);
g2Folder.getBasefile().mkdirs();
VFSItem groupPortrait = g2Folder.resolve("portrait.jpg");
if(groupPortrait == null) {
URL portraitUrl = UserMgmtTest.class.getResource("portrait.jpg");
File ioPortrait = new File(portraitUrl.toURI());
FileUtils.copyFileToDirectory(ioPortrait, g2Folder.getBasefile(), false);
}
dbInstance.commitAndCloseSession();
//prepare some courses
Identity author = JunitTestHelper.createAndPersistIdentityAsUser("auth-" + UUID.randomUUID().toString());
RepositoryEntry entry = JunitTestHelper.deployDemoCourse(author);
if (!repositoryService.hasRole(id1.getIdentity(), entry, GroupRoles.participant.name())){
repositoryService.addRole(id1.getIdentity(), entry, GroupRoles.participant.name());
}
demoCourse = CourseFactory.loadCourse(entry);
TreeVisitor visitor = new TreeVisitor(new Visitor() {
@Override
public void visit(INode node) {
if(node instanceof FOCourseNode) {
if(demoForumNode == null) {
demoForumNode = (FOCourseNode)node;
Forum courseForum = demoForumNode.loadOrCreateForum(demoCourse.getCourseEnvironment());
Message message1 = forumManager.createMessage(courseForum, id1.getIdentity(), false);
message1.setTitle("Thread-1");
message1.setBody("Body of Thread-1");
forumManager.addTopMessage(message1);
}
} else if (node instanceof BCCourseNode) {
if(demoBCCourseNode == null) {
demoBCCourseNode = (BCCourseNode)node;
VFSContainer container = BCCourseNode.getNodeFolderContainer(demoBCCourseNode, demoCourse.getCourseEnvironment());
VFSItem example = container.resolve("singlepage.html");
if(example == null) {
try(InputStream htmlUrl = UserMgmtTest.class.getResourceAsStream("singlepage.html")) {
VFSLeaf htmlLeaf = container.createChildLeaf("singlepage.html");
IOUtils.copy(htmlUrl, htmlLeaf.getOutputStream(false));
} catch (IOException e) {
log.error("", e);
}
}
}
}
}
}, demoCourse.getRunStructure().getRootNode(), false);
visitor.visitAll();
dbInstance.commitAndCloseSession();
setuped = true;
}
@Test
public void testGetUsers() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
assertNotNull(vos);
assertFalse(vos.isEmpty());
int voSize = vos.size();
vos = null;
List<Identity> identities = securityManager
.getIdentitiesByPowerSearch(null, null, true, null, null, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT);
assertEquals(voSize, identities.size());
conn.shutdown();
}
@Test
public void testFindUsersByLogin() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("login","administrator")
.queryParam("authProvider","OLAT").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
String[] authProviders = new String[]{"OLAT"};
List<Identity> identities = securityManager
.getIdentitiesByPowerSearch("administrator", null, true, null, authProviders, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT);
Assert.assertNotNull(vos);
Assert.assertFalse(vos.isEmpty());
Assert.assertEquals(vos.size(), identities.size());
conn.shutdown();
}
@Test
public void testFindUsersByLogin_notFuzzy() throws IOException, URISyntaxException {
//there is user-rest-...
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("user-rest");
Assert.assertNotNull(id);
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("login", id.getLogin()).build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
Assert.assertNotNull(vos);
Assert.assertEquals(1, vos.size());
Assert.assertEquals(id.getIdentity().getKey(), vos.get(0).getKey());
Assert.assertNull(vos.get(0).getLogin());
conn.shutdown();
}
@Test
public void testFindUsersByLogin_manualIdentityName() throws IOException, URISyntaxException {
String currentIdentityNameSetting = securityModule.getIdentityName();
securityModule.setIdentityName("manual");
//there is user-rest-...
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("u-rest-manual");
Assert.assertNotNull(id);
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("login", id.getLogin()).build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
Assert.assertNotNull(vos);
Assert.assertEquals(1, vos.size());
Assert.assertEquals(id.getIdentity().getKey(), vos.get(0).getKey());
Assert.assertEquals(id.getIdentity().getName(), vos.get(0).getLogin());
conn.shutdown();
securityModule.setIdentityName(currentIdentityNameSetting);
}
@Test
public void testFindUsersByExternalId() throws IOException, URISyntaxException {
//there is user-rest-...
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("user-external-id");
Assert.assertNotNull(id);
String externalId = UUID.randomUUID().toString();
Identity identity = securityManager.setExternalId(id.getIdentity(), externalId);
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("externalId", externalId)
.queryParam("statusVisibleLimit", "all")
.build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
Assert.assertNotNull(vos);
Assert.assertEquals(1, vos.size());
Assert.assertEquals(identity.getKey(), vos.get(0).getKey());
Assert.assertNull(vos.get(0).getLogin());
conn.shutdown();
}
@Test
public void testFindUsersByAuthusername() throws IOException, URISyntaxException {
//there is user-rest-...
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("user-auth-name");
Assert.assertNotNull(id);
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("authProvider", "OLAT")
.queryParam("authUsername", id.getLogin())
.queryParam("statusVisibleLimit", "all")
.build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
Assert.assertNotNull(vos);
Assert.assertEquals(1, vos.size());
Assert.assertEquals(id.getKey(), vos.get(0).getKey());
Assert.assertNull(vos.get(0).getLogin());
conn.shutdown();
}
@Test
public void testFindUsersByAuthusernameShib() throws IOException, URISyntaxException {
//there is user-rest-...
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("user-auth-name");
Assert.assertNotNull(id);
String shibIdent = UUID.randomUUID().toString();
securityManager.createAndPersistAuthentication(id.getIdentity(), "Shib", BaseSecurity.DEFAULT_ISSUER, shibIdent, null, null);
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("authProvider", "Shib")
.queryParam("authUsername", shibIdent)
.queryParam("statusVisibleLimit", "all")
.build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
Assert.assertNotNull(vos);
Assert.assertEquals(1, vos.size());
Assert.assertEquals(id.getKey(), vos.get(0).getKey());
Assert.assertNull(vos.get(0).getLogin());
// false check
URI negativeRequest = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("authProvider", "OLAT")
.queryParam("authUsername", shibIdent)
.queryParam("statusVisibleLimit", "all")
.build();
HttpGet negativeMethod = conn.createGet(negativeRequest, MediaType.APPLICATION_JSON, true);
HttpResponse negativeResponse = conn.execute(negativeMethod);
Assert.assertEquals(200, negativeResponse.getStatusLine().getStatusCode());
List<UserVO> negativeVos = parseUserArray(negativeResponse.getEntity());
Assert.assertNotNull(negativeVos);
Assert.assertTrue(negativeVos.isEmpty());
conn.shutdown();
}
@Test
public void testFindUsersByExternalId_negatif() throws IOException, URISyntaxException {
//there is user-rest-...
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("user-external-id-2");
Assert.assertNotNull(id);
String externalId = UUID.randomUUID().toString();
Identity identity = securityManager.setExternalId(id.getIdentity(), externalId);
dbInstance.commitAndCloseSession();
Assert.assertNotNull(identity);
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("externalId", "a-non-existing-external-key")
.queryParam("statusVisibleLimit", "all")
.build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
Assert.assertNotNull(vos);
Assert.assertTrue(vos.isEmpty());
conn.shutdown();
}
@Test
public void testFindUsersByProperty() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("telMobile","39847592")
.queryParam("gender","Female")
.queryParam("birthDay", "12/12/2009").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
assertNotNull(vos);
assertFalse(vos.isEmpty());
conn.shutdown();
}
@Test
public void testFindAdminByAuth() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users")
.queryParam("authUsername","administrator")
.queryParam("authProvider","OLAT").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<UserVO> vos = parseUserArray(response.getEntity());
assertNotNull(vos);
assertFalse(vos.isEmpty());
assertEquals(1, vos.size());
Identity admin = securityManager.findIdentityByLogin("administrator");
assertEquals(admin.getKey(), vos.get(0).getKey());
conn.shutdown();
}
@Test
public void testGetMe() throws IOException, URISyntaxException {
IdentityWithLogin meLogin = JunitTestHelper.createAndPersistRndUser("rest-users");
Identity me = meLogin.getIdentity();
me.getUser().setProperty("telMobile", "39847592");
me.getUser().setProperty("telOffice", "39847592");
me.getUser().setProperty("telPrivate", "39847592");
me.getUser().setProperty("gender", "female");
me.getUser().setProperty("birthDay", "20040405");
dbInstance.updateObject(me.getUser());
dbInstance.commit();
HomePageConfig hpc = homePageConfigManager.loadConfigFor(me);
hpc.setEnabled("telOffice", true);
hpc.setEnabled("telMobile", true);
hpc.setEnabled("birthDay", true);
homePageConfigManager.saveConfigTo(me, hpc);
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login(meLogin.getLogin(), meLogin.getPassword()));
URI request = UriBuilder.fromUri(getContextURI()).path("/users/me").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
UserVO vo = conn.parse(response, UserVO.class);
assertNotNull(vo);
assertEquals(vo.getKey(), me.getKey());
//are the properties there?
assertFalse(vo.getProperties().isEmpty());
conn.shutdown();
}
@Test
public void testGetUser() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey()).build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
UserVO vo = conn.parse(response, UserVO.class);
assertNotNull(vo);
assertEquals(vo.getKey(), id1.getKey());
//are the properties there?
assertFalse(vo.getProperties().isEmpty());
conn.shutdown();
}
@Test
public void testGetUserNotAdmin() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id2.getKey()).build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
UserVO vo = conn.parse(response, UserVO.class);
assertNotNull(vo);
assertEquals(vo.getKey(), id2.getKey());
//no properties for security reason
assertTrue(vo.getProperties().isEmpty());
conn.shutdown();
}
@Test
public void testGetManagedUser() throws IOException, URISyntaxException {
String externalId = UUID.randomUUID().toString();
Identity managedId = JunitTestHelper.createAndPersistIdentityAsRndUser("managed-1");
dbInstance.commitAndCloseSession();
securityManager.setExternalId(managedId, externalId);
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("users").path("managed").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<ManagedUserVO> managedUsers = parseManagedUserArray(response.getEntity());
boolean found = false;
for(ManagedUserVO managedUser:managedUsers) {
if(managedUser.getKey().equals(managedId.getKey())) {
found = true;
Assert.assertEquals(externalId, managedUser.getExternalId());
}
Assert.assertNotNull(managedUser.getExternalId());
}
Assert.assertTrue(found);
conn.shutdown();
}
@Test
public void testGetManagedUser_onlyUserManagers() throws IOException, URISyntaxException {
String externalId = UUID.randomUUID().toString();
Identity managedId = JunitTestHelper.createAndPersistIdentityAsRndUser("managed-1");
dbInstance.commitAndCloseSession();
securityManager.setExternalId(managedId, externalId);
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI request = UriBuilder.fromUri(getContextURI()).path("users").path("managed").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(401, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
conn.shutdown();
}
/**
* Only print out the raw body of the response
* @throws IOException
*/
@Test
public void testGetRawJsonUser() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey()).build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
String bodyJson = EntityUtils.toString(response.getEntity());
log.info("User JSON: {}", bodyJson);
conn.shutdown();
}
/**
* Only print out the raw body of the response
* @throws IOException
*/
@Test
public void testGetRawXmlUser() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey()).build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_XML, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
String bodyXml = EntityUtils.toString(response.getEntity());
log.info("User XML: {}", bodyXml);
conn.shutdown();
}
@Test
public void testCreateUser() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
UserVO vo = new UserVO();
String username = UUID.randomUUID().toString();
vo.setLogin(username);
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail(username + "@frentix.com");
vo.putProperty("telOffice", "39847592");
vo.putProperty("telPrivate", "39847592");
vo.putProperty("telMobile", "39847592");
vo.putProperty("gender", "Female");//male or female
vo.putProperty("birthDay", "12/12/2009");
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);
UserVO savedVo = conn.parse(response, UserVO.class);
Identity savedIdent = securityManager.loadIdentityByKey(savedVo.getKey());
assertNotNull(savedVo);
assertNotNull(savedIdent);
assertEquals(savedVo.getKey(), savedIdent.getKey());
assertEquals("Female", savedIdent.getUser().getProperty("gender", Locale.ENGLISH));
assertEquals("39847592", savedIdent.getUser().getProperty("telPrivate", Locale.ENGLISH));
assertEquals("12/12/2009", savedIdent.getUser().getProperty("birthDay", Locale.ENGLISH));
conn.shutdown();
}
@Test
public void testCreateUser_emptyLogin() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
UserVO vo = new UserVO();
vo.setLogin("");
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail(UUID.randomUUID() + "@frentix.com");
vo.putProperty("telOffice", "39847592");
vo.putProperty("telPrivate", "39847592");
vo.putProperty("telMobile", "39847592");
vo.putProperty("gender", "Female");//male or female
vo.putProperty("birthDay", "12/12/2009");
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
EntityUtils.consume(response.getEntity());
Assert.assertEquals(406, statusCode);
}
@Test
public void testCreateUser_special() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
UserVO vo = new UserVO();
vo.setLogin("tes @-()_" + CodeHelper.getForeverUniqueID());
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail(UUID.randomUUID() + "@frentix.com");
vo.putProperty("telOffice", "39847592");
vo.putProperty("telPrivate", "39847592");
vo.putProperty("telMobile", "39847592");
vo.putProperty("gender", "Female");//male or female
vo.putProperty("birthDay", "12/12/2009");
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
EntityUtils.consume(response.getEntity());
Assert.assertEquals(200, statusCode);
}
/**
* Test machine format for gender and date
*/
@Test
public void testCreateUser2() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
UserVO vo = new UserVO();
vo.setLogin(UUID.randomUUID().toString());
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail(UUID.randomUUID() + "@frentix.com");
vo.putProperty("telOffice", "39847592");
vo.putProperty("telPrivate", "39847592");
vo.putProperty("telMobile", "39847592");
vo.putProperty("gender", "female");//male or female
vo.putProperty("birthDay", "20091212");
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);
UserVO savedVo = conn.parse(response, UserVO.class);
Identity savedIdent = securityManager.loadIdentityByKey(savedVo.getKey());
assertNotNull(savedVo);
assertNotNull(savedIdent);
assertEquals(savedVo.getKey(), savedIdent.getKey());
assertEquals("Female", savedIdent.getUser().getProperty("gender", Locale.ENGLISH));
assertEquals("39847592", savedIdent.getUser().getProperty("telPrivate", Locale.ENGLISH));
assertEquals("12/12/2009", savedIdent.getUser().getProperty("birthDay", Locale.ENGLISH));
conn.shutdown();
}
/**
* Test the trim of email
*/
@Test
public void testCreateUser_emailWithTrailingSpace() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
UserVO vo = new UserVO();
String username = UUID.randomUUID().toString();
vo.setLogin(username);
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail(username + "@frentix.com ");
vo.putProperty("gender", "male");//male or female
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);
UserVO savedVo = conn.parse(response, UserVO.class);
Identity savedIdent = securityManager.loadIdentityByKey(savedVo.getKey());
assertNotNull(savedVo);
assertNotNull(savedIdent);
assertEquals(savedVo.getKey(), savedIdent.getKey());
assertEquals(username + "@frentix.com", savedIdent.getUser().getProperty(UserConstants.EMAIL, null));
conn.shutdown();
}
/**
* Test if we can create two users with the same email addresses.
*/
@Test
public void testCreateUser_same_email() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
String email = UUID.randomUUID() + "@frentix.com";
UserVO vo = new UserVO();
String username = UUID.randomUUID().toString();
vo.setLogin(username);
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail(email);
vo.putProperty("gender", "male");//male or female
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);
UserVO savedVo = conn.parse(response, UserVO.class);
Identity savedIdent = securityManager.loadIdentityByKey(savedVo.getKey());
assertNotNull(savedVo);
assertNotNull(savedIdent);
assertEquals(savedVo.getKey(), savedIdent.getKey());
//second
UserVO vo2 = new UserVO();
vo2.setLogin(UUID.randomUUID().toString());
vo2.setFirstName("Eva");
vo2.setLastName("Smith");
vo2.setEmail(email);
vo2.putProperty("gender", "female");
URI request2 = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method2 = conn.createPut(request2, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method2, vo2);
method2.addHeader("Accept-Language", "en");
HttpResponse response2 = conn.execute(method2);
int statusCode2 = response2.getStatusLine().getStatusCode();
Assert.assertEquals(406, statusCode2);
String errorMessage = EntityUtils.toString(response2.getEntity());
Assert.assertNotNull(errorMessage);
conn.shutdown();
}
@Test
public void testCreateUserWithValidationError() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
String login = "rest-809-" + UUID.randomUUID();
UserVO vo = new UserVO();
vo.setLogin(login);
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail("");
vo.putProperty("gender", "lu");
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
HttpResponse response = conn.execute(method);
assertEquals(406, response.getStatusLine().getStatusCode());
List<ErrorVO> errors = parseErrorArray(response.getEntity());
assertNotNull(errors);
assertFalse(errors.isEmpty());
assertTrue(errors.size() >= 2);
assertNotNull(errors.get(0).getCode());
assertNotNull(errors.get(0).getTranslation());
assertNotNull(errors.get(1).getCode());
assertNotNull(errors.get(1).getTranslation());
Identity savedIdent = securityManager.findIdentityByName(login);
assertNull(savedIdent);
conn.shutdown();
}
/**
* Test if we can create two users with the same email addresses.
*/
@Test
public void testCreateAndUpdateUser() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
String username = UUID.randomUUID().toString();
String email = UUID.randomUUID() + "@frentix.com";
UserVO vo = new UserVO();
vo.setLogin(username);
vo.setFirstName("Terence");
vo.setLastName("Smith");
vo.setEmail(email);
vo.putProperty("gender", "male");//male or female
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);
UserVO savedVo = conn.parse(response, UserVO.class);
Identity savedIdent = securityManager.loadIdentityByKey(savedVo.getKey());
Assert.assertNotNull(savedVo);
Assert.assertNotNull(savedIdent);
Assert.assertEquals(savedVo.getKey(), savedIdent.getKey());
Assert.assertEquals("Terence", savedIdent.getUser().getFirstName());
//second
UserVO updateVo = new UserVO();
updateVo.setKey(savedVo.getKey());
updateVo.setLogin(username);
updateVo.setFirstName("Maximilien");
updateVo.setLastName("Smith");
updateVo.setEmail(email);
updateVo.putProperty("gender", "male");
URI updateRequest = UriBuilder.fromUri(getContextURI()).path("users").path(savedVo.getKey().toString()).build();
HttpPost updateMethod = conn.createPost(updateRequest, MediaType.APPLICATION_JSON);
conn.addJsonEntity(updateMethod, updateVo);
updateMethod.addHeader("Accept-Language", "en");
HttpResponse updateResponse = conn.execute(updateMethod);
int statusCode = updateResponse.getStatusLine().getStatusCode();
Assert.assertEquals(200, statusCode);
UserVO updatedVo = conn.parse(updateResponse, UserVO.class);
dbInstance.commitAndCloseSession();
Identity updatedIdent = securityManager.loadIdentityByKey(savedVo.getKey());
Assert.assertNotNull(updatedVo);
Assert.assertNotNull(updatedIdent);
Assert.assertEquals(updatedVo.getKey(), savedIdent.getKey());
Assert.assertEquals(updatedVo.getKey(), updatedIdent.getKey());
Assert.assertEquals("Maximilien", updatedIdent.getUser().getFirstName());
conn.shutdown();
}
/**
* Test if we can create two users with the same email addresses.
*/
@Test
public void testCreateAndUpdateUser_same_email() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
String email = UUID.randomUUID() + "@frentix.com";
UserVO vo = new UserVO();
String username = UUID.randomUUID().toString();
vo.setLogin(username);
vo.setFirstName("John");
vo.setLastName("Smith");
vo.setEmail(email);
vo.putProperty("gender", "male");//male or female
URI request = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(method, vo);
method.addHeader("Accept-Language", "en");
HttpResponse response = conn.execute(method);
assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);
UserVO savedVo = conn.parse(response, UserVO.class);
Identity savedIdent = securityManager.loadIdentityByKey(savedVo.getKey());
Assert.assertNotNull(savedVo);
Assert.assertNotNull(savedIdent);
//second user
String secondEmail = UUID.randomUUID() + "@frentix.com";
String secondUsername = UUID.randomUUID().toString();
UserVO secondVo = new UserVO();
secondVo.setLogin(secondUsername);
secondVo.setFirstName("Eva");
secondVo.setLastName("Smith");
secondVo.setEmail(secondEmail);
secondVo.putProperty("gender", "female");
URI secondRequest = UriBuilder.fromUri(getContextURI()).path("users").build();
HttpPut secondMethod = conn.createPut(secondRequest, MediaType.APPLICATION_JSON, true);
conn.addJsonEntity(secondMethod, secondVo);
secondMethod.addHeader("Accept-Language", "en");
HttpResponse secondResponse = conn.execute(secondMethod);
int secondStatusCode = secondResponse.getStatusLine().getStatusCode();
Assert.assertEquals(200, secondStatusCode);
UserVO secondSavedVo = conn.parse(secondResponse, UserVO.class);
Assert.assertNotNull(secondSavedVo);
dbInstance.commitAndCloseSession();
Identity secondSavedIdent = securityManager.loadIdentityByKey(secondSavedVo.getKey());
Assert.assertNotNull(secondSavedIdent);
Assert.assertEquals(secondEmail, secondSavedIdent.getUser().getEmail());
// update second with new first name and the mail of the first user
UserVO updateVo = new UserVO();
updateVo.setKey(secondSavedVo.getKey());
updateVo.setLogin(secondUsername);
updateVo.setFirstName("Caprice");
updateVo.setLastName("Smith");
updateVo.setEmail(email);
updateVo.putProperty("gender", "female");
URI updateRequest = UriBuilder.fromUri(getContextURI()).path("users").path(secondSavedVo.getKey().toString()).build();
HttpPost updateMethod = conn.createPost(updateRequest, MediaType.APPLICATION_JSON);
conn.addJsonEntity(updateMethod, updateVo);
updateMethod.addHeader("Accept-Language", "en");
HttpResponse updateResponse = conn.execute(updateMethod);
int statusCode = updateResponse.getStatusLine().getStatusCode();
Assert.assertEquals(406, statusCode);
String errorMessage = EntityUtils.toString(updateResponse.getEntity());
Assert.assertNotNull(errorMessage);
// check that nothing has changed for the second user
dbInstance.commitAndCloseSession();
Identity notUpdatedIdent = securityManager.loadIdentityByKey(secondSavedVo.getKey());
Assert.assertNotNull(notUpdatedIdent);
Assert.assertEquals("Eva", notUpdatedIdent.getUser().getFirstName());
Assert.assertEquals("Smith", notUpdatedIdent.getUser().getLastName());
Assert.assertEquals(secondEmail, notUpdatedIdent.getUser().getEmail());
conn.shutdown();
}
@Test
public void testUpdateUser_emptyInstitutionalEmail() throws IOException, URISyntaxException {
String login = "update-" + UUID.randomUUID();
User user = userManager.createUser(login, login, login + "@openolat.com");
user.setProperty(UserConstants.INSTITUTIONALEMAIL, "inst" + login + "@openolat.com");
Identity id = securityManager.createAndPersistIdentityAndUser(null, login, null, user, "OLAT", BaseSecurity.DEFAULT_ISSUER, login, "secret", null);
Organisation organisation = organisationService.getDefaultOrganisation();
organisationService.addMember(organisation, id, OrganisationRoles.user);
dbInstance.commitAndCloseSession();
Assert.assertEquals("inst" + login + "@openolat.com", id.getUser().getInstitutionalEmail());
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
// set the institutional email empty
UserVO updateVo = new UserVO();
updateVo.setKey(id.getKey());
updateVo.setLogin(id.getName());
updateVo.setFirstName(id.getUser().getFirstName());
updateVo.setLastName(id.getUser().getLastName());
updateVo.setEmail(id.getUser().getEmail());
updateVo.putProperty(UserConstants.INSTITUTIONALEMAIL, "");
URI updateRequest = UriBuilder.fromUri(getContextURI()).path("users").path(id.getKey().toString()).build();
HttpPost updateMethod = conn.createPost(updateRequest, MediaType.APPLICATION_JSON);
conn.addJsonEntity(updateMethod, updateVo);
updateMethod.addHeader("Accept-Language", "en");
HttpResponse updateResponse = conn.execute(updateMethod);
int statusCode = updateResponse.getStatusLine().getStatusCode();
Assert.assertEquals(200, statusCode);
EntityUtils.consume(updateResponse.getEntity());
Identity identity = securityManager.loadIdentityByKey(id.getKey());
String institutionalEmail = identity.getUser().getInstitutionalEmail();
Assert.assertTrue(institutionalEmail == null || institutionalEmail.isEmpty());
}
@Test
public void testDeleteUser() throws IOException, URISyntaxException {
Identity idToDelete = JunitTestHelper.createAndPersistIdentityAsUser("user-to-delete-" + UUID.randomUUID());
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//delete an authentication token
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + idToDelete.getKey()).build();
HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_XML);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
Identity deletedIdent = securityManager.loadIdentityByKey(idToDelete.getKey());
assertNotNull(deletedIdent);//Identity aren't deleted anymore
assertEquals(Identity.STATUS_DELETED, deletedIdent.getStatus());
conn.shutdown();
}
@Test
public void testGetRoles() throws IOException, URISyntaxException {
//create an author
Identity author = JunitTestHelper.createAndPersistIdentityAsRndAuthor("author-");
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//get roles of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + author.getKey() + "/roles").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
RolesVO roles = conn.parse(response, RolesVO.class);
Assert.assertNotNull(roles);
Assert.assertTrue(roles.isAuthor());
Assert.assertFalse(roles.isGroupManager());
Assert.assertFalse(roles.isGuestOnly());
Assert.assertFalse(roles.isInstitutionalResourceManager());
Assert.assertFalse(roles.isInvitee());
Assert.assertFalse(roles.isOlatAdmin());
Assert.assertFalse(roles.isUserManager());
conn.shutdown();
}
@Test
public void testGetRoles_xml() throws IOException, URISyntaxException {
//create an author
Identity author = JunitTestHelper.createAndPersistIdentityAsRndAuthor("author-");
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//get roles of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + author.getKey() + "/roles").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_XML, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
String xmlOutput = EntityUtils.toString(response.getEntity());
Assert.assertTrue(xmlOutput.contains("<rolesVO>"));
Assert.assertTrue(xmlOutput.contains("<olatAdmin>"));
conn.shutdown();
}
@Test
public void getRoles_itself() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI rolesUri = UriBuilder.fromUri(getContextURI())
.path("users").path(id1.getKey().toString()).path("roles").build();
HttpGet method = conn.createGet(rolesUri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
RolesVO vo = conn.parse(response, RolesVO.class);
Assert.assertNotNull(vo);
Assert.assertFalse(vo.isInvitee());
Assert.assertFalse(vo.isGuestOnly());
conn.shutdown();
}
@Test
public void getRoles_notItself() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI rolesUri = UriBuilder.fromUri(getContextURI())
.path("users").path(id2.getKey().toString()).path("roles").build();
HttpGet method = conn.createGet(rolesUri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(403, response.getStatusLine().getStatusCode());
conn.shutdown();
}
@Test
public void testUpdateRoles() throws IOException, URISyntaxException {
//create an author
Identity author = JunitTestHelper.createAndPersistIdentityAsAuthor("author-" + UUID.randomUUID().toString());
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
RolesVO roles = new RolesVO();
roles.setAuthor(true);
roles.setUserManager(true);
//get roles of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + author.getKey() + "/roles").build();
HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
conn.addJsonEntity(method, roles);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
RolesVO modRoles = conn.parse(response, RolesVO.class);
Assert.assertNotNull(modRoles);
//check the roles
Roles reloadRoles = securityManager.getRoles(author);
Assert.assertTrue(reloadRoles.isAuthor());
Assert.assertFalse(reloadRoles.isGroupManager());
Assert.assertFalse(reloadRoles.isGuestOnly());
Assert.assertFalse(reloadRoles.isLearnResourceManager());
Assert.assertFalse(reloadRoles.isInvitee());
Assert.assertFalse(reloadRoles.isAdministrator());
Assert.assertFalse(reloadRoles.isPoolManager());
Assert.assertTrue(reloadRoles.isUserManager());
conn.shutdown();
}
@Test
public void testGetStatus() throws IOException, URISyntaxException {
//create an author
Identity user = JunitTestHelper.createAndPersistIdentityAsUser("status-" + UUID.randomUUID().toString());
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//get roles of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + user.getKey() + "/status").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
StatusVO status = conn.parse(response, StatusVO.class);
Assert.assertNotNull(status);
Assert.assertNotNull(status.getStatus());
Assert.assertEquals(2, status.getStatus().intValue());
conn.shutdown();
}
@Test
public void testUpdateStatus() throws IOException, URISyntaxException {
//create a user
Identity user = JunitTestHelper.createAndPersistIdentityAsUser("login-denied-1-" + UUID.randomUUID().toString());
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
StatusVO status = new StatusVO();
status.setStatus(101);
//get roles of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + user.getKey() + "/status").build();
HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
conn.addJsonEntity(method, status);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
StatusVO modStatus = conn.parse(response, StatusVO.class);
Assert.assertNotNull(modStatus);
Assert.assertNotNull(modStatus.getStatus());
Assert.assertEquals(101, modStatus.getStatus().intValue());
//check the roles
Identity reloadIdentity = securityManager.loadIdentityByKey(user.getKey());
Assert.assertNotNull(reloadIdentity);
Assert.assertNotNull(reloadIdentity.getStatus());
Assert.assertEquals(101, reloadIdentity.getStatus().intValue());
conn.shutdown();
}
/**
* Test if a standard user can change the status of someone else
* @throws IOException
* @throws URISyntaxException
*/
@Test
public void testUpdateStatus_denied() throws IOException, URISyntaxException {
//create a user
IdentityWithLogin user = JunitTestHelper.createAndPersistRndUser("login-denied-2");
IdentityWithLogin hacker = JunitTestHelper.createAndPersistRndUser("login-denied-2");
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login(hacker));
StatusVO status = new StatusVO();
status.setStatus(101);
//get roles of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + user.getKey() + "/status").build();
HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
conn.addJsonEntity(method, status);
HttpResponse response = conn.execute(method);
assertEquals(403, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
conn.shutdown();
}
@Test
public void testGetPreferences() throws IOException, URISyntaxException {
//create an author
Identity prefsId = JunitTestHelper.createAndPersistIdentityAsAuthor("prefs-1-" + UUID.randomUUID().toString());
dbInstance.commitAndCloseSession();
prefsId.getUser().getPreferences().setLanguage("fr");
userManager.updateUserFromIdentity(prefsId);
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//get preferences of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + prefsId.getKey() + "/preferences").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
PreferencesVO prefsVo = conn.parse(response, PreferencesVO.class);
Assert.assertNotNull(prefsVo);
Assert.assertEquals("fr", prefsVo.getLanguage());
conn.shutdown();
}
@Test
public void testUpdatePreferences() throws IOException, URISyntaxException {
//create an author
Identity prefsId = JunitTestHelper.createAndPersistIdentityAsAuthor("prefs-1-" + UUID.randomUUID().toString());
dbInstance.commitAndCloseSession();
prefsId.getUser().getPreferences().setLanguage("de");
userManager.updateUserFromIdentity(prefsId);
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
PreferencesVO prefsVo = new PreferencesVO();
prefsVo.setLanguage("fr");
//get roles of author
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + prefsId.getKey() + "/preferences").build();
HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
conn.addJsonEntity(method, prefsVo);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
PreferencesVO modPrefs = conn.parse(response, PreferencesVO.class);
Assert.assertNotNull(modPrefs);
Assert.assertEquals("fr", prefsVo.getLanguage());
//double check
Identity reloadedPrefsId = securityManager.loadIdentityByKey(prefsId.getKey());
Assert.assertNotNull(reloadedPrefsId);
Assert.assertEquals("fr", reloadedPrefsId.getUser().getPreferences().getLanguage());
conn.shutdown();
}
@Test
public void testUserForums() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("forums")
.queryParam("start", 0).queryParam("limit", 20).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
ForumVOes forums = conn.parse(response, ForumVOes.class);
assertNotNull(forums);
assertNotNull(forums.getForums());
assertTrue(forums.getForums().length > 0);
for(ForumVO forum:forums.getForums()) {
Long groupKey = forum.getGroupKey();
if(groupKey != null) {
BusinessGroup bg = businessGroupService.loadBusinessGroup(groupKey);
assertNotNull(bg);
CollaborationTools bgCTSMngr = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(bg);
assertTrue(bgCTSMngr.isToolEnabled(CollaborationTools.TOOL_FORUM));
assertNotNull(forum.getForumKey());
assertEquals(bg.getName(), forum.getName());
assertEquals(bg.getKey(), forum.getGroupKey());
assertTrue(businessGroupService.isIdentityInBusinessGroup(id1.getIdentity(), bg));
} else {
assertNotNull(forum.getCourseKey());
}
}
conn.shutdown();
}
@Test
public void testUserGroupForum() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("forums")
.path("group").path(g1.getKey().toString())
.path("threads").queryParam("start", "0").queryParam("limit", "25").build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
MessageVOes threads = conn.parse(response, MessageVOes.class);
assertNotNull(threads);
assertNotNull(threads.getMessages());
assertTrue(threads.getMessages().length > 0);
conn.shutdown();
}
@Test
public void testUserCourseForum() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("forums")
.path("course").path(demoCourse.getResourceableId().toString()).path(demoForumNode.getIdent())
.path("threads").queryParam("start", "0").queryParam("limit", 25).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
MessageVOes threads = conn.parse(response, MessageVOes.class);
assertNotNull(threads);
assertNotNull(threads.getMessages());
assertTrue(threads.getMessages().length > 0);
conn.shutdown();
}
@Test
public void testUserFolders() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders").build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
FolderVOes folders = conn.parse(response, FolderVOes.class);
assertNotNull(folders);
assertNotNull(folders.getFolders());
assertTrue(folders.getFolders().length > 0);
boolean matchG2 = false;
for(FolderVO folder:folders.getFolders()) {
Long groupKey = folder.getGroupKey();
if(groupKey != null) {
BusinessGroup bg = businessGroupService.loadBusinessGroup(groupKey);
assertNotNull(bg);
CollaborationTools bgCTSMngr = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(bg);
assertTrue(bgCTSMngr.isToolEnabled(CollaborationTools.TOOL_FOLDER));
assertEquals(bg.getName(), folder.getName());
assertEquals(bg.getKey(), folder.getGroupKey());
assertTrue(businessGroupService.isIdentityInBusinessGroup(id1.getIdentity(), bg));
if(g2.getKey().equals(groupKey)) {
matchG2 = true;
}
} else {
assertNotNull(folder.getCourseKey());
}
}
//id1 is participant of g2. Make sure it found the folder
assertTrue(matchG2);
conn.shutdown();
}
@Test
public void testUserGroupFolder() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders")
.path("group").path(g2.getKey().toString()).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<FileVO> folders = parseFileArray(response.getEntity());
assertNotNull(folders);
assertFalse(folders.isEmpty());
assertEquals(1, folders.size()); //private and public
FileVO portrait = folders.get(0);
assertEquals("portrait.jpg", portrait.getTitle());
conn.shutdown();
}
@Test
public void testUserBCCourseNodeFolder() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders")
.path("course").path(demoCourse.getResourceableId().toString()).path(demoBCCourseNode.getIdent()).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<FileVO> folders = parseFileArray(response.getEntity());
assertNotNull(folders);
assertFalse(folders.isEmpty());
assertEquals(1, folders.size()); //private and public
FileVO singlePage = folders.get(0);
assertEquals("singlepage.html", singlePage.getTitle());
conn.shutdown();
}
@Test
public void testUserPersonalFolder() throws Exception {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders").path("personal").build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<FileVO> files = parseFileArray(response.getEntity());
assertNotNull(files);
assertFalse(files.isEmpty());
assertEquals(2, files.size()); //private and public
conn.shutdown();
}
@Test
public void testOtherUserPersonalFolder() throws Exception {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id2.getKey().toString()).path("folders").path("personal").build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<FileVO> files = parseFileArray(response.getEntity());
assertNotNull(files);
assertTrue(files.isEmpty());
assertEquals(0, files.size()); //private and public
conn.shutdown();
}
@Test
public void testOtherUserPersonalFolderOfId3() throws Exception {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id3.getKey().toString()).path("folders").path("personal").build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<FileVO> files = parseFileArray(response.getEntity());
assertNotNull(files);
assertFalse(files.isEmpty());
assertEquals(1, files.size()); //private and public
FileVO portrait = files.get(0);
assertEquals("portrait.jpg", portrait.getTitle());
conn.shutdown();
}
@Test
public void testUserGroup() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve all groups
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey() + "/groups").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<GroupVO> groups = parseGroupArray(response.getEntity());
assertNotNull(groups);
assertEquals(3, groups.size());//g1, g2 and g3
conn.shutdown();
}
@Test
public void testUserGroup_managed() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve managed groups
URI request = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups")
.queryParam("managed", "true").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<GroupVO> groups = parseGroupArray(response.getEntity());
assertNotNull(groups);
assertEquals(2, groups.size());//g1 and g3
conn.shutdown();
}
@Test
public void testUserGroup_notManaged() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve free groups
URI request = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups")
.queryParam("managed", "false").build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<GroupVO> groups = parseGroupArray(response.getEntity());
assertNotNull(groups);
assertEquals(1, groups.size());//g2
conn.shutdown();
}
@Test
public void testUserGroup_externalId() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve g1
URI request = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups")
.queryParam("externalId", g1externalId).build();
HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
List<GroupVO> groups = parseGroupArray(response.getEntity());
assertNotNull(groups);
assertEquals(1, groups.size());
assertEquals(g1.getKey(), groups.get(0).getKey());
assertEquals(g1externalId, groups.get(0).getExternalId());
conn.shutdown();
}
@Test
public void testUserGroupWithPaging() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve all groups
URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups")
.queryParam("start", 0).queryParam("limit", 1).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
GroupVOes groups = conn.parse(response, GroupVOes.class);
assertNotNull(groups);
assertNotNull(groups.getGroups());
assertEquals(1, groups.getGroups().length);
assertEquals(3, groups.getTotalCount());//g1, g2 and g3
conn.shutdown();
}
@Test
public void testUserGroup_checkRefusedAccess() throws IOException, URISyntaxException {
IdentityWithLogin alien = JunitTestHelper.createAndPersistRndUser("user-group-alien-");
dbInstance.commitAndCloseSession();
RestConnection conn = new RestConnection();
assertTrue(conn.login(alien));
//retrieve all groups
URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups")
.queryParam("start", 0).queryParam("limit", 1).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(401, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
conn.shutdown();
}
@Test
public void testUserGroup_checkAllowedAccess() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
//retrieve all groups
URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups")
.queryParam("start", 0).queryParam("limit", 1).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
GroupVOes groups = conn.parse(response, GroupVOes.class);
assertNotNull(groups);
assertNotNull(groups.getGroups());
conn.shutdown();
}
@Test
public void testUserGroup_owner() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve all groups
URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString())
.path("groups").path("owner").queryParam("start", 0).queryParam("limit", 1).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
GroupVOes groups = conn.parse(response, GroupVOes.class);
assertNotNull(groups);
assertNotNull(groups.getGroups());
assertEquals(1, groups.getGroups().length);
assertEquals(1, groups.getTotalCount());//g1
conn.shutdown();
}
@Test
public void testUserGroup_participant() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve all groups
URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString())
.path("groups").path("participant").queryParam("start", 0).queryParam("limit", 1).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
GroupVOes groups = conn.parse(response, GroupVOes.class);
assertNotNull(groups);
assertNotNull(groups.getGroups());
assertEquals(1, groups.getGroups().length);
assertEquals(2, groups.getTotalCount());//g2 and g3
conn.shutdown();
}
@Test
public void testUserGroupInfosWithPaging() throws IOException, URISyntaxException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
//retrieve all groups
URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups").path("infos")
.queryParam("start", 0).queryParam("limit", 1).build();
HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
GroupInfoVOes groups = conn.parse(response, GroupInfoVOes.class);
assertNotNull(groups);
assertNotNull(groups.getGroups());
assertEquals(1, groups.getGroups().length);
assertEquals(3, groups.getTotalCount());//g1, g2 and g3
conn.shutdown();
}
@Test
public void testPortrait() throws IOException, URISyntaxException {
URL portraitUrl = UserMgmtTest.class.getResource("portrait.jpg");
assertNotNull(portraitUrl);
File portrait = new File(portraitUrl.toURI());
RestConnection conn = new RestConnection();
assertTrue(conn.login(id1));
//upload portrait
URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey() + "/portrait").build();
HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
conn.addMultipart(method, "portrait.jpg", portrait);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
//check if big and small portraits exist
File bigPortrait = portraitManager.getBigPortrait(id1.getIdentity());
assertNotNull(bigPortrait);
assertTrue(bigPortrait.exists());
assertTrue(bigPortrait.exists());
//check get portrait
URI getRequest = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey() + "/portrait").build();
HttpGet getMethod = conn.createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true);
HttpResponse getResponse = conn.execute(getMethod);
assertEquals(200, getResponse.getStatusLine().getStatusCode());
InputStream in = getResponse.getEntity().getContent();
int b = 0;
int count = 0;
while((b = in.read()) > -1) {
count++;
}
assertEquals(-1, b);//up to end of file
assertTrue(count > 1000);//enough bytes
bigPortrait = portraitManager.getBigPortrait(id1.getIdentity());
assertNotNull(bigPortrait);
assertEquals(count, bigPortrait.length());
//check get portrait as Base64
UriBuilder getRequest2 = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).queryParam("withPortrait", "true");
HttpGet getMethod2 = conn.createGet(getRequest2.build(), MediaType.APPLICATION_JSON, true);
HttpResponse getCode2 = conn.execute(getMethod2);
assertEquals(200, getCode2.getStatusLine().getStatusCode());
UserVO userVo = conn.parse(getCode2, UserVO.class);
assertNotNull(userVo);
assertNotNull(userVo.getPortrait());
byte[] datas = Base64.decodeBase64(userVo.getPortrait().getBytes());
assertNotNull(datas);
assertTrue(datas.length > 0);
File smallPortrait = portraitManager.getSmallPortrait(id1.getIdentity());
assertNotNull(smallPortrait);
assertEquals(datas.length, smallPortrait.length());
try {
ImageIO.read(new ByteArrayInputStream(datas));
} catch (Exception e) {
assertFalse("Cannot read the portrait after Base64 encoding/decoding", false);
}
conn.shutdown();
}
@Test
public void testPortrait_HEAD() throws IOException, URISyntaxException {
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("portrait-1");
Identity idWithoutPortrait = JunitTestHelper.createAndPersistIdentityAsRndUser("portrait-2");
URL portraitUrl = UserMgmtTest.class.getResource("portrait.jpg");
Assert.assertNotNull(portraitUrl);
File portrait = new File(portraitUrl.toURI());
RestConnection conn = new RestConnection();
Assert.assertTrue(conn.login(id));
//upload portrait
URI request = UriBuilder.fromUri(getContextURI())
.path("users").path(id.getKey().toString()).path("portrait").build();
HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
conn.addMultipart(method, "portrait.jpg", portrait);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
//check 200
URI headRequest = UriBuilder.fromUri(getContextURI())
.path("users").path(id.getKey().toString()).path("portrait").build();
HttpHead headMethod = conn.createHead(headRequest, MediaType.APPLICATION_OCTET_STREAM, true);
HttpResponse headResponse = conn.execute(headMethod);
assertEquals(200, headResponse.getStatusLine().getStatusCode());
EntityUtils.consume(headResponse.getEntity());
//check 404
URI headNoRequest = UriBuilder.fromUri(getContextURI())
.path("users").path(idWithoutPortrait.getKey().toString()).path("portrait").build();
HttpHead headNoMethod = conn.createHead(headNoRequest, MediaType.APPLICATION_OCTET_STREAM, true);
HttpResponse headNoResponse = conn.execute(headNoMethod);
assertEquals(404, headNoResponse.getStatusLine().getStatusCode());
EntityUtils.consume(headNoResponse.getEntity());
}
/**
* Check the 3 sizes
* @throws IOException
* @throws URISyntaxException
*/
@Test
public void testPortrait_HEAD_sizes() throws IOException, URISyntaxException {
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("portrait-3");
URL portraitUrl = UserMgmtTest.class.getResource("portrait.jpg");
Assert.assertNotNull(portraitUrl);
File portrait = new File(portraitUrl.toURI());
RestConnection conn = new RestConnection();
Assert.assertTrue(conn.login(id));
//upload portrait
URI request = UriBuilder.fromUri(getContextURI())
.path("users").path(id.getKey().toString()).path("portrait").build();
HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
conn.addMultipart(method, "portrait.jpg", portrait);
HttpResponse response = conn.execute(method);
assertEquals(200, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
//check 200
URI headMasterRequest = UriBuilder.fromUri(getContextURI())
.path("users").path(id.getKey().toString()).path("portrait").path("master").build();
HttpHead headMasterMethod = conn.createHead(headMasterRequest, MediaType.APPLICATION_OCTET_STREAM, true);
HttpResponse headMasterResponse = conn.execute(headMasterMethod);
assertEquals(200, headMasterResponse.getStatusLine().getStatusCode());
EntityUtils.consume(headMasterResponse.getEntity());
//check 200
URI headBigRequest = UriBuilder.fromUri(getContextURI())
.path("users").path(id.getKey().toString()).path("portrait").path("big").build();
HttpHead headBigMethod = conn.createHead(headBigRequest, MediaType.APPLICATION_OCTET_STREAM, true);
HttpResponse headBigResponse = conn.execute(headBigMethod);
assertEquals(200, headBigResponse.getStatusLine().getStatusCode());
EntityUtils.consume(headBigResponse.getEntity());
//check 200
URI headSmallRequest = UriBuilder.fromUri(getContextURI())
.path("users").path(id.getKey().toString()).path("portrait").path("small").build();
HttpHead headSmallMethod = conn.createHead(headSmallRequest, MediaType.APPLICATION_OCTET_STREAM, true);
HttpResponse headSmallResponse = conn.execute(headSmallMethod);
assertEquals(200, headSmallResponse.getStatusLine().getStatusCode());
EntityUtils.consume(headSmallResponse.getEntity());
}
@Test
public void rename() throws URISyntaxException, IOException {
RestConnection conn = new RestConnection();
assertTrue(conn.login("administrator", "openolat"));
IdentityWithLogin id = JunitTestHelper.createAndPersistRndUser("portrait-3");
String newUsername = UUID.randomUUID().toString();
URI request = UriBuilder.fromUri(getContextURI()).path("users").path(id.getKey().toString())
.path("username").queryParam("username", newUsername).build();
HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
HttpResponse response = conn.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
Identity renamedId = securityManager.loadIdentityByKey(id.getKey());
Assert.assertEquals(newUsername, renamedId.getUser().getNickName());
Authentication auth = securityManager.findAuthentication(renamedId, "OLAT", BaseSecurity.DEFAULT_ISSUER);
Assert.assertNotNull(auth);
Assert.assertEquals(newUsername, auth.getAuthusername());
}
protected List<UserVO> parseUserArray(HttpEntity entity) {
try(InputStream in=entity.getContent()) {
ObjectMapper mapper = new ObjectMapper(jsonFactory);
return mapper.readValue(in, new TypeReference<List<UserVO>>(){/* */});
} catch (Exception e) {
log.error("", e);
return null;
}
}
protected List<ManagedUserVO> parseManagedUserArray(HttpEntity entity) {
try(InputStream in=entity.getContent()) {
ObjectMapper mapper = new ObjectMapper(jsonFactory);
return mapper.readValue(in, new TypeReference<List<ManagedUserVO>>(){/* */});
} catch (Exception e) {
log.error("", e);
return null;
}
}
protected List<GroupVO> parseGroupArray(HttpEntity entity) {
try(InputStream in=entity.getContent()) {
ObjectMapper mapper = new ObjectMapper(jsonFactory);
return mapper.readValue(in, new TypeReference<List<GroupVO>>(){/* */});
} catch (Exception e) {
log.error("", e);
return null;
}
}
} |
Nasal Glial Heterotopia in a 1-Year-Old Child A Case Report: Histopathology is the Ultimate Gold Standard for Diagnosis!! Nasal glial heterotopia (NGH) is a benign congenital malformation wherein abnormally located mature brain (glial) tissue presents as a mass on the forehead or nasal root area. Rarity of this condition makes clinical level diagnosis a challenge. Differential diagnoses for NGH are dermoid cyst, encephalocoele, hemangioma, allergic nasal polyp, or chronic otitis media. NGH has no direct communication with intracranial cavity, unlike an encephalocoele. However, potential intracranial connection is possible, through cribriform plate or bony deformities. Therefore, pre-operative aspiration and biopsies are contraindicated in childhood swellings in forehead/nasal bridge area. Instead, pre-operative imaging modality investigations are mandatory. It is also important to note the risk for the removal of functional brain tissue and also post-operative meningitis or cerebrospinal fluid rhinorrhea. A 1-year-old female child presented with a mass on nasal bridge. Overlying skin was unremarkable. Swelling did not increase in size on coughing. Diagnosis: Dermoid cyst/encephalocoele. Computed tomography (CT) scan investigation: CT scan confirmed the diagnosis of nasal encephalocoele > nasal dermoid. The mass was excised. Histopathology (histopathological examination ): The excised specimen was a single, unencapsulated, ovoid, and soft to firm, yellow-colored tissue bit, measuring 2.5 cm 2 cm 1 cm. On cut section, there were no cystic areas/spongy appearance/mucoid bits. Hematoxylin and eosin-stained sections revealed a poorly circumscribed mass, showing a population of cells with ovoid or irregular nuclei and a fibrillary stroma resembling cerebral and glial tissue. These were arranged in a disorganized fashion and were surrounded by fibrous tissue and few skeletal muscle fibers. All HPE findings point toward the diagnosis of NGH. It is important to consider NGH as a differential, in case of childhood swellings in the forehead and nasal root region. Histopathology remains the gold standard for diagnosis. |
Middlesbrough FC boss Aitor Karanka says it's a “pleasure” to have players like Alvaro Negredo, Jordan Rhodes and David Nugent as attacking options.
All three were involved against Alcorcon at the Marbella Football Center on Saturday evening with Negredo and Rhodes netting in a 2-2 draw.
The match was a physical and eventful encounter with the second division side from Madrid giving as good as they got.
Making his Boro debut, Negredo scored an extremely well-taken goal in the 34 minute but Alcorcon levelled through Pedreno 10 minutes into the second half.
Rhodes looked to have secured a win for his team with a stoppage time header from Carlos de Pena's cross, but Alcorcon raced up the other end of the pitch to equalise with the last kick of the game through Juan Bautista.
But despite the late goal, Karanka was pleased with the workout - telling The Gazette that Negredo's classy finish came as no surprise to him.
“He's a really good player and a player who can play in the Premier League for sure,” Karanka said.
“We can't forget that Valencia paid €30m for him two years ago so a player like him, you don't forget how to play.
At half-time, Karanka switched systems from 4-2-3-1 to 4-4-2, sending on Rhodes and Nugent to play in attack.
On the options at his disposal, the Boro boss added: “We have a lot of alternatives and to have Negredo playing in the first half and in the second half to have Nugent and Rhodes is a pleasure.
The match also saw Victor Valdes make his Boro debut, but in truth he rarely touched the ball - and when he did the saves he had to make were fairly routine.
Viktor Fischer got more minutes under his belt as did Marten de Roon.
On their performances, Karanka said: “Viktor is a good lad, it's difficult when you are coming from another country, you can be surprised with the intensity but he is enjoying it, he is improving every day. |
import java.util.*;
public class Suffix {
static String[][] languages = { {"po", "FILIPINO"},
{"desu", "JAPANESE"},
{"masu", "JAPANESE"},
{"mnida", "KOREAN"}
};
public static void suffixLang(String stri) {
int finalIndex = 0;
// for (int i = 0; i < stri.length(); i++) {
for (String[] test: languages) {
if(stri.contains(test[0]) && stri.lastIndexOf(test[0]) == (stri.length() - test[0].length())) {
System.out.println(test[1]);
break;
}
}
// }
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int i = 0;
int n1 = s.nextInt();
String[] str = new String[n1+1];
while(s.hasNextLine()) {
str[i] = s.nextLine();
i++;
}
for (int j = 0; j < str.length; j ++) {
suffixLang(str[j]);
}
}
}
|
package pl.gov.coi.example.calc;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @since 17.11.16
*/
public class CalcTest {
@Test
public void testAdd() {
// given
int a = 5;
int b = 4;
Calc calc = new Calc();
// when
int result = calc.add(a, b);
// then
assertEquals(9, result);
}
} |
<gh_stars>0
package sonarscanner
import "fmt"
type AnalysisStatus int
const (
AnalysisStatusUndefined AnalysisStatus = iota
AnalysisStatusOk AnalysisStatus = iota
AnalysisStatusWarning AnalysisStatus = iota
AnalysisStatusError AnalysisStatus = iota
AnalysisStatusNone AnalysisStatus = iota
)
const (
analysisStatusUndefinedStr = "UNDEFINED"
analysisStatusOkStr = "OK"
analysisStatusWarningStr = "WARN"
analysisStatusErrorStr = "ERROR"
analysisStatusNoneStr = "NONE"
)
func (status AnalysisStatus) String() string {
switch status {
case AnalysisStatusOk:
return analysisStatusOkStr
case AnalysisStatusWarning:
return analysisStatusWarningStr
case AnalysisStatusError:
return analysisStatusErrorStr
case AnalysisStatusNone:
return analysisStatusNoneStr
default:
return analysisStatusUndefinedStr
}
}
func parseAnalysisStatus(value string) (AnalysisStatus, error) {
switch value {
case analysisStatusOkStr:
return AnalysisStatusOk, nil
case analysisStatusWarningStr:
return AnalysisStatusWarning, nil
case analysisStatusErrorStr:
return AnalysisStatusError, nil
case analysisStatusNoneStr:
return AnalysisStatusNone, nil
default:
return AnalysisStatusUndefined, fmt.Errorf("unexpected analysis status '%s'", value)
}
}
|
Dan Kennedy (soccer)
Early life and education
Kennedy was born July 22, 1982, in Fullerton, California. He attended El Dorado High School in Placentia, California and played 3 years for the school's varsity soccer team.
He attended the University of California, Santa Barbara and was a student-athlete on the UC Santa Barbara Gauchos men's soccer team. As a member of the 2004 UCSB team, he participated in the championship match of the 2004 NCAA Division I Men's Soccer Championship, but lost on penalty kicks. In his four-year career as a starter for UCSB, he appeared in 84 games.
Amateur
During his college years, Kennedy also played with Orange County Blue Star in the USL Premier Development League. He played alongside Jürgen Klinsmann, who played under a pseudonym, as well as UCSB teammate Tony Lochhead. In two seasons with the club, Kennedy appeared in 21 games.
American start
Kennedy was drafted by C.D. Chivas USA in the 4th Round (38th overall) of the 2005 MLS Supplemental Draft out of UCSB. He was not kept on for the season, but joined MetroStars as a temporary backup due to injuries to their personnel.
Puerto Rico Islanders
He was signed by Hugo Maradona to play with USL First Division side Puerto Rico Islanders in April 2005. He played every minute for the Islanders in the 2005 United Soccer Leagues season en route to being named the 2005 USL First Division Rookie of the Year. He made 55 appearances in his two seasons with the club.
Municipal Iquique
Kennedy was under contract with Puerto Rico and was expected to return for the 2007 United Soccer Leagues season, but was transferred to Primera B de Chile side Municipal Iquique for the 2007 season. He immediately attracted attention for his play, with Club Universidad de Chile, Club Deportivo Universidad Católica, and Cobreloa all rumored to have been interested in him. Kennedy led the Primera B in goals against average for the 2007 season.
Chivas USA
In April 2008, Chivas USA re-acquired their former draft pick to understudy current starter Brad Guzan for the 2008 Major League Soccer season. Guzan, however, was transferred by Chivas to Aston Villa F.C. in July with head coach Preki bringing in veteran Zach Thornton as the number one. A torn hamstring ruled Thornton out for weeks, thrusting Kennedy into the starting role.
With the starting goalkeeper undecided between Thornton and Kennedy ahead of the 2009 Major League Soccer season, a preseason knee injury suffered by Kennedy knocked him out of contention. Rehabilitation on the knee failed and Kennedy underwent reconstructive surgery to his posterior cruciate ligament in June 2009, washing out his entire season.
Thornton remained Chivas USA's starter for the majority of the 2010 Major League Soccer season, but early struggles by Thornton in the 2011 Major League Soccer season led to Kennedy being named the starter. He remained the starter for the rest of the season en route to being named the 2011 Chivas USA Most Valuable Player. December 2011 saw Kennedy sign a multi-year extension with Chivas USA.
Kennedy remained the starter until Chivas folded after the 2014 Major League Soccer season. He finished in second place for the 2012 MLS Goalkeeper of the Year Award despite Chivas USA's last-place finish and participated in the 2012 MLS All-Star Game. In May 2013, he signed a contract extension with Chivas and Major League Soccer through the 2016 season. Francisco Palencia, the Chivas technical director, said of Kennedy at the time of the signing, "He's our captain and our symbol at this moment, so we're very happy to extend this contract." Kennedy celebrated his new contract by scoring his first professional goal on May 28, 2013, on a penalty kick in the 2013 Lamar Hunt U.S. Open Cup against Los Angeles Blues.
Kennedy finished his Chivas USA career as the franchise's all-time leader in games played (144), games started (142), saves (451), and shutouts (28). Despite Chivas USA's demise, Kennedy's future was secure in Major League Soccer due to the extension he previously signed.
FC Dallas
After the contraction of Chivas USA, Kennedy was selected 1st overall in the 2014 MLS Dispersal Draft by FC Dallas. Despite making 16 appearances for Dallas, he became surplus to requirements when Jesse Gonzalez replaced him as a starter.
LA Galaxy
Following the 2015 Major League Soccer season, Kennedy was traded to LA Galaxy in exchange for two picks in the 2017 MLS SuperDraft.
On April 11, 2017, Kennedy announced his retirement from playing professional soccer. |
// WaitForServerWithName waits for a server with specified name appears in the list
func WaitForServerWithName(client *Client, serverName string) (*CloudServer, error) {
completed := false
failCount := 0
var server *CloudServer
for !completed {
servers, _, err := client.CloudServers.List()
if err != nil {
if failCount <= maxRetries {
failCount++
continue
}
return nil, err
}
for _, serverItem := range servers {
if serverItem.Name == serverName {
completed = true
server = &serverItem
}
}
time.Sleep(5 * time.Second)
}
return server, nil
} |
In most conventional data processing systems, a central processor unit (CPU) thereof is generally arranged to operate with its associated memory source units at a synchronous rate which is related to the speed of operation of the memory unit. The memory functions are controlled by the CPU, and the two units are then synchronously operated by the use of appropriate timing signals communicated therebetween.
In such apparatus, the data processing system functions by transferring data among its internal registers, its memory, and its input-output (I/O) devices. The transferring of data involves movement of data between a source and a destination, either directly or through intervening units, such as an arithmetic logic unit (ALU), which appropriately modify the data which is being transferred. The transferring of data with I/O devices occurs over at least one memory bus. In addition, the apparatus has an appropriate independent memory address bus for transferring memory address data.
When memory units associated with the CPU lack synchronous clocks, it is desirable to operate the CPU asynchronously with the memory units, because each of the memory units may operate at a different speed, independent of the CPU operatory speed.
In prior art data processing systems each CPU thereof operates either synchronously or asynchronously with its associated memory units. In the former case, a single clock source is utilized to assure that correct sequencing of the overall data processing operation occurs. In such systems both the CPU and the associated memory units are timed directly from the same clock source. In the latter case, separately and effectively independently operated timing systems, or clocks, are used in the CPU and in its associated memory units. In such asynchronous systems there is no effective relationship between the independently operating clocks. In order to assure that the desired sequence of operations occurs in the CPU and each associated memory unit, the synchronizing of their operations is usually accomplished through appropriate sensing of operating state changes as certain operating signals pass from one binary level to another, such as an edge sensitive synchronizing operations, for example. Relatively elaborate sensing and synchronizing circuitry is usually required for such purpose, and its implementation is relatively expensive.
With most presently known asynchronously operated data processing systems, at least one CPU, and associated control signals used to coordinate its operation with that of its associated memory units are configured so that once a CPU initiates the operation of an associated memory unit, operation of the CPU is effectively halted until an appropriate control signal is received from the associated memory unit to permit resumption of the CPU operations. In such an arrangement, the overall processing time is increased over that which would be required if the CPU were permitted to proceed with at least certain operations simultaneously with the operation of its associated memory units.
In other known data processing apparatus, asynchronous operation is achieved with CPU and associated memory unit clock signals having predetermined phase relationships with each other. The timing between the separate clock pulses of a CPU and each of its associated memory units is asynchronous in the sense that the CPU can operate with associated memory units having different operating speeds, while at the same time the overall timing of each memory unit is made adaptively synchronous to that of its associated CPU because of the predetermined phase relationship between their respective clock pulses. Although this system allows the operation of various memory units at different speeds with a single CPU, separate clocks with a fixed phase relationship are required. In addition, this arrangement requires a clock distribution cable and interface arrangement between the CPU and its associated memory units, just as is the case with synchronous systems. The elimination of this costly addition to the computer system is highly desirable. |
<filename>hjc236_covid_dashboard/tests/test_time_conversions.py
from hjc236_covid_dashboard.time_conversions import *
def test_minutes_to_seconds():
assert minutes_to_seconds(1) == 60
assert minutes_to_seconds("3") == 180
def test_hours_to_minutes():
assert hours_to_minutes(3) == 180
assert hours_to_minutes("2") == 120
def test_hhmm_to_seconds():
assert hhmm_to_seconds("03:00") == 10800
assert hhmm_to_seconds("12:38") == 45480
assert hhmm_to_seconds("foo") is None
assert hhmm_to_seconds("0800") is None
def test_current_time_seconds():
assert current_time_seconds() > 0
|
export * from '../../../domain/entities'
export * from '../../../domain/usecases'
|
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Spino_Character_BP_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function Spino_Character_BP.Spino_Character_BP_C.GetSocketForMeleeTraceForHitBlockers
// ()
// Parameters:
// int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
// struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
struct FName ASpino_Character_BP_C::GetSocketForMeleeTraceForHitBlockers(int* AttackIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.GetSocketForMeleeTraceForHitBlockers");
ASpino_Character_BP_C_GetSocketForMeleeTraceForHitBlockers_Params params;
params.AttackIndex = AttackIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Spino_Character_BP.Spino_Character_BP_C.BlueprintCanAttack
// ()
// Parameters:
// int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
// float* Distance (Parm, ZeroConstructor, IsPlainOldData)
// float* attackRangeOffset (Parm, ZeroConstructor, IsPlainOldData)
// class AActor** OtherTarget (Parm, ZeroConstructor, IsPlainOldData)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool ASpino_Character_BP_C::BlueprintCanAttack(int* AttackIndex, float* Distance, float* attackRangeOffset, class AActor** OtherTarget)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.BlueprintCanAttack");
ASpino_Character_BP_C_BlueprintCanAttack_Params params;
params.AttackIndex = AttackIndex;
params.Distance = Distance;
params.attackRangeOffset = attackRangeOffset;
params.OtherTarget = OtherTarget;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Spino_Character_BP.Spino_Character_BP_C.BPDoAttack
// ()
// Parameters:
// int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::BPDoAttack(int* AttackIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.BPDoAttack");
ASpino_Character_BP_C_BPDoAttack_Params params;
params.AttackIndex = AttackIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.CanSwitchStances
// ()
// Parameters:
// bool isBiped (Parm, ZeroConstructor, IsPlainOldData)
// bool canSwitch (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::CanSwitchStances(bool isBiped, bool* canSwitch)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.CanSwitchStances");
ASpino_Character_BP_C_CanSwitchStances_Params params;
params.isBiped = isBiped;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (canSwitch != nullptr)
*canSwitch = params.canSwitch;
}
// Function Spino_Character_BP.Spino_Character_BP_C.BlueprintCanRiderAttack
// ()
// Parameters:
// int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool ASpino_Character_BP_C::BlueprintCanRiderAttack(int* AttackIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.BlueprintCanRiderAttack");
ASpino_Character_BP_C_BlueprintCanRiderAttack_Params params;
params.AttackIndex = AttackIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Spino_Character_BP.Spino_Character_BP_C.GetStanceSwitchAnim
// ()
// Parameters:
// class UAnimMontage* AnimMontage (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::GetStanceSwitchAnim(class UAnimMontage** AnimMontage)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.GetStanceSwitchAnim");
ASpino_Character_BP_C_GetStanceSwitchAnim_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (AnimMontage != nullptr)
*AnimMontage = params.AnimMontage;
}
// Function Spino_Character_BP.Spino_Character_BP_C.SS_SetCurrentStance
// ()
// Parameters:
// bool isBiped (Parm, ZeroConstructor, IsPlainOldData)
// bool bUseCooldown (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::SS_SetCurrentStance(bool isBiped, bool bUseCooldown)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.SS_SetCurrentStance");
ASpino_Character_BP_C_SS_SetCurrentStance_Params params;
params.isBiped = isBiped;
params.bUseCooldown = bUseCooldown;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.ToggleStance
// ()
void ASpino_Character_BP_C::ToggleStance()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.ToggleStance");
ASpino_Character_BP_C_ToggleStance_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.BPTimerServer
// ()
void ASpino_Character_BP_C::BPTimerServer()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.BPTimerServer");
ASpino_Character_BP_C_BPTimerServer_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.PreInit_SwitchStance
// ()
void ASpino_Character_BP_C::PreInit_SwitchStance()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.PreInit_SwitchStance");
ASpino_Character_BP_C_PreInit_SwitchStance_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.K2_OnMovementModeChanged
// ()
// Parameters:
// TEnumAsByte<EMovementMode>* PrevMovementMode (Parm, ZeroConstructor, IsPlainOldData)
// TEnumAsByte<EMovementMode>* NewMovementMode (Parm, ZeroConstructor, IsPlainOldData)
// unsigned char* PrevCustomMode (Parm, ZeroConstructor, IsPlainOldData)
// unsigned char* NewCustomMode (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::K2_OnMovementModeChanged(TEnumAsByte<EMovementMode>* PrevMovementMode, TEnumAsByte<EMovementMode>* NewMovementMode, unsigned char* PrevCustomMode, unsigned char* NewCustomMode)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.K2_OnMovementModeChanged");
ASpino_Character_BP_C_K2_OnMovementModeChanged_Params params;
params.PrevMovementMode = PrevMovementMode;
params.NewMovementMode = NewMovementMode;
params.PrevCustomMode = PrevCustomMode;
params.NewCustomMode = NewCustomMode;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.GetDefaultDino
// ()
// Parameters:
// class ASpino_Character_BP_C* Dino (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::GetDefaultDino(class ASpino_Character_BP_C** Dino)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.GetDefaultDino");
ASpino_Character_BP_C_GetDefaultDino_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Dino != nullptr)
*Dino = params.Dino;
}
// Function Spino_Character_BP.Spino_Character_BP_C.UpdateMoveSpeed
// ()
void ASpino_Character_BP_C::UpdateMoveSpeed()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.UpdateMoveSpeed");
ASpino_Character_BP_C_UpdateMoveSpeed_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.UpdateStance
// ()
void ASpino_Character_BP_C::UpdateStance()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.UpdateStance");
ASpino_Character_BP_C_UpdateStance_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.OnRep_bIsBiped
// ()
void ASpino_Character_BP_C::OnRep_bIsBiped()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.OnRep_bIsBiped");
ASpino_Character_BP_C_OnRep_bIsBiped_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.CS_Set Biped State
// ()
// Parameters:
// bool isBiped (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::CS_Set_Biped_State(bool isBiped)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.CS_Set Biped State");
ASpino_Character_BP_C_CS_Set_Biped_State_Params params;
params.isBiped = isBiped;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.UserConstructionScript
// ()
void ASpino_Character_BP_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.UserConstructionScript");
ASpino_Character_BP_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.SS_RequestStanceSwitch
// ()
void ASpino_Character_BP_C::SS_RequestStanceSwitch()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.SS_RequestStanceSwitch");
ASpino_Character_BP_C_SS_RequestStanceSwitch_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.StanceSwitch_Delay
// ()
// Parameters:
// float Delay (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::StanceSwitch_Delay(float Delay)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.StanceSwitch_Delay");
ASpino_Character_BP_C_StanceSwitch_Delay_Params params;
params.Delay = Delay;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.ReceiveActorBeginOverlap
// ()
// Parameters:
// class AActor** OtherActor (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::ReceiveActorBeginOverlap(class AActor** OtherActor)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.ReceiveActorBeginOverlap");
ASpino_Character_BP_C_ReceiveActorBeginOverlap_Params params;
params.OtherActor = OtherActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.ReceiveActorEndOverlap
// ()
// Parameters:
// class AActor** OtherActor (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::ReceiveActorEndOverlap(class AActor** OtherActor)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.ReceiveActorEndOverlap");
ASpino_Character_BP_C_ReceiveActorEndOverlap_Params params;
params.OtherActor = OtherActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.Multi_UpdateBuffTime
// ()
// Parameters:
// bool bIsActive (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::Multi_UpdateBuffTime(bool bIsActive)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.Multi_UpdateBuffTime");
ASpino_Character_BP_C_Multi_UpdateBuffTime_Params params;
params.bIsActive = bIsActive;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.AdditiveRoar
// ()
void ASpino_Character_BP_C::AdditiveRoar()
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.AdditiveRoar");
ASpino_Character_BP_C_AdditiveRoar_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Spino_Character_BP.Spino_Character_BP_C.ExecuteUbergraph_Spino_Character_BP
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void ASpino_Character_BP_C::ExecuteUbergraph_Spino_Character_BP(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Spino_Character_BP.Spino_Character_BP_C.ExecuteUbergraph_Spino_Character_BP");
ASpino_Character_BP_C_ExecuteUbergraph_Spino_Character_BP_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
// Check if the filter is well cloned. We send random values to the filter and
// then we clone it. If we send the same new random values to both filters,
// we should have the same filtered results
void InputFilterTest::TestCloneFilter() {
gfx::PointF point;
base::TimeTicks ts = PredictionUnittestHelpers::GetStaticTimeStampForTests();
base::TimeDelta delta = base::Milliseconds(8);
for (int i = 0; i < 100; i++) {
point.SetPoint(base::RandDouble(), base::RandDouble());
EXPECT_TRUE(filter_->Filter(ts, &point));
ts += delta;
}
std::unique_ptr<InputFilter> fork_filter;
fork_filter.reset(filter_->Clone());
gfx::PointF filtered_point, fork_filtered_point;
for (int i = 0; i < 100; i++) {
point.SetPoint(base::RandDouble(), base::RandDouble());
filtered_point = point;
fork_filtered_point = point;
EXPECT_TRUE(filter_->Filter(ts, &filtered_point));
EXPECT_TRUE(fork_filter->Filter(ts, &fork_filtered_point));
EXPECT_NEAR(filtered_point.x(), fork_filtered_point.x(), kEpsilon);
EXPECT_NEAR(filtered_point.y(), fork_filtered_point.y(), kEpsilon);
ts += delta;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.