content
stringlengths 10
4.9M
|
---|
MANAGEMENT DEVELOPMENT PROGRAM
Program Description Emory Medicine’s Management Development Program seeks to attract, position, develop, and advance talent for management and leadership positions. Within three to five years, participants will progress through the three phases, resulting in the opportunity to fill a permanent leadership position upon completion of the program. Participants have the opportunity to join an emerging leader network group, learn from mentors and executive leaders, and participate in continuing professional development. |
// SignGenericJWT takes a set of JWT keys and values to add to a JWT
func (s *JSONWebKeySigner) SignGenericJWT(kvs map[string]interface{}) ([]byte, error) {
t := jwt.New()
for k, v := range kvs {
if err := t.Set(k, v); err != nil {
err := errors.Wrapf(err, "could not set %s to value: %v", k, v)
logrus.WithError(err).Error("could not sign JWT")
return nil, err
}
}
return jwt.Sign(t, jwa.SignatureAlgorithm(s.GetSigningAlgorithm()), s.Key)
} |
def return_creds(self, cred_type='test'):
if cred_type == 'test':
return self.test_secret, self.test_auth, self.phone_number
else:
return self.secret, self.auth, self.phone_number |
<filename>src/structures/EventTokens.ts
/* eslint-disable no-restricted-syntax */
import User from './User';
import Client from '../client/Client';
import Base from '../client/Base';
import { ArenaDivisionData } from '../../resources/structs';
/**
* Represents a user's event tokens
*/
class EventTokens extends Base {
/**
* The user the event tokens belong to
*/
public user: User;
/**
* The raw event tokens
*/
public tokens: string[];
/**
* The user's arena division data
*/
public arenaDivisionData: ArenaDivisionData;
/**
* The user's geo identity
*/
public geoIdentity?: string;
/**
* @param client The main client
* @param data The avatar's data
* @param user The user this avatar belongs to
*/
constructor(client: Client, data: string[], user: User) {
super(client);
this.tokens = data;
this.user = user;
this.arenaDivisionData = {};
this.geoIdentity = undefined;
for (const token of this.tokens) {
const type = token.split('_')[0];
switch (type) {
case 'ARENA': {
let [, season, division] = token.split('_');
if (!division) {
division = season;
season = 'S9';
}
const divisionNumber = parseInt(division.replace('Division', ''), 10);
if (!this.arenaDivisionData[season.toLowerCase()] || this.arenaDivisionData[season.toLowerCase()] < divisionNumber) {
this.arenaDivisionData[season.toLowerCase()] = divisionNumber;
}
} break;
case 'GroupIdentity':
[,, this.geoIdentity] = token.split('_');
break;
}
}
}
}
export default EventTokens;
|
<reponame>noe/pycedict<filename>tests.py
# -*- coding: utf-8 -*-
import unittest
from io import StringIO
from cedict.cedict_parser import iter_cedict
from cedict.pinyin import depinyinize, pinyinize, syllabize
try:
unicode('hi')
except NameError:
def unicode(s, encoding):
return s
SAMPLE_CEDICT = unicode("""齡 龄 [ling2] /age/length of experience, membership etc/
齢 齢 [ling2] /Japanese variant of 齡|龄/
咬 咬 [yao3] /to bite/to nip/
齩 咬 [yao3] /variant of 咬[yao3]/
三氯化磷 三氯化磷 [san1 lu:4 hua4 lin2] /phosphorous trichloride/
麵包房 面包房 [mian4 bao1 fang2] /bakery/CL:家[jia1]/
鮎 鲇 [nian2] /sheatfish (Parasilurus asotus)/oriental catfish/see also 鯰|鲶[nian2]/
鯰 鲶 [nian2] /sheatfish (Parasilurus asotus)/oriental catfish/see also 鮎|鲇[nian2]/""", 'utf-8')
class TestIterCEDict(unittest.TestCase):
def setUp(self):
self.f = StringIO(SAMPLE_CEDICT)
def test_pinyin_correct(self):
entries = {}
for ch, chs, pinyin, defs, variants, mw in iter_cedict(self.f):
entries[chs] = pinyin
self.assertEqual(entries[u'三氯化磷'], 'san1 lv4 hua4 lin2')
self.assertEqual(entries[u'面包房'], 'mian4 bao1 fang2')
self.assertEqual(entries[u'鲇'], 'nian2')
def test_find_entries(self):
entries = []
for ch, chs, pinyin, defs, variants, mw in iter_cedict(self.f):
entries.append(pinyin)
self.assertEqual(8, len(entries))
self.assertEqual('ling2 ling2 yao3 yao3 san1 lv4 '
'hua4 lin2 mian4 bao1 fang2 nian2 nian2', ' '.join(entries))
def test_defs_correct(self):
d = {}
for ch, chs, pinyin, defs, variants, mw in iter_cedict(self.f):
d[ch] = defs
self.assertEqual(d[u'咬'], ['to bite', 'to nip'],
'should find 2 defs')
self.assertEqual(d[u'齩'], [],
'Variant notes are not definitions')
self.assertEqual(d[u'麵包房'], ['bakery'],
'Measure words should be removed from definitions')
def test_measure_words_correct(self):
d = {}
for ch, chs, pinyin, defs, variants, mw in iter_cedict(self.f):
d[ch] = mw
self.assertEqual(d[u'麵包房'], [(u'家', u'家', u'jia1')],
'This entry should have a measure word')
self.assertEqual(len(d[u'鯰']), 0,
'There is no measure word')
def test_variants_correct(self):
d = {}
for ch, chs, pinyin, defs, variants, mw in iter_cedict(self.f):
d[ch] = variants
class TestPinyin(unittest.TestCase):
def test_syllabize_pinyin(self):
self.assertEqual(syllabize('keneng'),
('ke nen g', 'ke neng', 'ken en g'))
self.assertEqual(syllabize('xi3huan1'),
('xi3 hu an1', 'xi3 huan1'))
self.assertEqual(syllabize('nve4dai4'), ('nv e4 dai4', 'nve4 dai4'))
self.assertEqual(syllabize('dax'), ('da x',))
self.assertEqual(syllabize('nizuij'), ('ni zui j',))
self.assertEqual(syllabize('nizuiji'), ('ni zui ji',))
self.assertEqual(syllabize('xixixiangg'),
('xi xi xi ang g', 'xi xi xiang g'))
self.assertEqual(syllabize('xianbian'), (
'xi an bi a n',
'xi an bi an',
'xi an bian',
'xian bi a n',
'xian bi an',
'xian bian'))
def test_pinyinize(self):
self.assertEqual(pinyinize('ke3neng2'), u'kěnéng')
self.assertEqual(pinyinize('xi3huan1'), u'xǐhuān')
self.assertEqual(pinyinize('xing2 dong4'), u'xíng dòng')
self.assertEqual(pinyinize('ni3 hao3'), u'nǐ hǎo')
self.assertEqual(pinyinize('ni3 hao5'), u'nǐ hao')
self.assertEqual(pinyinize('hua4'), u'huà')
self.assertEqual(pinyinize('you3'), u'yǒu')
# make sure case is preserved
self.assertEqual(pinyinize('xi3HUan1'), u'xǐHUān')
def test_depinyinize(self):
self.assertEqual('ke3neng2', depinyinize(u'kěnéng'))
self.assertEqual('ke3 neng2', depinyinize(u'kě néng'))
self.assertEqual('xi3huan1', depinyinize(u'xǐhuān'))
self.assertEqual('xi3 huan1', depinyinize(u'xǐ huān'))
self.assertEqual('xing2 dong4', depinyinize(u'xíng dòng'))
self.assertEqual('xing2dong4', depinyinize(u'xíngdòng'))
self.assertEqual('ni3 hao3', depinyinize(u'nǐ hǎo'))
self.assertEqual('ni3 hao', depinyinize(u'nǐ hao'))
self.assertEqual('hua4', depinyinize(u'huà'))
self.assertEqual('you3', depinyinize(u'yǒu'))
# make sure case is preserved
self.assertEqual('xi3HUan1', depinyinize(u'xǐHUān'))
def test_double_dot(self):
self.assertEqual(pinyinize('nve4dai4'), u'nüèdài')
self.assertEqual(pinyinize('lu:4fa3'), u'lǜfǎ')
self.assertEqual(pinyinize('lu:4fa3'), u'lǜfǎ')
self.assertEqual(pinyinize('nu:e4dai4'), u'nüèdài')
self.assertEqual(pinyinize('lv4fa3'), u'lǜfǎ')
self.assertEqual('lv4fa3', depinyinize(u'lǜfǎ'))
self.assertEqual(pinyinize('lv4fa3'), u'lǜfǎ')
self.assertEqual('lv4fa3', depinyinize(u'lǜfǎ'))
self.assertEqual(pinyinize('nve4dai4'), u'nüèdài')
self.assertEqual('nve4dai4', depinyinize(u'nüèdài'))
if __name__ == '__main__':
unittest.main()
|
<filename>WinApi++/env_vars.h<gh_stars>0
#pragma once
#include <type_traits>
#include <windows.h>
#include <string>
#include "macros.hpp"
namespace winpp {
namespace env {
namespace detail {
CharFunction(getEnviromentVariable, GetEnvironmentVariableA, GetEnvironmentVariableW);
CharFunction(setEnviromentVariable, SetEnvironmentVariableA, SetEnvironmentVariableW);
template<typename T>
std::basic_string<T> get(const std::basic_string<T>& value) {
const auto requiredSize = call_winapi(getEnviromentVariable<T>(), value.c_str(), nullptr, 0);
auto retValue = std::basic_string<T>(requiredSize, 0);
const auto writtenData = call_winapi(getEnviromentVariable<T>(), value.data(), &retValue[0], requiredSize);
_Assert(writtenData == requiredSize);
return retValue;
}
template<typename T>
void set(const std::basic_string<T>& name, const std::basic_string<T>& key) {
call_winapi(setEnviromentVariable<T>(), name.c_str(), key.c_str());
}
class Vars {
public:
constexpr Vars() {}
std::string operator[](const std::string& value) const {
return get(value);
}
std::wstring operator[](const std::wstring& value) const {
return get(value);
}
void set(const std::wstring& key, const std::wstring& value) const {
winpp::env::detail::set(key, value);
}
void set(const std::string& key, const std::string& value) const {
winpp::env::detail::set(key, value);
}
};
}
constexpr auto vars = detail::Vars {};
}
} |
Mobile communications technologies for young adult learning and skills development (m-learning)
The m-Learning project will develop prototype products to provide information and modules of learning via inexpensive portable technologies which are already owned by, or readily accessible for, the majority of EU young adults. The products seek to attract young adults to learning and assist in the development and achievement of lifelong learning objectives. M-Learning's tat-get audiences are young adults who are not in education or training (including the unemployed), and those who are mobile, casual/temporary/self-employed or in low paid/low skill employment, with literacy or numeracy development needs. |
<filename>demo38/src/main/java/com/wasu/demo38/service/CalculateService.java<gh_stars>1-10
package com.wasu.demo38.service;
public interface CalculateService {
Integer sum(Integer... value);
}
|
She just couldn't see a kid go hungry.
Della Curry, a cafeteria worker in an elementary school in a Denver suburb, has been fired for giving free food to students who didn't qualify for the federal free lunch program.
The mother of two admitted to KCNC-TV, which first reported the story, that she violated school policy by giving the free meals but said that she didn't want to see the children go hungry. She's hoping her case will change district policy.
"I had a first grader in front of me, crying, because she doesn't have enough money for lunch. Yes, I gave her lunch," Curry told the station. "I'll own that I broke the law. The law needs to be changed."
Curry (pictured above) said that many students' families can't afford to send them lunch even if they don't qualify for the free or reduced cost lunch program. She said sometimes students simply forget their lunch money and noted that on occasion she even went into her own pocket to pay for lunches.
Related: Dogs killed over unpaid fines
Cherry Creek School District, where she had been employed, refused to comment to the station about her case, saying it was a personnel matter.
But after the report aired, the district posted a statement on the district web site about the policy without mentioning her by name. It said that students are given free lunches the first three times they forget their lunch money and after that they are given a cheese or if available turkey sandwich, along with a milk.
"No child is ever allowed to go without lunch," said the district's statement.
But Curry said that meal is not enough and leaves kids still hungry.
The district said the cost of the district's lunch program are not covered by the prices charged.
Related: Debt collector doing government dirty work
Curry hopes to speak to the Board of Education about her case and about changing the policy.
"If me getting fired for it is one way that we can try to change this, I'll take it in a heartbeat," she said.
She may have support from some parents at the meeting. Parent Darnell Hill told the station that Curry should be thanked for what she did.
"Do something different than fire her. She's trying to help," he said. |
import * as _ from 'lodash'
import httpClient from '../../src/http'
import config from '../config'
import { symbol } from '../constants'
const client = httpClient(config)
describe('orderbook', () => {
test('orderbook', async () => {
const res = await client.orderBook({
symbol,
})
expect(_.isArray(res.data.SELL)).toBe(true)
expect(_.isArray(res.data.BUY)).toBe(true)
})
test('sellOrderBook', async () => {
const res = await client.sellOrderBook({ symbol })
res.data.forEach(item => {
expect(item.length).toBe(3)
})
})
test('buyOrderBook', async () => {
const res = await client.buyOrderBook({ symbol })
res.data.forEach(item => {
expect(item.length).toBe(3)
})
})
}) |
<gh_stars>0
package unsplash
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
var (
apiPrefix = "https://api.unsplash.com/"
randomPhotoPath = "photos/random"
)
type idGetter interface {
GetToken() (string, error)
}
// API implementation
type API struct {
idGetter idGetter
httpClient *http.Client
}
func NewUnsplashAPI(
idGetter idGetter,
httpClient *http.Client,
) *API {
return &API{
idGetter: idGetter,
httpClient: httpClient,
}
}
type RandomImageURLs struct {
RAW string `json:"raw"`
Full string `json:"full"`
Regular string `json:"regular"`
Small string `json:"small"`
Thumb string `json:"thumb"`
}
type ImageLinks struct {
Self string `json:"self"`
Html string `json:"html"`
Download string `json:"download"`
DownloadLocation string `json:"download_location"`
}
type Image struct {
ID string `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Width int `json:"width"`
Height int `json:"height"`
Description string `json:"description"`
URLs RandomImageURLs `json:"urls"`
Links ImageLinks `json:"links"`
}
type ImageResponse struct {
Data Image
RateLimitRemaining int
}
func (u *API) GetRandomImage(
ctx context.Context,
orientation string,
width string,
height string,
) (*ImageResponse, error) {
token, err := u.idGetter.GetToken()
if err != nil {
return nil, err
}
url := fmt.Sprintf(
"%s%s?orientation=%s&w=%s&h=%s",
apiPrefix,
randomPhotoPath,
orientation,
width,
height,
)
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
request.Header.Set("Authorization", "Client-ID "+token)
response, err := u.httpClient.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
var data interface{}
json.NewDecoder(response.Body).Decode(&data)
return nil, fmt.Errorf("error response status from unsplash: %d. %v", response.StatusCode, data)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
rateLimitRemainingStr := response.Header.Get("X-Ratelimit-Remaining")
rateLimitRemaining, err := strconv.Atoi(rateLimitRemainingStr)
if err != nil {
return nil, err
}
var data Image
if err := json.Unmarshal(body, &data); err != nil {
return nil, err
}
return &ImageResponse{
Data: data,
RateLimitRemaining: rateLimitRemaining,
}, nil
}
|
def ixia_export_buffer_to_file(self, frames_filename):
command = 'captureBuffer export %s' % frames_filename
self.send_expect(command, '%', 30) |
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int calc()
{
ll a,b,c,n;
ll a1,a2,a3;
ll i,j;ll m=0;
cin>>n>>a>>b>>c;
a1=min(a,min(b,c));
a3=max(a,max(b,c));
a2=(a+b+c)-(a1+a3);
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
if(n-i*a1-j*a2>=0)
{
if((n-i*a1-j*a2)%a3==0)
m= max(m,i+j+((n-i*a1-j*a2)/a3));
}
}
}
cout<<m<<endl;
return 0;
}
int main()
{
ll t;
t=1;
while(t--)
calc();
return 0;
} |
/**
* Allows to update register with new events
*/
public class UpdatableEventsRegister extends EventsRegister {
private transient final EventTypeRegister<String> onSendTextRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<ReceiveTextContainer> onReceiveTextRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Player> onPlayerLeftRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Position> onNukeDetectRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitDiscoverRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitEvadeRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitShowRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitHideRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitCreateRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitDestroyRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitMorphRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitRenegadeRegister = new EventTypeRegister<>();
private transient final EventTypeRegister<Unit> onUnitCompleteRegister = new EventTypeRegister<>();
public void saveEvents(int currentFrame) {
onSendTextRegister.batchEventsInFrameToRegister(currentFrame, onSendText);
onReceiveTextRegister.batchEventsInFrameToRegister(currentFrame, onReceiveText);
onPlayerLeftRegister.batchEventsInFrameToRegister(currentFrame, onPlayerLeft);
onNukeDetectRegister.batchEventsInFrameToRegister(currentFrame, onNukeDetect);
onUnitDiscoverRegister.batchEventsInFrameToRegister(currentFrame, onUnitDiscover);
onUnitEvadeRegister.batchEventsInFrameToRegister(currentFrame, onUnitEvade);
onUnitShowRegister.batchEventsInFrameToRegister(currentFrame, onUnitShow);
onUnitHideRegister.batchEventsInFrameToRegister(currentFrame, onUnitHide);
onUnitCreateRegister.batchEventsInFrameToRegister(currentFrame, onUnitCreate);
onUnitDestroyRegister.batchEventsInFrameToRegister(currentFrame, onUnitDestroy);
onUnitMorphRegister.batchEventsInFrameToRegister(currentFrame, onUnitMorph);
onUnitRenegadeRegister.batchEventsInFrameToRegister(currentFrame, onUnitRenegade);
onUnitCompleteRegister.batchEventsInFrameToRegister(currentFrame, onUnitComplete);
}
public void onUnitDiscover(Unit unit) {
onUnitDiscoverRegister.add(unit);
}
public void onUnitEvade(Unit unit) {
onUnitEvadeRegister.add(unit);
}
public void onUnitShow(Unit unit) {
onUnitShowRegister.add(unit);
}
public void onUnitHide(Unit unit) {
onUnitHideRegister.add(unit);
}
public void onUnitCreate(Unit unit) {
onUnitCreateRegister.add(unit);
}
public void onUnitDestroy(Unit unit) {
onUnitDestroyRegister.add(unit);
}
public void onUnitMorph(Unit unit) {
onUnitMorphRegister.add(unit);
}
public void onUnitRenegade(Unit unit) {
onUnitRenegadeRegister.add(unit);
}
public void onUnitComplete(Unit unit) {
onUnitCompleteRegister.add(unit);
}
public void onEnd(int currentFrame, boolean value) {
onEnd.addProperty(value, currentFrame);
}
public void onSendText(String text) {
onSendTextRegister.add(text);
}
public void onReceiveText(Player player, String text) {
onReceiveTextRegister.add(new ReceiveTextContainer(player, text));
}
public void onPlayerLeft(Player player) {
onPlayerLeftRegister.add(player);
}
public void onNukeDetect(Position position) {
onNukeDetectRegister.add(position);
}
} |
def energy_programs():
energy_progs = _programs_with_attribute('ENERGY_READERS')
return energy_progs |
'Tis shortly after midnight in Washington, DC, and at least one person is stirring over at the Federal Communications Commission—the FCC's Jen Howard. She's just sent out the tentative agenda for the agency's December 21 Open Commission meeting, which includes this notable item:
Open Internet Order: An Order adopting basic rules of the road to preserve the open Internet as a platform for innovation, investment, competition, and free expression. These rules would protect consumers' and innovators' right to know basic information about broadband service, right to send and receive lawful Internet traffic, and right to a level playing field, while providing broadband Internet access providers with the flexibility to reasonably manage their networks.
This is, of course, what everybody has been hoping for, or dreading—actual, for-real open Internet rules. The next question is what kind of regulations can we expect? A non-discrimination provision that includes wireless? A transparency rule? Will they be based on Title II limited common carrier language, or will the agency stick to some kind of Title I "information services" regimen, as we've been hearing from various quarters?
Public Knowledge has been staying up late too, and just sent us this press response to the announcement.
"We commend the Federal Communications Commission for tentatively putting open Internet rules on the agenda for the Dec. 21 Commission meeting and for, we expect, circulating a draft order," PK's Gigi Sohn declared. "As Comcast's recent actions have shown, such rules are urgently needed."
That last comment refers to the brouhaha over Comcast's demand for cash to deliver cached Netflix traffic to its subscribers, and its fight with Zoom Telephonics over cable modem testing (we'll have a story on that battle soon).
Also on the FCC agenda for December: a Notice of Inquiry on how to bring texting, photos, and video to 911 services. |
/**
* Make sure to have the following:
*
* 1. Hardware config
* 2. Setup direction of motors
* 3. Action method to do something (hookUpDown, drive, etc.,)
* 4. Helper methods (stop, brake, leftTurn, rightTurn, etc.,)
*
* Purpose: Drive the 4 wheels
*/
public class LinearSlideActions {
public DcMotor slide;
//the amount to throttle the power of the motors
public double THROTTLE = 0.5;
private Telemetry telemetry;
private HardwareMap hardwareMap;
public boolean applySensorSpeed = false;
/**
* Creates a mecanum motor using the 4 individual motors passed in as the arguments
* @param opModeTelemetry : Telemetry to send messages to the Driver Control
* @param opModeHardware : Hardware Mappings
*/
// Constructor
public LinearSlideActions(Telemetry opModeTelemetry, HardwareMap opModeHardware ) {
this.telemetry = opModeTelemetry;
this.hardwareMap = opModeHardware;
// 1. Hardware config
slide = hardwareMap.get(DcMotor.class, ConfigConstants.ARM);
// 2. Set direction
setMotorDirection_Down();
}
public void setSpeed(double mySpeed){
THROTTLE = mySpeed;
}
/**
* Drive method to throttle the power
* @param speedX - the x value of the joystick controlling strafe
* @param speedY - the y value of the joystick controlling the forward/backward motion
* @param rotation - the x value of the joystick controlling the rotation
*/
public void drive(double speedX, double speedY, double rotation){
double throttledX = speedX * THROTTLE;
double throttledY = speedY * THROTTLE;
double throttledRotation = rotation * THROTTLE;
driveUsingJoyStick(throttledX, throttledY, throttledRotation);
}
/**
* This function makes the mecanum motor drive using the joystick
* @param speedX - the x value of the joystick controlling strafe
* @param speedY - the y value of the joystick controlling the forward/backwards motion
* @param rotation - the x value of the joystick controlling the rotation
*/
public void driveUsingJoyStick(double speedX, double speedY, double rotation) {
double backLeftValue = -speedX + speedY + rotation;
double frontLeftValue = speedX + speedY + rotation;
double backRightValue = speedX + speedY - rotation;
double frontRightValue = -speedX + speedY - rotation;
double max = getMaxPower(frontLeftValue, frontRightValue, backLeftValue, backRightValue);
if (max > 1) {
frontLeftValue = frontLeftValue / max;
frontRightValue = frontRightValue / max;
backLeftValue = backLeftValue / max;
backRightValue = backRightValue / max;
}
slide.setPower(frontLeftValue);
}
private double getMaxPower(double frontLeftValue, double frontRightValue, double backLeftValue, double backRightValue) {
List<Double> valueList = new LinkedList<>();
valueList.add(frontLeftValue);
valueList.add(frontRightValue);
valueList.add(backLeftValue);
valueList.add(backRightValue);
return Collections.max(valueList);
}
public void setMotorDirection_Down() {
slide.setDirection(MotorConstants.REVERSE);
}
public void setMotorDirection_Up() {
slide.setDirection(MotorConstants.FORWARD);
}
public void stop() {
slide.setPower(0);
}
public void applyBrake() {
slide.setZeroPowerBehavior(MotorConstants.BRAKE);
}
public void driveByTime(LinearOpMode opMode, double speed, double drivingTime) {
slide.setPower(speed); //Speed needed for hooks (this is our normal speed)
opMode.sleep((long) (1000 * drivingTime));
}
/**
* Method to drive a specified distance using motor encoder functionality
*
* @param inches - The Number Of Inches to Move
* @param direction - The Direction to Move
* - Valid Directions:
* - MecanumDrivetrain.DIRECTION_FORWARD
* - MecanumDrivetrain.DIRECTION_REVERSE
* - MecanumDrivetrain.DIRECTION_STRAFE_LEFT
* - MecanumDrivetrain.DIRECTION_STRAFE_RIGHT
* @param speed - The desired motor power (most accurate at low powers < 0.25)
*/
public void driveByInches(int inches, int direction, double speed){
setMotorDirection(direction);
driveByRevolution(convertDistanceToTarget(inches, direction) * 3, speed);
}
/**
* Method will motors a specified number of revolutions at the desired power
* agnostic of direction.
*
* @param revolutions - the number of motor encoder ticks to move
* @param power - the speed at which to move
*/
private void driveByRevolution(int revolutions, double power){
slide.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
slide.setTargetPosition(revolutions);
slide.setMode(DcMotor.RunMode.RUN_TO_POSITION);
slide.setPower(power);
telemetry.addData("Current Position: ",
"slide: ", slide.getCurrentPosition());
telemetry.update();
}
//NOT TESTED
private int convertDistanceToTarget(int inches, int direction){
float target;
if (direction == MotorConstants.DIRECTION_FORWARD
|| direction == MotorConstants.DIRECTION_REVERSE){
target = inches * MotorConstants.ENCODER_CLICKS_FORWARD_1_INCH;
} else{
target = inches * MotorConstants.ENCODER_CLICKS_STRAFE_1_INCH;
}
return Math.round(target);
}
/**
* Returns true if the robot is moving
*/
public boolean isMoving() {
return slide.isBusy();
}
//NOT TESTED
private void setMotorDirection(int direction){
if (direction == MotorConstants.DIRECTION_REVERSE){
setMotorDirection_Up();
} else {
setMotorDirection_Down();
}
}
} |
<filename>src/stackoverflow/57970016/loadmythings_1.ts
import * as api from './api';
export class loadmythings_1 {
loadmythings = async () => {
const list = await api.getmythings('arg1', 'arg2');
const finalvalues: any[] = [];
list.map((item) => finalvalues.push({ value: item.name }));
return finalvalues;
};
}
|
package httpclient
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
neturl "net/url"
"strings"
)
// compile time check
var _ BaseURLAwareClient = Client{}
// BaseURLAwareClient is a http client that can build requests not from a full URL, but from a path relative to a configured base url
// this is useful for REST-APIs that always connect to the same host, but on different paths
type BaseURLAwareClient interface {
NewRequest(method, path string, body interface{}) (*http.Request, *Error)
Do(req *http.Request, result interface{}) (*http.Response, *[]byte, *Error)
}
type Client struct {
baseURL *neturl.URL
httpClient *http.Client
}
// NewHTTPClient creates a new client and ensures that the given baseURL ends with a trailing '/'.
// The trailing '/' is required later for constructing the full URL using a relative path.
func NewHTTPClient(baseURL string, client *http.Client) (*Client, error) {
url, err := neturl.Parse(baseURL)
// add trailing '/' to the url path, so that we can combine the url with other paths according to standards
if !strings.HasSuffix(url.Path, "/") {
url.Path = url.Path + "/"
}
if err != nil {
return nil, err
}
return &Client{
httpClient: client,
baseURL: url,
}, nil
}
func (c *Client) GetHTTPClient() *http.Client {
return c.httpClient
}
func (c Client) NewRequest(method, path string, body interface{}) (*http.Request, *Error) {
var jsonBody io.ReadWriter
if body != nil {
jsonBody = new(bytes.Buffer)
if err := json.NewEncoder(jsonBody).Encode(body); err != nil {
return nil, NewError(err)
}
}
pu, err := neturl.Parse(path)
if err != nil {
return nil, NewError(err)
}
u := resolveReferenceAsRelative(c.baseURL, pu)
req, err := http.NewRequest(method, u.String(), jsonBody)
if err != nil {
return nil, NewError(err)
}
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
}
func resolveReferenceAsRelative(base, ref *neturl.URL) *neturl.URL {
return base.ResolveReference(&neturl.URL{Path: strings.TrimPrefix(ref.Path, "/")})
}
func (c Client) Do(req *http.Request, result interface{}) (*http.Response, *[]byte, *Error) {
resp, err := c.httpClient.Do(req)
if err != nil {
if resp == nil {
return resp, nil, NewError(err)
}
return resp, nil, NewError(err, WithStatusCode(resp.StatusCode))
}
defer func() { _ = resp.Body.Close() }()
defer c.httpClient.CloseIdleConnections()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp, nil, NewError(err, WithStatusCode(resp.StatusCode))
}
if len(body) == 0 {
return resp, nil, nil
}
if err := json.Unmarshal(body, result); err != nil {
return resp, nil, NewError(err, WithStatusCode(resp.StatusCode), WithMessage(string(body)))
}
return resp, &body, nil
}
|
// Use this to set the type of encoding that you want - e.g. JSON, protobuf, etc
void InputStreamInterface::SetInputDecoding(const jude_decode_transport_t* transport)
{
jude_istream_create(
&m_istream,
transport,
ReadCallback,
this,
(char*)m_istream.buffer.m_data,
m_istream.buffer.m_capacity);
} |
/**
* Market data manager class to allow save or update and load operations on MarketDataSets.
*/
public class MarketDataManager {
/** The logger. */
/* package */ static final Logger LOGGER = LoggerFactory.getLogger(MarketDataManager.class);
/** The default observation time */
private static final String DEFAULT_OBSERVATION_TIME = "DEFAULT";
/** The value requirement names that indicate that a time series has been requested */
private static final Set<String> TIME_SERIES_REQUIREMENT_NAMES = new HashSet<>();
static {
TIME_SERIES_REQUIREMENT_NAMES.add(ValueRequirementNames.HISTORICAL_TIME_SERIES);
TIME_SERIES_REQUIREMENT_NAMES.add(ValueRequirementNames.HISTORICAL_TIME_SERIES_LATEST);
TIME_SERIES_REQUIREMENT_NAMES.add(ValueRequirementNames.HISTORICAL_FX_TIME_SERIES);
}
/** The time series master */
private final HistoricalTimeSeriesMaster _htsMaster;
/** The security source */
private final SecuritySource _secSource;
/** The view processor */
private final ViewProcessor _viewProcessor;
/** The historical time series resolver */
private final HistoricalTimeSeriesResolver _htsResolver;
/** The config source */
private final ConfigSource _configSource;
/**
* Public constructor to create an instance of the market data manager.
* @param htsMaster a historical time series master, not null
* @param secSource a security source, not null
* @param htsResolver a historical time series resolver, not null
* @param configSource a config source, not null
* @param viewProcessor a view processor, not null
*/
public MarketDataManager(final HistoricalTimeSeriesMaster htsMaster, final SecuritySource secSource, final HistoricalTimeSeriesResolver htsResolver,
final ConfigSource configSource, final ViewProcessor viewProcessor) {
_htsMaster = ArgumentChecker.notNull(htsMaster, "htsMaster");
_secSource = ArgumentChecker.notNull(secSource, "secSource");
_htsResolver = ArgumentChecker.notNull(htsResolver, "htsResolver");
_configSource = ArgumentChecker.notNull(configSource, "configSource");
_viewProcessor = ArgumentChecker.notNull(viewProcessor, "viewProcessor");
}
/**
* Public constructor to create an instance of a market data manager.
* @param toolContext the tool context
*/
public MarketDataManager(final ToolContext toolContext) {
this(ArgumentChecker.notNull(toolContext, "toolContext").getHistoricalTimeSeriesMaster(),
toolContext.getSecuritySource(),
toolContext.getHistoricalTimeSeriesResolver(),
toolContext.getConfigSource(),
toolContext.getViewProcessor());
}
/**
* Save or update the provided market data set on the provided date.
* @param marketDataSet the set of market data to save or update
* @param date the date on which to save the data
*/
public void saveOrUpdate(final MarketDataSet marketDataSet, final LocalDate date) {
final HistoricalTimeSeriesMasterUtils masterUtils = new HistoricalTimeSeriesMasterUtils(_htsMaster);
for (final Map.Entry<MarketDataKey, Object> entry : marketDataSet.entrySet()) {
final MarketDataKey marketDataKey = entry.getKey();
if (entry.getValue() instanceof Double) {
masterUtils.writeTimeSeriesPoint(marketDataKey.getExternalIdBundle().toString(), marketDataKey.getSource().getName(),
marketDataKey.getProvider().getName(),
marketDataKey.getField().getName(),
DEFAULT_OBSERVATION_TIME,
marketDataKey.getExternalIdBundle(),
date,
(Double) entry.getValue());
} else if (entry.getValue() instanceof LocalDateDoubleTimeSeries) {
masterUtils.writeTimeSeries(marketDataKey.getExternalIdBundle().toString(), marketDataKey.getSource().getName(),
marketDataKey.getProvider().getName(),
marketDataKey.getField().getName(),
DEFAULT_OBSERVATION_TIME,
marketDataKey.getExternalIdBundle(),
(LocalDateDoubleTimeSeries) entry.getValue());
} else {
LOGGER.warn("Object to save or update {} was not a value or time series; ignoring", entry.getValue());
}
}
}
/**
* Listens for the result and pipes it back.
*/
private class CompileResultListener extends AbstractViewResultListener {
/** The queue */
private final SynchronousQueue<CompiledViewDefinition> _queue;
/**
* @param queue the queue
*/
public CompileResultListener(final SynchronousQueue<CompiledViewDefinition> queue) {
_queue = queue;
}
@Override
public UserPrincipal getUser() {
return UserPrincipal.getLocalUser();
}
@Override
public void viewDefinitionCompiled(final CompiledViewDefinition compiledViewDefinition, final boolean hasMarketDataPermissions) {
try {
_queue.put(compiledViewDefinition);
} catch (final InterruptedException e) {
LOGGER.error("View compilation queue interrupted", e);
}
}
@Override
public void viewDefinitionCompilationFailed(final Instant valuationTime, final Exception exception) {
try {
LOGGER.error("View compilation failed", exception);
_queue.put(null);
} catch (final InterruptedException e) {
LOGGER.error("View compilation queue interrupted", e);
}
}
}
/**
* Determine the required market data for a given view at a given valuation time.
* @param viewKey the key for the view, not null
* @param valuationTime the valuation time, which may influence market data requirements, not null
* @return the market data information
*/
public MarketDataInfo getRequiredDataForView(final ViewKey viewKey, final Instant valuationTime) {
ArgumentChecker.notNull(viewKey, "viewKey");
ArgumentChecker.notNull(valuationTime, "valuationTime");
final ViewClient viewClient = _viewProcessor.createViewClient(UserPrincipal.getLocalUser());
viewClient.setResultMode(ViewResultMode.FULL_ONLY);
final List<MarketDataSpecification> marketDataSpecificationList = Collections.<MarketDataSpecification>singletonList(AlwaysAvailableMarketDataSpecification.builder().build());
final UniqueId viewDefId = ensureConfig(viewKey.getName());
final ExecutionFlags flags = ExecutionFlags.none().fetchMarketDataOnly().compileOnly().runAsFastAsPossible();
final SynchronousQueue<CompiledViewDefinition> queue = new SynchronousQueue<>();
viewClient.setResultListener(new CompileResultListener(queue));
viewClient.attachToViewProcess(viewDefId, ExecutionOptions.singleCycle(valuationTime, marketDataSpecificationList, flags.get()));
final MarketDataInfo marketDataInfo = MarketDataInfo.empty();
final LocalDate valuationDate = ZonedDateTime.ofInstant(valuationTime, ZoneOffset.UTC).toLocalDate();
try {
final CompiledViewDefinition compiledViewDefinition = queue.take(); // wait for listener to get called back
for (final ValueSpecification valueSpecification : compiledViewDefinition.getMarketDataRequirements()) {
final ComputationTargetType targetType = valueSpecification.getTargetSpecification().getType();
if (targetType == ComputationTargetType.SECURITY) {
final Security security = _secSource.get(valueSpecification.getTargetSpecification().getUniqueId());
final ExternalIdBundle bundle = security.getExternalIdBundle();
final MarketDataKey marketDataKey = MarketDataKey.of(bundle, DataField.of(valueSpecification.getValueName()));
// don't care if a point is requested twice
marketDataInfo.addScalarInfo(marketDataKey, ScalarMarketDataMetaData.INSTANCE);
} else if (targetType == ComputationTargetType.PRIMITIVE) {
final ExternalIdBundle bundle = PrimitiveResolver.resolveExternalIds(valueSpecification.getTargetSpecification().getUniqueId(), PrimitiveResolver.SCHEME_PREFIX);
if (bundle == null) {
LOGGER.error("Could not resolve {} ignoring", valueSpecification.getTargetSpecification().getUniqueId());
} else {
final MarketDataKey marketDataKey = MarketDataKey.of(bundle, DataField.of(valueSpecification.getValueName()));
marketDataInfo.addScalarInfo(marketDataKey, ScalarMarketDataMetaData.INSTANCE);
}
}
}
if (compiledViewDefinition instanceof CompiledViewDefinitionWithGraphs) {
final CompiledViewDefinitionWithGraphs withGraphs = (CompiledViewDefinitionWithGraphs) compiledViewDefinition;
for (final DependencyGraphExplorer explorer : withGraphs.getDependencyGraphExplorers()) {
for (int i = 0; i < explorer.getWholeGraph().getRootCount(); i++) {
final DependencyNode rootNode = explorer.getWholeGraph().getRootNode(i);
getHistoricalTimeSeriesRequirements(_htsMaster, rootNode, marketDataInfo, valuationDate);
}
}
}
return marketDataInfo;
} catch (final InterruptedException ie) {
throw new OpenGammaRuntimeException("View Compilation interrupted while waiting: " + ie.getMessage());
}
}
/**
* Crawls the graph looking for nodes referencing one of the value requirement names indicating that a time series has been requested.
* This is not yet exhaustive - some functions call into the time series source every time execute() is called and should be rewritten.
* @param htsMaster the time series master
* @param node a graph node
* @param marketDataInfo known market data requirements
* @param valuationDate the valuation date
*/
private void getHistoricalTimeSeriesRequirements(final HistoricalTimeSeriesMaster htsMaster, final DependencyNode node, final MarketDataInfo marketDataInfo, final LocalDate valuationDate) {
if (node.getInputCount() == 0 && node.getTarget().getType() == ComputationTargetType.PRIMITIVE && TIME_SERIES_REQUIREMENT_NAMES.contains(node.getOutputValue(0).getValueName())) {
final ValueSpecification spec = node.getOutputValue(0);
final TimeSeriesMarketDataMetaData metaData = createTimeSeriesMetaData(spec.getProperties(), valuationDate);
final UniqueId tsUid = spec.getTargetSpecification().getUniqueId();
try {
final HistoricalTimeSeriesInfoDocument tsInfoDocument = htsMaster.get(tsUid);
if (tsInfoDocument != null) {
final ManageableHistoricalTimeSeriesInfo info = tsInfoDocument.getInfo();
final ExternalIdBundle bundle = info.getExternalIdBundle().toBundle();
final MarketDataKey key = MarketDataKey.builder().externalIdBundle(bundle).field(DataField.of(info.getDataField())).source(DataSource.of(info.getDataSource()))
.provider(DataProvider.of(info.getDataProvider())).build();
marketDataInfo.addTimeSeriesInfo(key, metaData);
return;
}
} catch (final DataNotFoundException e) {
}
// if the code reaches here, could not get time series from database
if (_htsResolver instanceof AlwaysAvailableHistoricalTimeSeriesResolver) {
final AlwaysAvailableHistoricalTimeSeriesResolver resolver = (AlwaysAvailableHistoricalTimeSeriesResolver) _htsResolver;
final ManageableHistoricalTimeSeriesInfo info = resolver.getMissingTimeSeriesInfoForUniqueId(tsUid);
final ExternalIdBundle bundle = info.getExternalIdBundle().toBundle();
final DataSource source = info.getDataSource() == null ? DataSource.DEFAULT : DataSource.of(info.getDataSource());
final DataProvider provider = info.getDataProvider() == null ? DataProvider.DEFAULT : DataProvider.of(info.getDataProvider());
final MarketDataKey key = MarketDataKey.builder().externalIdBundle(bundle).field(DataField.of(info.getDataField())).source(source)
.provider(provider).build();
marketDataInfo.addTimeSeriesInfo(key, metaData);
return;
}
LOGGER.warn("Time series with id {} not available from master and could not get ExternalIdBundle from UniqueId", tsUid);
}
for (int i = 0; i < node.getInputCount(); i++) {
final DependencyNode child = node.getInputNode(i);
getHistoricalTimeSeriesRequirements(htsMaster, child, marketDataInfo, valuationDate);
}
}
/**
* Creates the meta data object from the properties of a time series requirement.
* @param properties the properties
* @param valuationDate the valuation date
* @return the meta data
*/
private static TimeSeriesMarketDataMetaData createTimeSeriesMetaData(final ValueProperties properties, final LocalDate valuationDate) {
final TimeSeriesMarketDataMetaData.Builder builder = TimeSeriesMarketDataMetaData.builder();
builder.type(LocalDateDoubleTimeSeries.class); //TODO is this right
if (properties.isDefined(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY)) {
builder.adjust(properties.getSingleValue(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY));
}
if (properties.isDefined(HistoricalTimeSeriesFunctionUtils.AGE_LIMIT_PROPERTY)) {
builder.ageLimit(properties.getSingleValue(HistoricalTimeSeriesFunctionUtils.AGE_LIMIT_PROPERTY));
}
if (properties.isDefined(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY)) {
// note that the date constraint can be -P7D, so the result from the properties must be evaluated to a date
builder.startDate(DateConstraint.evaluate(valuationDate, properties.getSingleValue(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY)));
}
if (properties.isDefined(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY)) {
final String includeStart = properties.getSingleValue(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY);
builder.includeStart(includeStart.equals(HistoricalTimeSeriesFunctionUtils.YES_VALUE));
}
if (properties.isDefined(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY)) {
// note that the date constraint can be -P7D, so the result from the properties must be evaluated to a date
builder.endDate(DateConstraint.evaluate(valuationDate, properties.getSingleValue(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY)));
}
if (properties.isDefined(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY)) {
final String includeEnd = properties.getSingleValue(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY);
builder.includeEnd(includeEnd.equals(HistoricalTimeSeriesFunctionUtils.YES_VALUE));
}
return builder.build();
}
/**
* Checks that the view is available from the source.
* @param viewName the view name
* @return the unique id of the view
*/
private UniqueId ensureConfig(final String viewName) {
final ViewDefinition viewDef = _configSource.getSingle(ViewDefinition.class, viewName, VersionCorrection.LATEST);
if (viewDef == null) {
throw new OpenGammaRuntimeException("Could not get view definition called " + viewName + " from config source");
}
return viewDef.getUniqueId();
}
} |
Electrostatically Doped DSL Schottky Barrier MOSFET on SOI for Low Power Applications
In this paper, we propose and simulate a novel Schottky barrier MOSFET (SB-MOSFET) with improved performance in comparison to the conventional SB-MOSFET. The proposed device employs charge plasma/electrostatic doping-based dopant segregation layers (DSLs) by using metal extensions (Hafnium) at the source and drain top and bottom edges. The metal hafnium induces charge plasma and hence realizes DSLs adjacent to source and drain regions. These charge plasma DSLs reduce the tunneling width and hence enhances the performance of the proposed device. The proposed electrostatically doped DSL-based SB-MOSFET has all the advantages of the conventional SB-MOSFET and it outperforms the state of the art doped DSL-based MOSFET. A two-dimensional calibrated simulation study has shown that the ON current <inline-formula> <tex-math notation="LaTeX">$(I_{\mathrm{ ON}})$ </tex-math></inline-formula>, <inline-formula> <tex-math notation="LaTeX">$I_{\mathrm{ ON}}/I_{\mathrm{ OFF}}$ </tex-math></inline-formula> ratio, subthreshold-swing and cutoff frequency <inline-formula> <tex-math notation="LaTeX">$(f_{T})$ </tex-math></inline-formula> of the proposed device have been increased by ~420 times, ~1000 times, 14.5%, and 290 times in comparison to conventional SB-MOSFET, respectively. The transient analyses have shown that a reduction by 16 times in ON delay and 6 times in OFF delay in the proposed device-based inerter in comparison to the conventional SB-MOSFET-based inverter. |
// requested can only transition to responded state
func TestRequestedState(t *testing.T) {
requested := &requested{}
require.Equal(t, "requested", requested.Name())
require.False(t, requested.CanTransitionTo(&null{}))
require.False(t, requested.CanTransitionTo(&invited{}))
require.False(t, requested.CanTransitionTo(requested))
require.True(t, requested.CanTransitionTo(&responded{}))
require.False(t, requested.CanTransitionTo(&completed{}))
} |
/**
* Handles Binary XML parsing callback and generate XML. You can use your
* own XML generator and register with Android_BX2 (Android Binary XML) parser.
*
* @author prasanta
*
*/
public class GenXML implements BXCallback {
StringBuffer xml = new StringBuffer();
// Current line number
int cl = 1;
Node currentNode = null;
String xmlFile;
String tag = getClass().getSimpleName();
public void startDoc(String xmlFile)
{
this.xmlFile = xmlFile;
// TODO: Encoding value
xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
}
public void startNode(Node node) {
// TODO Auto-generated method stub
if(node == null)
return;
currentNode = node;
Log.d(tag, "[GenXML] Node LN: "+ node.getLinenumber() +" CL: "+ cl);
if(cl == node.getLinenumber()){
// TODO: Remove this case. Only for temp fix.
// FIX line number problem.
xml.append("\n");
}
else {
while(cl < node.getLinenumber()){
// Next line
ln();
}
}
xml.append("<"+ node.getName());
if(node.getIndex() == Node.ROOT){
// Add name space value
xml.append(" xmlns:"+ node.getNamespacePrefix() +"=\""+ node.getNamespaceURI() +"\"");
}
ArrayList<Attribute> attrs = node.getAttrs();
Log.d(tag, "[GenXML] Number of Attributes "+ attrs.size());
if(attrs.size() == 0){
// Attributes
xml.append(">");
ln();
return;
}
for(int i=0; i<attrs.size(); i++){
Attribute attr = attrs.get(i);
// next line. All attributes in different line
ln();
xml.append(" "+ attr.getName() +"=\""+ attr.getValue() +"\"");
}
xml.append(">");
}
public void nodeValue(int lineNumber, String name, String value) {
// TODO: handle Node value
}
public void endNode(Node node) {
// TODO: Remove this case. Only for temp fix.
// FIX line number problem.
if(cl == node.getLinenumber())
xml.append("\n");
else if(cl < node.getLinenumber())
ln();
// TODO Auto-generated method stub
if(currentNode.getName().equals(node.getName()))
{
// Add end tag "/>". Remove ">" and add "/>"
//xml = xml.delete(xml.length() - 1, xml.length());
int index = xml.lastIndexOf("\"");
if(index != -1){
xml.delete(index + 1, xml.length());
xml.append("/>");
}
else{
xml.append("</"+ node.getName() +">");
}
}
else{
// there are child nodes
xml.append("</"+ node.getName() +">");
}
}
public void endDoc() throws Exception {
// Generate the XML
FileOutputStream out = new FileOutputStream(xmlFile +".xml");
out.write(xml.toString().getBytes());
out.flush();
out.close();
}
private void ln(){
cl++;
xml.append("\n");
}
} |
/**
* Transform template html and css into executable code.
* Intended to be used in a build step.
*/
import * as ts from 'typescript';
import * as path from 'path';
import {AngularCompilerOptions} from '@angular/tsc-wrapped';
import * as compiler from '@angular/compiler';
import {ViewEncapsulation} from '@angular/core';
import {StaticReflector} from './static_reflector';
import {
CompileMetadataResolver,
HtmlParser,
DirectiveNormalizer,
Lexer,
Parser,
TemplateParser,
DomElementSchemaRegistry,
StyleCompiler,
ViewCompiler,
TypeScriptEmitter
} from './compiler_private';
import {Parse5DomAdapter} from '@angular/platform-server';
import {NodeReflectorHost} from './reflector_host';
import {StaticAndDynamicReflectionCapabilities} from './static_reflection_capabilities';
const GENERATED_FILES = /\.ngfactory\.ts$|\.css\.ts$|\.css\.shim\.ts$/;
const PREAMBLE = `/**
* This file is generated by the Angular 2 template compiler.
* Do not edit.
*/
/* tslint:disable */
`;
export class CodeGenerator {
constructor(private options: AngularCompilerOptions,
private program: ts.Program, public host: ts.CompilerHost,
private staticReflector: StaticReflector, private resolver: CompileMetadataResolver,
private compiler: compiler.OfflineCompiler,
private reflectorHost: NodeReflectorHost) {}
private generateSource(metadatas: compiler.CompileDirectiveMetadata[]) {
const normalize = (metadata: compiler.CompileDirectiveMetadata) => {
const directiveType = metadata.type.runtime;
const directives = this.resolver.getViewDirectivesMetadata(directiveType);
return Promise.all(directives.map(d => this.compiler.normalizeDirectiveMetadata(d)))
.then(normalizedDirectives => {
const pipes = this.resolver.getViewPipesMetadata(directiveType);
return new compiler.NormalizedComponentWithViewDirectives(metadata,
normalizedDirectives, pipes);
});
};
return Promise.all(metadatas.map(normalize))
.then(normalizedCompWithDirectives =>
this.compiler.compileTemplates(normalizedCompWithDirectives));
}
private readComponents(absSourcePath: string) {
const result: Promise<compiler.CompileDirectiveMetadata>[] = [];
const moduleMetadata = this.staticReflector.getModuleMetadata(absSourcePath);
if (!moduleMetadata) {
console.log(`WARNING: no metadata found for ${absSourcePath}`);
return result;
}
const metadata = moduleMetadata['metadata'];
const symbols = metadata && Object.keys(metadata);
if (!symbols || !symbols.length) {
return result;
}
for (const symbol of symbols) {
if (metadata[symbol] && metadata[symbol].__symbolic == 'error') {
// Ignore symbols that are only included to record error information.
continue;
}
const staticType = this.reflectorHost.findDeclaration(absSourcePath, symbol, absSourcePath);
let directive: compiler.CompileDirectiveMetadata;
directive = this.resolver.maybeGetDirectiveMetadata(<any>staticType);
if (!directive || !directive.isComponent) {
continue;
}
result.push(this.compiler.normalizeDirectiveMetadata(directive));
}
return result;
}
// Write codegen in a directory structure matching the sources.
private calculateEmitPath(filePath: string) {
let root = this.options.basePath;
for (let eachRootDir of this.options.rootDirs || []) {
if (this.options.trace) {
console.log(`Check if ${filePath} is under rootDirs element ${eachRootDir}`);
}
if (path.relative(eachRootDir, filePath).indexOf('.') !== 0) {
root = eachRootDir;
}
}
return path.join(this.options.genDir, path.relative(root, filePath));
}
// TODO(tbosch): add a cache for shared css files
// TODO(tbosch): detect cycles!
private generateStylesheet(filepath: string, shim: boolean): Promise<any> {
return this.compiler.loadAndCompileStylesheet(filepath, shim, '.ts')
.then((sourceWithImports) => {
const emitPath = this.calculateEmitPath(sourceWithImports.source.moduleUrl);
// TODO(alexeagle): should include the sourceFile to the WriteFileCallback
this.host.writeFile(emitPath, PREAMBLE + sourceWithImports.source.source, false);
return Promise.all(
sourceWithImports.importedUrls.map(url => this.generateStylesheet(url, shim)));
});
}
codegen(): Promise<any> {
Parse5DomAdapter.makeCurrent();
let stylesheetPromises: Promise<any>[] = [];
const generateOneFile = (absSourcePath: string) =>
Promise.all(this.readComponents(absSourcePath))
.then((metadatas: compiler.CompileDirectiveMetadata[]) => {
if (!metadatas || !metadatas.length) {
return;
}
metadatas.forEach((metadata) => {
let stylesheetPaths = metadata && metadata.template && metadata.template.styleUrls;
if (stylesheetPaths) {
stylesheetPaths.forEach((path) => {
stylesheetPromises.push(this.generateStylesheet(
path, metadata.template.encapsulation === ViewEncapsulation.Emulated));
});
}
});
return this.generateSource(metadatas);
})
.then(generated => {
if (generated) {
const sourceFile = this.program.getSourceFile(absSourcePath);
const emitPath = this.calculateEmitPath(generated.moduleUrl);
this.host.writeFile(emitPath, PREAMBLE + generated.source, false, () => {},
[sourceFile]);
}
})
.catch((e) => { console.error(e.stack); });
var compPromises = this.program.getSourceFiles()
.map(sf => sf.fileName)
.filter(f => !GENERATED_FILES.test(f))
.map(generateOneFile);
return Promise.all(stylesheetPromises.concat(compPromises));
}
static create(options: AngularCompilerOptions, program: ts.Program,
compilerHost: ts.CompilerHost): CodeGenerator {
const xhr: compiler.XHR = {get: (s: string) => Promise.resolve(compilerHost.readFile(s))};
const urlResolver: compiler.UrlResolver = compiler.createOfflineCompileUrlResolver();
const reflectorHost = new NodeReflectorHost(program, compilerHost, options);
const staticReflector = new StaticReflector(reflectorHost);
StaticAndDynamicReflectionCapabilities.install(staticReflector);
const htmlParser = new HtmlParser();
const config = new compiler.CompilerConfig(true, true, true);
const normalizer = new DirectiveNormalizer(xhr, urlResolver, htmlParser, config);
const parser = new Parser(new Lexer());
const tmplParser = new TemplateParser(parser, new DomElementSchemaRegistry(), htmlParser,
/*console*/ null, []);
const offlineCompiler = new compiler.OfflineCompiler(
normalizer, tmplParser, new StyleCompiler(urlResolver),
new ViewCompiler(new compiler.CompilerConfig(true, true, true)),
new TypeScriptEmitter(reflectorHost), xhr);
const resolver = new CompileMetadataResolver(
new compiler.DirectiveResolver(staticReflector), new compiler.PipeResolver(staticReflector),
new compiler.ViewResolver(staticReflector), null, null, staticReflector);
return new CodeGenerator(options, program, compilerHost, staticReflector, resolver,
offlineCompiler, reflectorHost);
}
}
|
def first(self, connection: ldap3.Connection=None, convert=True) -> Any:
entry = next(self._query(connection), None)
if convert is True and self.model is not None:
return self.model.from_entry(entry)
return entry |
// ReadEvent returns one event. This call blocks until an event is received.
func (o *Observer) ReadEvent() (Event, error) {
select {
case <-o.close:
return nil, nil
case event := <-o.events:
return event, nil
}
} |
Should Medical Assistance in Dying Be Extended to Incompetent Patients With Dementia? Research Protocol of a Survey Among Four Groups of Stakeholders From Quebec, Canada
Background: Alzheimer’s disease and related disorders affect a growing number of people worldwide. Quality of life is generally good in the early stages of these diseases. However, many individuals fear living through the advanced stages. Such fears are triggering requests for medical assistance in dying (MAiD) by patients with dementia. Legislation was recently passed in Canada and the province of Quebec allowing MAiD at the explicit request of a patient who meets a set of eligibility criteria, including competence. Some commentators have argued that MAiD should be accessible to incompetent patients as well, provided appropriate safeguards are in place. Governments of both Quebec and Canada are currently considering whether MAiD should be accessible through written requests made in advance of loss of capacity. Objective: Aimed at informing the societal debate on this sensitive issue, this study will compare stakeholders’ attitudes towards expanding MAiD to incompetent patients with dementia, the beliefs underlying stakeholders’ attitudes on this issue, and the value they attach to proposed safeguards. This paper describes the study protocol. Methods: Data will be collected via a questionnaire mailed to random samples of community-dwelling seniors, relatives of persons with dementia, physicians, and nurses, all residing in Quebec (targeted sample size of 385 per group). Participants will be recruited through the provincial health insurance database, Alzheimer Societies, and professional associations. Attitudes towards MAiD for incompetent patients with dementia will be elicited through clinical vignettes featuring a patient with Alzheimer’s disease for whom MAiD is considered towards the end of the disease trajectory. Vignettes specify the source of the request (from the patient through an advance request or from the patient’s substitute decision-maker), manifestations of suffering, and how close the patient is to death. Arguments for or against MAiD are used to elicit the beliefs underlying respondents’ attitudes. JMIR Res Protoc 2017 | vol. 6 | iss. 11 | e208 | p.1 http://www.researchprotocols.org/2017/11/e208/ (page number not for citation purposes) Bravo et al JMIR RESEARCH PROTOCOLS
Introduction
Medicine aims to relieve patient suffering and cure illness . When patients can no longer be cured, palliative care aims to improve quality of life by relieving suffering . Palliative care has expanded over the past decades, although accessibility gaps remain, notably for patients with Alzheimer's disease and related disorders whose illnesses are still too often not recognized as terminal . Moreover, despite quality palliative care, some patients (with and without dementia) experience treatment-refractory symptoms that may lead to medical assistance in dying (MAiD) requests as a last resort to alleviate suffering . Whether MAiD should be accessible to incompetent patients with dementia raises complex ethical and practical issues. We designed a study to investigate the views of stakeholders on these issues in Quebec, Canada. In this paper, we summarize current knowledge on these issues, state the objectives of our study, describe its methodology, and discuss its strengths and limitations.
Legal Landscape on MAiD Internationally in Canada, and in Quebec
Outside of Canada, euthanasia and/or physician-assisted suicide have now been legalized in four countries (The Netherlands, Belgium, Luxemburg, and Colombia), four US states (Oregon, Washington, Vermont, and California) and the District of Columbia. In the scientific literature, euthanasia commonly refers to, "the administration of drugs with the explicit intention of ending the patient's life at his or her explicit request" and physician-assisted suicide refers to, "the prescription or supply of drugs with the explicit intention of enabling the patient to end his or her own life" . An explicit request can be made contemporaneously or previously (ie, in advance of incapacity). Physician-assisted suicide is also allowed by operation of a court decision in Montana. In Switzerland, euthanasia is illegal but assisted suicide (whether by a physician or nonphysician) is only prohibited when done for a "selfish motive" . Between 0.1% and 4.6% of all deaths involve MAiD in countries where it is legal .
In most permissive jurisdictions, MAiD is not available to individuals with dementia. Patients are either still capable but not near enough to the end of life, or they are close enough to the end of life but no longer capable. However, in the Netherlands, where being at the end of life is not a condition of eligibility for MAiD, 109 euthanasia requests from competent patients in the early stages of dementia were granted in 2015 . Furthermore, the Dutch legislation allows a physician to comply with a euthanasia request made by a formerly competent patient through an advance request, as long as all of the "criteria of due care" are met (notably including unbearable suffering). To date, four cases have been reported regarding Dutch patients who requested euthanasia while competent via a written request, and whose requests were granted after they had become incompetent . Similarly, the law in Belgium does not require patients to be at the end of life or terminally ill, and does permit some access to MAiD through written requests made in advance of loss of capacity. However, in these cases the patient must be unconscious. In Luxembourg, a patient must be in a terminal condition, and access to MAiD is permitted through an advance request (provided the patient is unconscious). These requirements mean that many patients with dementia will not qualify for MAiD, but some will.
Until recently, MAiD was prohibited in Canada under several provisions of the Criminal Code. There have been court challenges to these provisions over the last 25 years, the most notable being Rodriguez v. British Columbia (Attorney General) in 1993 and, more recently, Carter v. Canada (Attorney General) in 2015 . In the first case, the Supreme Court of Canada dismissed the appeal of Sue Rodriguez, a woman living with amyotrophic lateral sclerosis who had challenged the validity of the Criminal Code prohibitions on MAiD . This decision was overturned on February 6, 2015 by a unanimous decision of the Supreme Court in Carter v. Canada . The judges ruled that the prohibitions violate section 7 of the Canadian Charter of Rights and Freedoms.
The Court's ruling catalyzed the Government of Canada to engage in consultation and draft legislation specifying the eligibility criteria and procedural safeguards for access to MAiD. Bill C-14 came into force on June 17, 2016 , enacting exemptions from criminal liability for physicians and nurse practitioners who provide MAiD, and for others who assist them. Eligibility is restricted to a competent adult who makes a voluntary and well-considered request for MAiD and has a, "grievous and irremediable medical condition" . Canada Bill C-14 defines medical assistance in dying as: The administering by a medical practitioner or nurse practitioner of a substance to a person, at their request, that causes their death, or the prescribing or providing by a medical practitioner or nurse practitioner of a substance to a person, at their request, so that they may self-administer the substance and in doing so cause their own death MAiD thus encompasses both euthanasia and physician-assisted suicide, as defined above. A person has a grievous and irremediable medical condition only if all of the following criteria are met: (a) they have a serious and incurable illness, disease, or disability; (b) they are in an advanced state of irreversible decline in capability; (c) that illness, disease, or disability or that state of decline causes them enduring physical or psychological suffering that is intolerable to them and that cannot be relieved under conditions that they consider acceptable; and (d) their natural death has become reasonably foreseeable, taking into account all of their medical circumstances, without a prognosis necessarily having been made as to the specific length of time that they have remaining Contrary to recommendations made by a Provincial-Territorial Expert Advisory Group on Physician-Assisted Dying and a Special Joint Committee of the House and Senate on Physician-Assisted Dying , the federal legislation does not allow a person to access MAiD through a request made in advance of loss of capacity. However, the legislation mandated an independent review and reporting back to Parliament on several issues, including advance requests. The government has commissioned the Council of Canadian Academies to independently manage the review and report to Parliament by December 2018.
On June 10, 2014, eight months before the Supreme Court's ruling in Carter v. Canada, the Quebec National Assembly adopted An Act respecting end-of-life care (Bill 52) which codifies recommendations made by the Quebec College of Physicians and the province's Select Committee on Dying with Dignity . Briefly, Bill 52 first affirms the right of everyone to end-of-life care that is appropriate to their needs. The bill also regulates continuous palliative sedation, establishes an advance medical directives regime, and permits MAiD under strictly defined circumstances . In Quebec Bill 52, MAiD is defined as: Care consisting in the administration by a physician of medications or substances to an end-of-life patient, at the patient's request, in order to relieve their suffering by hastening death This definition corresponds to euthanasia, as defined above. Nurse practitioners are not authorized to administer aid in dying under the Quebec legislation. The legislation became effective on December 10, 2015. Eligibility for MAiD is restricted to competent adults from Quebec who are at the end of their lives, have made persistent explicit requests for MAiD, and: Suffer from a serious and incurable illness, are in an advanced state of irreversible decline in capacity, and experience constant and unbearable physical or psychological suffering which cannot be relieved in a matter the patient deems tolerable (article 26) .
For greater clarity, article 51 specifies that MAiD may not be requested by means of an advance medical directive.
Quebec Bill 52 has drawn both opposition and support, with some supporters recommending that access to MAiD be extended to incompetent patients, provided appropriate safeguards are in place . Proposed safeguards for MAiD, should it be accessible to incompetent individuals, have included: an explicit request made in an advance directive by the patient while competent; consent from the patient's legal representative; and prior authorization of a local or provincial body, where relatives and health professionals could be heard . Ultimately, Quebec decided not to give incompetent patients access to MAiD through Bill 52, noting a lack of societal consensus on this issue . However, recently the Minister of Health and Social Services announced that an expert group will be tasked with studying whether access to MAiD should be permitted through requests made in advance of loss of capacity. This initiative has obvious implications for patients with dementia.
In both Canada and the province of Quebec, eligibility criteria for MAiD currently exclude patients who have become incompetent due to Alzheimer's disease or other forms of dementia. These are serious incurable conditions that progressively and irreversibly erode patients' abilities to perform basic activities of daily living. Additionally, many affected individuals develop serious clinical complications (eg, eating problems, pneumonia) and distressing symptoms (eg, pain, dyspnea) that are difficult to manage . However, by the time a patient satisfies these criteria, he or she is unlikely to be competent. Strong opinions have been voiced in support of, and in opposition to, the exclusion of patients with advanced Alzheimer's disease and other forms of dementia. The issue of respecting MAiD requests that are to be carried out after the patient has lost capacity is a complex health care issue that brings diverse societal values and beliefs into relief and conflict; these are briefly reviewed below.
Arguments For and Against MAiD, in General and for Incompetent Patients With Dementia
Arguments in favor of MAiD generally include individual autonomy and freedom of choice, the inability to relieve suffering in some cases, the absence of a moral distinction between withholding/withdrawing potentially life-sustaining treatment and MAiD, and the claim that permitting MAiD allows the establishment of stronger safeguards and oversight for the entire spectrum of end-of-life medical care through carefully-designed regimes. Arguments against MAiD include: the sanctity of life; the need to protect socially vulnerable populations from abuse and social discrimination; concerns about the slippery slope which (depending on the interpretation) could lead to more abuse, or to the legislation being extended to incompetent patients; the risk of impeding the development of palliative care; and ethical tensions faced by physicians who object to MAiD on moral grounds, but could feel or be obliged to carry out the request .
Other arguments are raised against MAiD when referring specifically to patients rendered incompetent by advanced dementia: patients' potential to adapt to their disease, which may change previously expressed wishes (the so-called "disability paradox"); the impossibility of health care providers and families engaging in meaningful conversations with the patient to confirm the wish to die; and practical difficulties in assessing suffering, balancing current preferences against earlier wishes laid down in a now-forgotten request, and choosing the right moment to carry out the request. Complying with an advance request for MAiD also raises the philosophical question of whether a request made by a previously competent person should have any authority over the life of a person who now has severe dementia .
Attitudes of Stakeholders Towards MAiD
Major groups of stakeholders likely to be impacted by extending MAiD to incompetent patients include older adults, relatives of patients with dementia, physicians, and nurses. Systematic reviews of quantitative studies from several countries, including Canada, show increasing support from these groups of stakeholders for MAiD in cases of competent terminally-ill patients experiencing severe pain who make an explicit request . Far fewer studies have investigated opinions of stakeholders on MAiD for patients with dementia . None of these studies were conducted in Canada and only two have focused exclusively on this issue . As shown in Table 1, support was found to be higher in the general population and lower among physicians, with nurses' opinions falling in between. Support for advance requests for MAiD is also stronger among the general public than among health care practitioners, who raise numerous issues regarding their use .
In conclusion, growing knowledge of possible clinical complications of advanced dementia, and current access to MAiD for competent adults, will likely trigger advance requests for MAiD from Canadians diagnosed with dementia . To date, no study has investigated the attitudes and beliefs of Canadians on this complex and sensitive issue. Similarly, no study has examined whether Canadians support other end-of-life medical practices in advanced dementia, such as the withholding of antibiotics for a life-threatening pneumonia or continuous deep sedation for agitation refractory to treatment. This study will shed light on these specific issues, providing much-needed evidence to support future health care policy development on end-of-life care for Canadians with advanced dementia.
Research Objectives and Hypotheses
Restricted to Quebec with plans for extension to other Canadian provinces, this study will elicit and compare the attitudes of four groups of stakeholders (seniors, relatives of persons with dementia, physicians, and nurses) towards MAiD for incompetent patients with dementia, the beliefs underpinning stakeholders' positions on this matter, and their opinions as to whether proposed safeguards can adequately protect incompetent patients. Based on findings in other countries , we expect that: (1) support for MAiD for incompetent patients with dementia will be higher among seniors and relatives than among health care practitioners; (2) support among health care practitioners will increase with additional safeguards, without reaching the level of support found in the two other groups; (3) religiosity, slippery slope, autonomy, and dying-with-dignity arguments will affect respondents' permissiveness toward MAiD for incompetent patients with dementia; and (4) the relative weight of these arguments in shaping opinions will vary across the four groups of stakeholders.
Study Design, Target Groups, and Sampling
An anonymous province-wide postal survey using clinical vignettes will be conducted on random samples of French-speaking Quebec residents belonging to one of four groups of stakeholders: (1) community-dwelling seniors aged 65 years or older, (2) relatives of persons with dementia, and (3) physicians and (4) nurses likely to be involved in end-of-life decision making. In Quebec, 94% of the population speaks French .
The random sample of community-dwelling seniors will come from the Quebec health insurance database. Relatives of patients with dementia will be reached through regional Alzheimer Societies. To protect their members' right to privacy, participating Societies will randomly select a predetermined number of potential participants (proportional to the size of their memberships) and distribute the survey package directly to them per our instructions. Assistance in managing the survey will be provided by our research staff to any Society that expresses the need. Practicing physicians and nurses will be recruited through their respective professional bodies, excluding those in full-time administrative, teaching, or research positions due to their limited direct contact with patients. Specialties for physicians will be restricted to family medicine, geriatrics, internal medicine, neurology, psychiatry, and intensive care; for nurses, specialties will be restricted to geriatrics/gerontology and end-of-life care.
Postal Survey
The survey and questionnaires were designed using strategies shown to maximize response rates and data quality . As depicted in Figure 1, randomly sampled individuals receive a personalized cover letter and accompanying materials in week 1, and a thank-you/reminder postcard in week 3. Nonrespondents are mailed a second survey package in week 12. The personal letter states the aim of the survey, explains how recipients were chosen, mentions that completing the questionnaire requires 20 minutes on average (based on pretesting), and addresses issues of privacy and anonymity. The letter also provides the Internet link (website address) to the online version of the questionnaire as well as the recipient's single-use personal identifier. A self-addressed and stamped return envelope is enclosed in the survey package for those who prefer to complete the printed questionnaire. A letter of endorsement from the Federation of Quebec Alzheimer Societies is also included, with a postcard bearing the respondent's name, to be returned separately from the questionnaire. Returned postcards make it possible to identify sampled individuals who have returned the questionnaire-either by mail or electronically-while preserving the anonymity of their answers. The postcard also serves the purpose of identifying sampled individuals who are no longer eligible (eg, seniors who are now institutionalized or too cognitively impaired to participate). The names of those who return the postcard are immediately removed from the mailing list to prevent further reminders. At the close of the postal survey, nonrespondents receive a 3-item questionnaire asking: (1) for their reasons for not participating (eg, felt questions were biased, lack of time, or doubt that anonymity can truly be preserved); (2) how comfortable they are with the current Quebec legislation that gives competent patients access to MAiD if certain conditions are met; and (3) whether they favor or oppose allowing physicians to administer MAiD to incompetent patients, with proper safeguards in place. The latter two questions will be used to assess nonresponse bias.
Questionnaires
After stating the eligibility criteria for MAiD as defined in Quebec's Act respecting end-of-life care, the 3-part questionnaire presents a series of multiple-choice questions, with space for the respondent's comments. Part 1 elicits attitudes towards MAiD and other end-of-life practices. Two sets of clinical vignettes are used for that purpose. The first vignette features a cancer patient who is eligible for MAiD. Using a 5-point Likert-type scale, respondents are asked to what extent they find it acceptable for a physician to sedate the patient continuously until death to relieve suffering, or to comply with the patient's request for MAiD. The second set, containing 7 interrelated vignettes, features a woman moving along the dementia trajectory, from the early stage when she is diagnosed with Alzheimer's disease to her final days of life. End-of-life practices (besides MAiD) for which support or opposition is investigated include withholding antibiotics for a life-threatening infection and continuous deep sedation for refractory agitation. Vignettes specify the source of the request for MAiD (an advance request made in writing by the patient while she was still competent, or her family), whether the patient appears to be suffering (eg, showing signs of distress, crying regularly), and whether death seems imminent. Vignettes are kept as nontechnical as possible to be easily understood, regardless of the respondent's medical knowledge. A sensitive and neutral tone is used throughout the questionnaire to prevent response bias. Part 1 ends with a list of statements designed to capture respondents' reasons for supporting or opposing MAiD, generally and for incompetent patients in particular. Reasons include, for example: religious and moral objections, respect for patient autonomy, practical difficulties in ascertaining whether an incompetent patient is suffering unbearably, and concerns about the slippery slope.
Part 2 explores related issues, such as whether respondents have filled out an advance directive for themselves, personally know someone with dementia, or have ever accompanied a dying relative or friend. Respondents are also asked the likelihood that they would request MAiD in advance of loss of capacity, should they be diagnosed with Alzheimer's disease, or ask a physician to comply with such a request drafted by a loved one under similar circumstances.
Part 3 collects sociodemographic data from all respondents (eg, age, gender, ethnicity, degree of religiosity) and contains additional group-specific questions. For seniors, these questions include educational attainment and self-rated health. Relatives are asked how long ago the person with dementia was diagnosed and their current level of cognitive functioning. Questions for physicians and nurses explore their experience in caring for dying and dementia patients, training in palliative care, and exposure to MAiD requests from patients or patients' relatives. Physicians are also asked whether they would be willing to provide such assistance, were it legal. Few physicians currently administer MAiD in Quebec, and to preserve their anonymity, surveyed physicians are not asked whether they have in fact provided such assistance in the past.
Questionnaires were developed in English with input from renowned English-speaking content experts from countries where assisted dying is legal or not criminalized. The questionnaires were then translated into French and pretested through cognitive interviews performed by a research assistant with representatives of the four groups of stakeholders (n=20).
Interviews were aimed at assessing the length of the questionnaires, clarity of the questions, uniformity in comprehension, and respondent comfort with the content . Following these interviews, minor modifications were made to some questions, which aimed at emphasizing differences between vignettes (eg, advanced vs. terminal stage of Alzheimer's disease, presence vs. absence of a written request). Questionnaires were then converted to a Web format. The Web questionnaires were developed using the latest version of LimeSurvey , a free open-source online survey application that allows assigning a single-use password to each sampled individual. The server hosting the LimeSurvey software uses proven encryption methods (Transport Layer Security) to transmit survey answers to a secure server and export collected data into a statistical package for analysis. Before launching the survey, the Web version was tested in-house and with several remote participants on different operating systems, browsers, and platforms, and for different types and speeds of Internet access. Systematic troubleshooting was performed to uncover unforeseen technical problems.
Data Analyses
The data will be analyzed in four consecutive steps. First, we will compare nonrespondents, respondents to the one-page questionnaire only, and late versus early respondents to the full questionnaire, to detect response bias and establish sample weights where needed. Response rates will be reported as recommended by the American Association for Public Opinion Research. In Step 2, we will study patterns of item nonresponse and determine whether imputing missing data would be appropriate . Next, we will summarize participant answers to the questionnaire, and compare distributions of answers within respondents, as well as within and between the four groups of stakeholders. Within-respondent comparisons will require multilevel analyses, since answers to different questionnaire items will be correlated . For instance, the proportions of respondents who support MAiD at the advanced versus terminal stages are not independent and hence cannot be compared using the usual Chi-square test. Estimations of model parameters will be based on maximum likelihood with adaptive quadrature, which outperforms other methods in terms of bias and efficiency of the estimates when the number of study participants is large, as is typical of survey research . Respondent characteristics will subsequently be added to the models in a stepwise fashion to identify additional correlates of response patterns in addition to group membership. Residual analyses will be conducted to assess the tenability of the assumptions underlying the statistical models, and to identify influential observations and outliers. Multilevel modelling will be conducted with SAS Proc NLMIXED , which offers a wide choice of integral approximations and optimization techniques.
Sample Size
The data from our four samples will first be summarized with proportions and associated confidence intervals. In the worst-case scenario of equal proportions for and against a given end-of-life practice, two-sided 95% confidence intervals for proportions require 385 respondents per sample when the semiinterval width is set at 5% (nQuery Advisor, version 7.0). The sample size required for reliably fitting multilevel models depends on several factors, including sample size at each level of the analysis, number and type of predictors included in the model, intraclass correlation, and model complexity. Recent Monte Carlo simulation studies on multilevel models for binary and continuous outcomes suggest that 100 to 200 level-2 units (ie, survey respondents) with 5 to 10 level-1 units (ie, questionnaire items) ensure model convergence and provide adequate power for testing fixed and random effects . To determine the number of questionnaires to mail out to achieve the target of 385 respondents per group, we applied response rates derived by averaging those reported in Table 1 with our own . The resulting numbers are: 621 seniors, 527 relatives of persons with dementia, 653 physicians, and 514 nurses, for a total of 2315 potential participants.
Ethical Considerations
This study will investigate views on sensitive issues. While there are no physical risks to participants, psychological risks must be acknowledged. Questionnaires may trigger emotional distress in some participants or revive painful memories of the death and suffering of a loved one. In an effort to minimize these risks, the cover letter that accompanies the questionnaire includes contact details for a support resource, if needed. Participation in the survey is voluntary and answers are anonymous. Signed consent is not required; in anonymous surveys, implicit consent is inferred from respondents who return the questionnaire . All information needed for informed consent is provided in the cover letters, including a toll-free telephone number and email address for those who have questions or concerns about the survey. Personal information on sampled individuals is coded, and access to password-protected lists of codes is restricted to the research team. Sampling lists will be destroyed five years after the end of the study. The Research Ethics Board of the University Institute of Geriatrics of Sherbrooke granted ethical approval of the survey design and questionnaires (file # 2016-623).
Results
The survey was launched in September 2016 among relatives of patients with dementia, physicians, and nurses, and is still ongoing. The survey will be launched among older adults as soon as we receive a random list of names extracted from the Quebec health insurance database.
Discussion
To the best of our knowledge, this study will be the first to uncover Quebec stakeholders' attitudes towards MAiD for incompetent patients with dementia, which is a vulnerable and rapidly expanding population of patients. Dementia affects more than 37 million people worldwide, with a projected increase to over 115 million by 2050 . The Alzheimer Society of Canada has estimated that 564,000 Canadians were living with dementia in 2016, and this number is expected to rise to 937,000 by 2031, representing an increase of 66% . Life expectancy after a dementia diagnosis is believed to lie between 3 and 12 years . Because no cure is foreseen in the near future, many people will die with or from dementia. Over the last decade, deaths attributed to Alzheimer's disease rose by 39% in the United States . Although quality of life can be good in the early stages, dementia still ranks among the most feared clinical conditions in modern societies . Indeed, some perceive this syndrome as a "fate worse than death" and dread the prospect of living through the advanced stages of dementia .
People are apprehensive about the progressive loss of decisional capacity and control, prolonged dependence upon others for their most basic needs, inability to report physical and psychological suffering, and lengthy periods of institutionalization before death. As the prevalence of dementia continues to rise, a growing number of individuals who do not want to experience the full course of dementia might request MAiD.
Do stakeholders believe that MAiD should be made available to patients who have reached an advanced stage of dementia? Under what circumstances? Are other end-of-life practices viewed as more appropriate? Can proposed safeguards on MAiD adequately protect vulnerable individuals from abuse and coercion? Do views on these issues vary markedly within and between groups of stakeholders? By using a proven research methodology and identical questions across stakeholder groups, this study will provide answers to these questions, which have yet to be explored in Canada, and have only been partially investigated in other countries.
Strengths and Limitations
The current study has strengths and limitations. Strengths include: the timeliness of the survey, which will inform ongoing legislative activities; random selection of potential respondents from four highly relevant groups of stakeholders; the anonymity of answers, which decreases bias due to social desirability; the care taken in designing and testing the questionnaires with input from international content experts; and our decision to administer a common set of questions to all four groups of stakeholders, enabling direct comparison of their views on MAiD for incompetent patients with dementia. The presence of investigators on the research team who support, and others who oppose, extending MAiD to these patients is another strength, as it minimizes the risk of biased questions and increases uptake of research findings .
Although not without limitations, surveys contribute invaluable data to inform ethical debates, public policy development, and future research on sensitive issues such as whether MAiD should be extended to incompetent patients with dementia . Postal surveys offer many advantages over other data collection methods. First, such surveys are relatively inexpensive for surveying large and geographically dispersed populations, provide greater flexibility for the respondents, maintain anonymity, and yield higher response rates than telephone surveys . In our survey, sampled individuals have the option to complete a paper or online version of the questionnaire, which is a strategy shown to yield even higher response rates . Second, earlier studies conducted abroad provide a solid basis for the design of high-quality clinical vignettes featuring incompetent patients, MAiD requests, and end-of-life practices . Additionally, the practical problems and moral dilemmas created by advanced MAiD requests, and the arguments for and against MAiD for incompetent patients with dementia, have been thoroughly reviewed . These reviews have provided ample materials from which to formulate questionnaire items for exploring beliefs underlying attitudes.
Low response rates threaten the external validity of findings from attitude surveys. To counter this problem, both the survey and the questionnaires were designed using strategies that comprehensive reviews have shown to be effective . Response rate is an imperfect indicator of survey quality, however. Empirical assessments over the past decade have concluded that response rates may not be as strongly associated with survey quality as was generally believed . The degree to which respondents differ from the target population is the central issue. Well-recognized approaches to assess nonresponse bias and minimize its effect are part of our analytical plan and include: inviting initial nonrespondents to complete a shorter questionnaire with only key measures of interest, comparing respondents with nonrespondents using information available in the sampling frame, comparing early versus late respondents on personal characteristics and answers to survey questions, and weighting analyses of the variables of primary interest.
One limitation is the restriction of the survey to the province of Quebec. We plan to extend the survey to the rest of Canada in the near future, using the same questionnaires to enable provincial/territorial comparisons. Short case descriptions with a limited number of possible answers fall short of capturing the complexity of end-of-life decision making . Our upcoming pan-Canadian survey will include a qualitative component aimed at gaining deeper insight into respondents' thought processes and the reasons behind their support for, or opposition to, MAiD for incompetent patients with dementia . Opinions are elicited using specific vignettes. Whether opinions extend to other clinical contexts involving MAiD requests from incompetent patients with dementia will remain unknown. We chose not to elicit attitudes towards extending MAiD to patients at earlier stages of dementia who are still competent. Including cases of early and late stage dementia in the same questionnaire would increase its length and possibly lower response rates. We also chose not to recruit in long-term care facilities, where most residents would be too cognitively impaired to provide reliable and valid answers to the survey questionnaire. We do not purposefully target seniors with dementia, even though those at an early stage of the disease would likely have the cognitive abilities to participate in the survey. We felt that a self-administered questionnaire was not ethically appropriate for this subpopulation, given the sensitive nature of the subject under investigation . However, as the views and concerns of this population regarding end-of-life practices in advanced dementia are highly relevant yet currently unknown, we are simultaneously conducting a qualitative study in this population. The data from persons with early dementia will be collected during face-to-face interviews, allowing the interviewer to respond promptly should questions trigger negative emotions in some participants. Combining findings from our survey with those from the in-depth interviews will allow more nuanced recommendations as to whether MAiD should be expanded to incompetent patients with dementia. |
<gh_stars>0
package link.thingscloud.freeswitch.esl.helper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import io.netty.channel.Channel;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @author th158
*/
public class ChannelCacheHelper {
private static final Cache<String, Channel> channelCache = CacheBuilder.newBuilder()
.maximumSize(8000)
.expireAfterWrite(1, TimeUnit.DAYS)
.removalListener(new RemovalListener<String, Channel>() {
@Override
public void onRemoval(RemovalNotification<String, Channel> removalNotification) {
removalNotification.getValue().close();
}
})
.build();
private static final Cache<String, List<ChannelStateMachine>> listCache = CacheBuilder.newBuilder()
.maximumSize(8000)
.expireAfterWrite(1, TimeUnit.DAYS)
.removalListener(new RemovalListener<String, List<ChannelStateMachine>>() {
@Override
public void onRemoval(RemovalNotification<String, List<ChannelStateMachine>> removalNotification) {
// todo
}
})
.build();
public static void setCache(String coreUUID, Channel channel) {
channelCache.put(coreUUID, channel);
}
public static Channel getCache(String coreUUID) {
try {
return channelCache.get(coreUUID, new Callable<Channel>() {
@Override
public Channel call() throws Exception {
return null;
}
});
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
|
Possible Unintended Consequence of an Evidence-Based Clinical Policy Change
he Annals of Family Medicine encourages read- ers to develop a learning community of those seeking to improve health care and health through enhanced primary care. You can participate by conducting a RADICAL journal club and sharing the results of your discussions in the Annals online discus- sion for the featured articles. RADICAL is an acronym for Read, Ask, Discuss, Inquire, Collaborate, Act, and Learn. The word radical also indicates the need to engage diverse participants in thinking critically about important issues affecting primary care and then acting on those discussions. 1 |
import { saveTokens, getTokenFromStorage, getRefreshTokenFromStorage, saveAccessToken, cleanTokens } from './storage';
test('storage tokens', () => {
expect(getTokenFromStorage()).toBeNull();
expect(getRefreshTokenFromStorage()).toBeNull();
let accessToken = '_access_token_';
let refreshToken = '_refresh_token_';
saveTokens({ accessToken, refreshToken });
expect(getTokenFromStorage()).toEqual(accessToken);
expect(getRefreshTokenFromStorage()).toEqual(refreshToken);
saveAccessToken('_access_token_changed_');
expect(getTokenFromStorage()).toEqual('_access_token_changed_');
cleanTokens();
expect(getTokenFromStorage()).toBeNull();
expect(getRefreshTokenFromStorage()).toBeNull();
});
|
I have a Glock 19. The gun itself was purchased last year, im the only owner. It is an factory FDE frame. The factory barrel has roughly 150 rounds through it. It has a ghost trigger bar installed. It also has brand new Trijicon HD night sights professionally installed. Has all the factory stuff that came with it. Gun is in great shape and well taken care of. Im getting rid of it because I really want a nice lever action hunting rifle.
Comes with Three 15 round magazines. two of which have +2 extensions. This will come with the factory barrel, it has talon grips installed, it can be removed but it makes the gun feel so nice.
I also have a lone wolf match grade barrel I can include for extra...
700 is the lowest im going to go. If you even ask ill just ignore it.
Will trade for: Looking for a Marlin 1895SBL 45-70. I would also be interested in a Henry All weather 30-30 or 45-70.
no shotguns, no revolvers, No bolt action rifles, no .22s, no .40s.
Only pistols I would be interested in is a HK p30, Chiappa Rhino.
I do have a lot of holsters for this gun that I could include to even out price. |
/**
* Deserializes the aliased discovery config nested under the {@code tag} in the provided JSON.
*
* @param json the JSON object containing the serialized config
* @param tag the tag under which the config is nested
* @return the deserialized config or {@code null} if the serialized config
* was missing in the JSON object
*/
private AliasedDiscoveryConfig deserializeAliasedDiscoveryConfig(
JsonObject json, String tag) {
JsonValue configJson = json.get(tag);
if (configJson != null && !configJson.isNull()) {
AliasedDiscoveryConfigDTO dto = new AliasedDiscoveryConfigDTO(tag);
dto.fromJson(configJson.asObject());
return dto.getConfig();
}
return null;
} |
<reponame>krichard410/moloch-dao-substrate<filename>target/release/build/libp2p-kad-abf4fae90ee4ac8d/out/dht.pb.rs
/// Record represents a dht record that contains a value
/// for a key value pair
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Record {
/// The key that references this record
#[prost(bytes, tag="1")]
pub key: std::vec::Vec<u8>,
/// The actual value this record is storing
#[prost(bytes, tag="2")]
pub value: std::vec::Vec<u8>,
// Note: These fields were removed from the Record message
// hash of the authors public key
//optional string author = 3;
// A PKI signature for the key+value+author
//optional bytes signature = 4;
/// Time the record was received, set by receiver
#[prost(string, tag="5")]
pub time_received: std::string::String,
/// The original publisher of the record.
/// Currently specific to rust-libp2p.
#[prost(bytes, tag="666")]
pub publisher: std::vec::Vec<u8>,
/// The remaining TTL of the record, in seconds.
/// Currently specific to rust-libp2p.
#[prost(uint32, tag="777")]
pub ttl: u32,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Message {
/// defines what type of message it is.
#[prost(enumeration="message::MessageType", tag="1")]
pub r#type: i32,
/// defines what coral cluster level this query/response belongs to.
/// in case we want to implement coral's cluster rings in the future.
///
/// NOT USED
#[prost(int32, tag="10")]
pub cluster_level_raw: i32,
/// Used to specify the key associated with this message.
/// PUT_VALUE, GET_VALUE, ADD_PROVIDER, GET_PROVIDERS
#[prost(bytes, tag="2")]
pub key: std::vec::Vec<u8>,
/// Used to return a value
/// PUT_VALUE, GET_VALUE
#[prost(message, optional, tag="3")]
pub record: ::std::option::Option<Record>,
/// Used to return peers closer to a key in a query
/// GET_VALUE, GET_PROVIDERS, FIND_NODE
#[prost(message, repeated, tag="8")]
pub closer_peers: ::std::vec::Vec<message::Peer>,
/// Used to return Providers
/// GET_VALUE, ADD_PROVIDER, GET_PROVIDERS
#[prost(message, repeated, tag="9")]
pub provider_peers: ::std::vec::Vec<message::Peer>,
}
pub mod message {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Peer {
/// ID of a given peer.
#[prost(bytes, tag="1")]
pub id: std::vec::Vec<u8>,
/// multiaddrs for a given peer
#[prost(bytes, repeated, tag="2")]
pub addrs: ::std::vec::Vec<std::vec::Vec<u8>>,
/// used to signal the sender's connection capabilities to the peer
#[prost(enumeration="ConnectionType", tag="3")]
pub connection: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum MessageType {
PutValue = 0,
GetValue = 1,
AddProvider = 2,
GetProviders = 3,
FindNode = 4,
Ping = 5,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum ConnectionType {
/// sender does not have a connection to peer, and no extra information (default)
NotConnected = 0,
/// sender has a live connection to peer
Connected = 1,
/// sender recently connected to peer
CanConnect = 2,
/// sender recently tried to connect to peer repeatedly but failed to connect
/// ("try" here is loose, but this should signal "made strong effort, failed")
CannotConnect = 3,
}
}
|
Hugh McNeal, chief executive of the British wind industry’s trade body, has acknowledged that with subsidies at an end, there won’t be any more wind turbine projects in England. Why? The wind doesn’t blow hard enough:
We are almost certainly not talking about the possibility of new plants in England. The project economics wouldn’t work; the wind speeds don’t allow for it.
Then, of course, there is “the cost of operating a conventional fleet of almost unchanged size to guarantee security of supply.” In other words, you can’t count on the wind blowing (just as you can’t count on the Sun shining), so no matter how many turbines you build, you still have to have enough coal, gas or nuclear plants to meet peak demand.
Too often left unsaid is that in addition to being uneconomic, wind power is bad for the environment. Not only do wind turbines kill vast numbers of birds and bats, they are noisy–here in Minnesota, lawsuits have been filed by people who live near wind farms and claim to have experienced adverse health effects on account of noise–take up lots of land that could be put to more productive uses, and are unsightly. |
# coding: utf-8
# Your code here!
num = int(input())
dish = [int(item)-1 for item in input().split()]
satis = [int(item) for item in input().split()]
additional = [int(item) for item in input().split()]
sum = 0
prev = num + 10
for item in dish:
sum += satis[item]
if item == prev +1:
sum += additional[prev]
prev = item
print(sum) |
//
// UtilsMacro.h
// DirectoryStructure
//
// Created by aaron.wu on 16/7/22.
// Copyright © 2016年 xuewei.zhang. All rights reserved.
// 放的是一些方便使用的宏定义
#ifndef UtilsMacro_h
#define UtilsMacro_h
#define WeakObj(o) autoreleasepool{} __weak typeof(o) o##Weak = o
#define StrongObj(o) autoreleasepool{} __strong typeof(o) o = o##Weak
//#define StrongObj(o) autoreleasepool{} __strong typeof(o##Weak) o##Strong = o##Weak
//获取系统版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define CurrentSystemVersion [[UIDevice currentDevice] systemVersion]
//判断是真机还是模拟器
#if TARGET_OS_IPHONE
//iPhone Device
#endif
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif
//单例化一个类
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [self alloc] init]; \
} \
} \
\
return shared##classname; \
}
//设置View的tag属性
#define VIEWWITHTAG(_OBJECT, _TAG) [_OBJECT viewWithTag : _TAG]
//程序的本地化,引用国际化的文件
#define MyLocal(x, ...) NSLocalizedString(x, nil)
//G-C-D
#define BACK(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
#define MAIN(block) dispatch_async(dispatch_get_main_queue(),block)
//文件目录
#define kPathTemp NSTemporaryDirectory()
#define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,\
NSUserDomainMask, YES) objectAtIndex:0]
#define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,\
NSUserDomainMask, YES) objectAtIndex:0]
//角度转弧度
#define DEGREES_TO_RADIANS(d) (d * M_PI / 180)
//大于等于7.0的ios版本
#define iOS7_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")
//大于等于8.0的ios版本
#define iOS8_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")
// 获取RGB颜色
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define RGB(r,g,b) RGBA(r,g,b,1.0f)
#define IsNilOrNull(_ref) (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]))
//转换
#define NSStringFromInt(intValue) [NSString stringWithFormat:@"%d",intValue]
//字体大小
#define kFont38 [UIFont systemFontOfSize:38]
#define kFont34 [UIFont systemFontOfSize:34]
#define kFont30 [UIFont systemFontOfSize:30]
#define kFont28 [UIFont systemFontOfSize:28]
#define kFont26 [UIFont systemFontOfSize:26]
#define kFont25 [UIFont systemFontOfSize:25]
#define kFont24 [UIFont systemFontOfSize:24]
#define kFont22 [UIFont systemFontOfSize:22]
#define kFont20 [UIFont systemFontOfSize:20]
#define kFont18 [UIFont systemFontOfSize:18]
#define kFont17 [UIFont systemFontOfSize:17]
#define kFont15 [UIFont systemFontOfSize:15]
#define kFont16 [UIFont systemFontOfSize:16]
#define kFont14 [UIFont systemFontOfSize:14]
#define kFont13 [UIFont systemFontOfSize:13]
#define kFont12 [UIFont systemFontOfSize:12]
#define kFont11 [UIFont systemFontOfSize:11]
#define kFont10 [UIFont systemFontOfSize:10]
#endif /* UtilsMacro_h */
|
Multiple job-holding and artistic careers: some empirical evidence
This article focuses attention on a somewhat overlooked component of the career portfolios of practising professional artists, namely their non-arts work. Although it is widely known that artists hold multiple jobs for a variety of reasons, there is little information on which jobs artists take on, whether they can make use of their creative skills in these jobs and how far artists doing non-arts work are different from artists who don't. We focus on two aspects of artists' non-arts work. First, we consider artists' working patterns in non-arts areas in general, looking particularly at the factors that influence artists to take on work outside the arts. Second, we analyse the extent to which artists are able to apply their creative skills in industries beyond the core arts, interpreting these results in the context of the concentric circles model of the cultural industries. Data used in this article are derived from the authors' recently completed survey of practising professional artists in Australia. |
<gh_stars>1-10
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 rdiscover
import (
rd "bk-bcs/bcs-common/common/RegisterDiscover"
"bk-bcs/bcs-common/common/blog"
"bk-bcs/bcs-common/common/types"
"bk-bcs/bcs-common/common/version"
"context"
"encoding/json"
"os"
"time"
)
// RoleEvent event for role change
type RoleEvent string
const (
// MasterToSlave event role change from master to slave
MasterToSlave = "m2s"
// SlaveToMaster event role change from slave to master
SlaveToMaster = "s2m"
)
// AdapterDiscover service discovery and master election for mesos adapter
type AdapterDiscover struct {
isMaster bool
rd *rd.RegDiscover
zkAddr string
clusterID string
ip string
metricPort uint
eventQueue chan RoleEvent
cancel context.CancelFunc
}
// NewAdapterDiscover create Adapter Discover
func NewAdapterDiscover(zkAddr, ip, clusterID string, metricPort uint) (*AdapterDiscover, <-chan RoleEvent) {
eventQueue := make(chan RoleEvent, 128)
return &AdapterDiscover{
isMaster: false,
rd: rd.NewRegDiscoverEx(zkAddr, 20*time.Second),
zkAddr: zkAddr,
ip: ip,
clusterID: clusterID,
metricPort: metricPort,
eventQueue: eventQueue,
}, eventQueue
}
// Start register zk path and monitor all registered adapters
func (ad *AdapterDiscover) Start() {
var err error
rootCxt, cancel := context.WithCancel(context.Background())
ad.cancel = cancel
err = ad.rd.Start()
if err != nil {
blog.Errorf("failed to start RegisterDiscover, err %s", err.Error())
blog.Infof("restart AdapterDiscover after 3 second")
time.Sleep(3 * time.Second)
go ad.Start()
return
}
err = ad.registerAdapter()
if err != nil {
blog.Errorf("failed to register mesos adapter, err %s", err.Error())
blog.Infof("restart AdapterDiscover after 3 second")
ad.rd.Stop()
time.Sleep(3 * time.Second)
go ad.Start()
return
}
adaptersPath := ad.getZkDiscoveryPath()
discoveryEvent, err := ad.rd.DiscoverService(adaptersPath)
if err != nil {
blog.Errorf("failed to register discover for mesos-adapter, err %s", err.Error())
blog.Infof("restart AdapterDiscover after 3 second")
ad.rd.Stop()
time.Sleep(3 * time.Second)
go ad.Start()
return
}
for {
select {
case curEvent := <-discoveryEvent:
servers := curEvent.Server
blog.V(3).Infof("discover mesos adapters(%v)", servers)
adapters := []*types.ServerInfo{}
for _, server := range servers {
adapter := new(types.ServerInfo)
err = json.Unmarshal([]byte(server), adapter)
if err != nil {
blog.Warnf("failed to unmarshal(%s), err %s", server, err.Error())
continue
}
adapters = append(adapters, adapter)
}
if len(adapters) == 0 {
blog.Warnf("found no registered adapters")
if ad.isMaster {
ad.isMaster = false
ad.eventQueue <- MasterToSlave
}
blog.Infof("Role changed, I become Slave")
continue
}
if adapters[0].IP == ad.ip && !ad.isMaster {
ad.isMaster = true
ad.eventQueue <- SlaveToMaster
blog.Infof("Role changed, I become Master")
continue
} else if adapters[0].IP != ad.ip && ad.isMaster {
ad.isMaster = false
ad.eventQueue <- MasterToSlave
blog.Infof("Role changed, I become Slave")
continue
}
case <-rootCxt.Done():
blog.Warnf("AdapterDiscover context done")
return
}
}
}
func (ad *AdapterDiscover) registerAdapter() error {
host, err := os.Hostname()
if err != nil {
blog.Error("mesos adapter get hostname err: %s", err.Error())
host = "UNKOWN"
}
serverInfo := types.ServerInfo{}
serverInfo.IP = ad.ip
serverInfo.Port = ad.metricPort
serverInfo.MetricPort = ad.metricPort
serverInfo.Pid = os.Getpid()
serverInfo.Version = version.GetVersion()
serverInfo.Cluster = ad.clusterID
serverInfo.HostName = host
// TODO: support https
serverInfo.Scheme = "http"
serverInfoByte, err := json.Marshal(serverInfo)
if err != nil {
blog.Errorf("fail to marshal mesos-adapter info to bytes, err %s", err.Error())
return err
}
serverRegisterPath := ad.getZkDiscoveryPath() + "/" + serverInfo.IP
return ad.rd.RegisterAndWatchService(serverRegisterPath, serverInfoByte)
}
func (ad *AdapterDiscover) getZkDiscoveryPath() string {
return types.BCS_SERV_BASEPATH + "/" + types.BCS_MODULE_MESOSADAPTER + "/" + ad.clusterID
}
|
<reponame>NatsubiSogan/comp_library<gh_stars>1-10
# SCC
def strongly_connected_component(G: list) -> list:
n = len(G)
G_rev = [[] for i in range(n)]
for i in range(n):
for v in G[i]:
G_rev[v].append(i)
vs = []
visited = [False] * n
def dfs(v):
visited[v] = True
for u in G[v]:
if not visited[u]:
dfs(u)
vs.append(v)
for i in range(n):
if not visited[i]:
dfs(i)
rev_visited = [False] * n
def rev_dfs(v):
p.append(v)
rev_visited[v] = True
for u in G_rev[v]:
if not rev_visited[u]:
rev_dfs(u)
res = []
for v in vs[::-1]:
if not rev_visited[v]:
p = []
rev_dfs(v)
res.append(p)
return res
|
/**
* RequeryEntityInformationSupportTest
*
* @author debop
* @since 18. 6. 12
*/
@RunWith(MockitoJUnitRunner.class)
public class RequeryEntityInformationSupportTest {
@Mock RequeryOperations operations;
@Mock EntityModel entityModel;
@Test
public void usesSimpleClassNameIfNoEntityNameGiven() throws Exception {
RequeryEntityInformation<User, Long> information = new DummyRequeryEntityInformation<>(User.class);
assertThat(information.getEntityName()).isEqualTo("User");
assertThat(information.getModelName()).isNullOrEmpty();
RequeryEntityInformation<AbstractBasicUser, Long> second = new DummyRequeryEntityInformation<>(AbstractBasicUser.class);
assertThat(second.getEntityName()).isEqualTo("BasicUser");
assertThat(second.getModelName()).isEqualTo("default");
}
@Test(expected = IllegalArgumentException.class)
public void rejectsClassNotBeingFoundInMetamodel() {
Mockito.when(operations.getEntityModel()).thenReturn(entityModel);
RequeryEntityInformationSupport.getEntityInformation(User.class, operations);
}
static class User {
}
static class DummyRequeryEntityInformation<T, ID> extends RequeryEntityInformationSupport<T, ID> {
public DummyRequeryEntityInformation(Class<T> domainClass) {
super(domainClass);
}
@Override
@Nullable
public Attribute<? super T, ?> getIdAttribute() {
return null;
}
@Override
public boolean hasCompositeId() {
return false;
}
@Override
public Iterable<String> getIdAttributeNames() {
return Collections.emptySet();
}
@Override
@Nullable
public Object getCompositeIdAttributeValue(Object id, String idAttribute) {
return null;
}
@Override
public ID getId(T entity) {
return null;
}
@Override
public Class<ID> getIdType() {
return null;
}
}
} |
/**
* Test of previous method, of class RandomAccessShapefile.
*/
@Test
public void testPrevious() {
System.out.println("previous");
ShapefileRecord rec = instance.nextRecord();
int curRecNo = rec.getRecordNumber();
assertEquals(FIRST_REC_NO, curRecNo);
boolean result = instance.previous();
assertEquals(true, result);
rec = instance.nextRecord();
curRecNo = rec.getRecordNumber();
assertEquals(FIRST_REC_NO, curRecNo);
result = instance.previous();
assertEquals(true, result);
result = instance.previous();
assertEquals(false, result);
} |
from insights.parsers.teamdctl_config_dump import TeamdctlConfigDump
from insights.parsers import teamdctl_config_dump
from insights.tests import context_wrap
import doctest
TEAMDCTL_CONFIG_DUMP_INFO = """
{
"device": "team0",
"hwaddr": "DE:5D:21:A8:98:4A",
"link_watch": [
{
"delay_up": 5,
"name": "ethtool"
},
{
"name": "nsna_ping",
"target_host ": "target.host"
}
],
"mcast_rejoin": {
"count": 1
},
"notify_peers": {
"count": 1
},
"runner": {
"hwaddr_policy": "only_active",
"name": "activebackup"
}
}
""".strip()
def test_teamdctl_state_dump():
result = TeamdctlConfigDump(context_wrap(TEAMDCTL_CONFIG_DUMP_INFO))
assert result.device_name == 'team0'
assert result.runner_name == 'activebackup'
assert result.runner_hwaddr_policy == 'only_active'
def test_nmcli_doc_examples():
env = {
'teamdctl_config_dump': TeamdctlConfigDump(context_wrap(TEAMDCTL_CONFIG_DUMP_INFO)),
}
failed, total = doctest.testmod(teamdctl_config_dump, globs=env)
assert failed == 0
|
package storetest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"sort"
"testing"
stdtime "time"
"github.com/google/uuid"
"github.com/modernice/goes/aggregate"
"github.com/modernice/goes/aggregate/snapshot"
"github.com/modernice/goes/aggregate/snapshot/query"
"github.com/modernice/goes/event/query/time"
"github.com/modernice/goes/event/query/version"
"github.com/modernice/goes/internal/xaggregate"
"github.com/modernice/goes/internal/xtime"
)
// StoreFactory creates Stores.
type StoreFactory func() snapshot.Store
// Run runs the Store tests.
func Run(t *testing.T, newStore StoreFactory) {
run(t, "Save", testSave, newStore)
run(t, "Latest", testLatest, newStore)
run(t, "Latest (multiple available)", testLatestMultipleAvailable, newStore)
run(t, "Latest (not found)", testLatestNotFound, newStore)
run(t, "Version", testVersion, newStore)
run(t, "Version (not found)", testVersionNotFound, newStore)
run(t, "Limit", testLimit, newStore)
run(t, "Query", testQuery, newStore)
run(t, "Delete", testDelete, newStore)
}
func run(t *testing.T, name string, runner func(*testing.T, StoreFactory), newStore StoreFactory) {
t.Run(name, func(t *testing.T) {
runner(t, newStore)
})
}
func testSave(t *testing.T, newStore StoreFactory) {
s := newStore()
a := &snapshotter{
Base: aggregate.New("foo", uuid.New()),
state: state{Foo: 3},
}
snap, err := snapshot.New(a)
if err != nil {
t.Fatalf("Marshal shouldn't fail; failed with %q", err)
}
if err := s.Save(context.Background(), snap); err != nil {
t.Errorf("Save shouldn't fail; failed with %q", err)
}
}
func testLatest(t *testing.T, newStore StoreFactory) {
s := newStore()
a := &snapshotter{
Base: aggregate.New("foo", uuid.New()),
state: state{Foo: 3},
}
snap, err := snapshot.New(a)
if err != nil {
t.Fatalf("Marshal shouldn't fail; failed with %q", err)
}
if err := s.Save(context.Background(), snap); err != nil {
t.Errorf("Save shouldn't fail; failed with %q", err)
}
latest, err := s.Latest(context.Background(), a.AggregateName(), a.AggregateID())
if err != nil {
t.Fatalf("Latest shouldn't fail; failed with %q", err)
}
if snap.AggregateName() != latest.AggregateName() {
t.Errorf("AggregateName should return %q; got %q", snap.AggregateName(), latest.AggregateName())
}
if snap.AggregateID() != latest.AggregateID() {
t.Errorf("AggregateID should return %q; got %q", snap.AggregateID(), latest.AggregateID())
}
if snap.AggregateVersion() != latest.AggregateVersion() {
t.Errorf("AggregateVersion should return %q; got %q", snap.AggregateVersion(), latest.AggregateVersion())
}
wantTime := snap.Time()
if !latest.Time().Equal(wantTime) {
t.Errorf("Time should return %v; got %v", wantTime, latest.Time())
}
if !bytes.Equal(snap.State(), latest.State()) {
t.Errorf("Data should return %v; got %v", snap.State(), latest.State())
}
}
func testLatestMultipleAvailable(t *testing.T, newStore StoreFactory) {
s := newStore()
id := uuid.New()
a10 := &snapshotter{Base: aggregate.New("foo", id, aggregate.Version(10))}
a20 := &snapshotter{Base: aggregate.New("foo", id, aggregate.Version(20))}
snap10, _ := snapshot.New(a10)
snap20, _ := snapshot.New(a20)
if err := s.Save(context.Background(), snap20); err != nil {
t.Errorf("Save shouldn't fail; failed with %q", err)
}
if err := s.Save(context.Background(), snap10); err != nil {
t.Errorf("Save shouldn't fail; failed with %q", err)
}
latest, err := s.Latest(context.Background(), "foo", id)
if err != nil {
t.Fatalf("Latest shouldn't fail; failed with %q", err)
}
if latest.AggregateName() != "foo" {
t.Errorf("AggregateName should return %q; got %q", "foo", latest.AggregateName())
}
if latest.AggregateID() != id {
t.Errorf("AggregateID should return %q; got %q", id, latest.AggregateID())
}
if latest.AggregateVersion() != 20 {
t.Errorf("AggregateVersion should return %q; got %q", 20, latest.AggregateVersion())
}
wantTime := snap20.Time()
if !latest.Time().Equal(wantTime) {
t.Errorf("Time should return %v; got %v", wantTime, latest.Time())
}
if !bytes.Equal(snap20.State(), latest.State()) {
t.Errorf("Data should return %v; got %v", snap20.State(), latest.State())
}
}
func testLatestNotFound(t *testing.T, newStore StoreFactory) {
s := newStore()
snap, err := s.Latest(context.Background(), "foo", uuid.New())
if snap != nil {
t.Errorf("Latest should return no Snapshot; got %v", snap)
}
if err == nil {
t.Errorf("Latest should fail; got %q", err)
}
}
func testVersion(t *testing.T, newStore StoreFactory) {
s := newStore()
id := uuid.New()
a10 := &snapshotter{Base: aggregate.New("foo", id, aggregate.Version(10))}
a20 := &snapshotter{Base: aggregate.New("foo", id, aggregate.Version(20))}
snap10, _ := snapshot.New(a10)
snap20, _ := snapshot.New(a20)
if err := s.Save(context.Background(), snap10); err != nil {
t.Fatalf("failed to save Snapshot: %v", err)
}
if err := s.Save(context.Background(), snap20); err != nil {
t.Fatalf("failed to save Snapshot: %v", err)
}
snap, err := s.Version(context.Background(), "foo", id, 10)
if err != nil {
t.Fatalf("Version shouldn't fail; failed with %q", err)
}
if snap.AggregateVersion() != snap10.AggregateVersion() {
t.Errorf(
"Version should return Snapshot with version %d; got version %d",
snap10.AggregateVersion(),
snap.AggregateVersion(),
)
}
}
func testVersionNotFound(t *testing.T, newStore StoreFactory) {
s := newStore()
snap, err := s.Version(context.Background(), "foo", uuid.New(), 10)
if snap != nil {
t.Errorf("Version should return no Snapshot; got %v", snap)
}
if err == nil {
t.Errorf("Version should fail; got %q", err)
}
}
func testLimit(t *testing.T, newStore StoreFactory) {
run(t, "Basic", testLimitBasic, newStore)
run(t, "NotFound", testLimitNotFound, newStore)
}
func testLimitBasic(t *testing.T, newStore StoreFactory) {
s := newStore()
id := uuid.New()
as := []aggregate.Aggregate{
&snapshotter{Base: aggregate.New("foo", id, aggregate.Version(1))},
&snapshotter{Base: aggregate.New("foo", id, aggregate.Version(5))},
&snapshotter{Base: aggregate.New("foo", id, aggregate.Version(10))},
&snapshotter{Base: aggregate.New("foo", id, aggregate.Version(20))},
}
snaps := makeSnaps(as)
for _, snap := range snaps {
if err := s.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
}
snap, err := s.Limit(context.Background(), "foo", id, 19)
if err != nil {
t.Fatalf("Limit shouldn't fail; failed with %q", err)
}
if snap.AggregateVersion() != 10 {
t.Errorf("Limit should return the Snapshot with version %d; got version %d", 10, snap.AggregateVersion())
}
}
func testLimitNotFound(t *testing.T, newStore StoreFactory) {
s := newStore()
id := uuid.New()
as := []aggregate.Aggregate{
&snapshotter{Base: aggregate.New("foo", id, aggregate.Version(10))},
&snapshotter{Base: aggregate.New("foo", id, aggregate.Version(20))},
}
snaps := makeSnaps(as)
for _, snap := range snaps {
if err := s.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
}
snap, err := s.Limit(context.Background(), "foo", id, 9)
if err == nil {
t.Errorf("Limit should fail!")
}
if snap != nil {
t.Errorf("Limit should return no Snapshot; got %v", snap)
}
}
func testQuery(t *testing.T, newStore StoreFactory) {
run(t, "Name", testQueryName, newStore)
run(t, "ID", testQueryID, newStore)
run(t, "Version", testQueryVersion, newStore)
run(t, "Time", testQueryTime, newStore)
run(t, "Sorting", testQuerySorting, newStore)
}
func testQueryName(t *testing.T, newStore StoreFactory) {
s := newStore()
foos, _ := xaggregate.Make(5, xaggregate.Name("foo"))
bars, _ := xaggregate.Make(5, xaggregate.Name("bar"))
for i, foo := range foos {
id, name, _ := foo.Aggregate()
foos[i] = &snapshotter{Base: aggregate.New(name, id)}
}
for i, bar := range bars {
id, name, _ := bar.Aggregate()
bars[i] = &snapshotter{Base: aggregate.New(name, id)}
}
fooSnaps := makeSnaps(foos)
barSnaps := makeSnaps(bars)
snaps := append(fooSnaps, barSnaps...)
for _, snap := range snaps {
if err := s.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
}
result, err := runQuery(s, query.New(query.Name("foo")))
if err != nil {
t.Fatal(err)
}
assertSame(t, fooSnaps, result)
}
func testQueryID(t *testing.T, newStore StoreFactory) {
s := newStore()
as, _ := xaggregate.Make(5, xaggregate.Name("foo"))
for i, a := range as {
id, name, _ := a.Aggregate()
as[i] = &snapshotter{Base: aggregate.New(name, id)}
}
snaps := makeSnaps(as)
for _, snap := range snaps {
if err := s.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
}
result, err := runQuery(s, query.New(query.ID(
aggregate.ExtractID(as[0]),
aggregate.ExtractID(as[4]),
)))
if err != nil {
t.Fatal(err)
}
assertSame(t, []snapshot.Snapshot{
snaps[0],
snaps[4],
}, result)
}
func testQueryVersion(t *testing.T, newStore StoreFactory) {
s := newStore()
as := []aggregate.Aggregate{
&snapshotter{Base: aggregate.New("foo", uuid.New(), aggregate.Version(1))},
&snapshotter{Base: aggregate.New("foo", uuid.New(), aggregate.Version(5))},
&snapshotter{Base: aggregate.New("foo", uuid.New(), aggregate.Version(10))},
}
snaps := makeSnaps(as)
for _, snap := range snaps {
if err := s.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
}
result, err := runQuery(s, query.New(
query.Version(version.Exact(1, 10)),
))
if err != nil {
t.Fatal(err)
}
assertSame(t, []snapshot.Snapshot{
snaps[0],
snaps[2],
}, result)
}
func testQueryTime(t *testing.T, newStore StoreFactory) {
s := newStore()
as := []aggregate.Aggregate{
&snapshotter{Base: aggregate.New("foo", uuid.New())},
&snapshotter{Base: aggregate.New("foo", uuid.New())},
&snapshotter{Base: aggregate.New("foo", uuid.New())},
}
snaps := make([]snapshot.Snapshot, len(as))
for i := range as {
var err error
var opts []snapshot.Option
if i == 2 {
opts = append(opts, snapshot.Time(xtime.Now().Add(-stdtime.Minute)))
}
if snaps[i], err = snapshot.New(as[i], opts...); err != nil {
t.Fatalf("failed to make Snapshot: %v", err)
}
}
for _, snap := range snaps {
if err := s.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
}
result, err := runQuery(s, query.New(
query.Time(time.After(xtime.Now().Add(-stdtime.Second))),
))
if err != nil {
t.Fatal(err)
}
assertSame(t, snaps[:2], result)
}
func testQuerySorting(t *testing.T, newStore StoreFactory) {
ids := make([]uuid.UUID, 9)
for i := range ids {
ids[i] = uuid.New()
}
sort.Slice(ids, func(a, b int) bool {
return ids[a].String() < ids[b].String()
})
as := []aggregate.Aggregate{
&snapshotter{Base: aggregate.New("bar1", ids[0], aggregate.Version(1))},
&snapshotter{Base: aggregate.New("bar2", ids[1], aggregate.Version(2))},
&snapshotter{Base: aggregate.New("bar3", ids[2], aggregate.Version(3))},
&snapshotter{Base: aggregate.New("baz1", ids[3], aggregate.Version(4))},
&snapshotter{Base: aggregate.New("baz2", ids[4], aggregate.Version(5))},
&snapshotter{Base: aggregate.New("baz3", ids[5], aggregate.Version(6))},
&snapshotter{Base: aggregate.New("foo1", ids[6], aggregate.Version(7))},
&snapshotter{Base: aggregate.New("foo2", ids[7], aggregate.Version(8))},
&snapshotter{Base: aggregate.New("foo3", ids[8], aggregate.Version(9))},
}
snaps := makeSnaps(as)
tests := []struct {
name string
q query.Query
want []snapshot.Snapshot
}{
{
name: "SortAggregateName(asc)",
q: query.New(query.SortBy(aggregate.SortName, aggregate.SortAsc)),
want: snaps,
},
{
name: "SortAggregateName(desc)",
q: query.New(query.SortBy(aggregate.SortName, aggregate.SortDesc)),
want: []snapshot.Snapshot{
snaps[8], snaps[7], snaps[6],
snaps[5], snaps[4], snaps[3],
snaps[2], snaps[1], snaps[0],
},
},
{
name: "SortAggregateID(asc)",
q: query.New(query.SortBy(aggregate.SortID, aggregate.SortAsc)),
want: snaps,
},
{
name: "SortAggregateID(desc)",
q: query.New(query.SortBy(aggregate.SortID, aggregate.SortDesc)),
want: []snapshot.Snapshot{
snaps[8], snaps[7], snaps[6],
snaps[5], snaps[4], snaps[3],
snaps[2], snaps[1], snaps[0],
},
},
{
name: "SortAggregateVersion(asc)",
q: query.New(query.SortBy(aggregate.SortVersion, aggregate.SortAsc)),
want: snaps,
},
{
name: "SortAggregateVersion(desc)",
q: query.New(query.SortBy(aggregate.SortVersion, aggregate.SortDesc)),
want: []snapshot.Snapshot{
snaps[8], snaps[7], snaps[6],
snaps[5], snaps[4], snaps[3],
snaps[2], snaps[1], snaps[0],
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := newStore()
for _, snap := range snaps {
if err := store.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
}
result, err := runQuery(store, tt.q)
if err != nil {
t.Fatalf("query failed with %q", err)
}
assertEqual(t, tt.want, result)
})
}
}
func testDelete(t *testing.T, newStore StoreFactory) {
s := newStore()
a := &snapshotter{Base: aggregate.New("foo", uuid.New())}
snap, _ := snapshot.New(a)
if err := s.Save(context.Background(), snap); err != nil {
t.Fatalf("Save shouldn't fail; failed with %q", err)
}
if err := s.Delete(context.Background(), snap); err != nil {
t.Fatalf("Delete shouldn't fail; failed with %q", err)
}
snap, err := s.Latest(context.Background(), a.AggregateName(), a.AggregateID())
if err == nil {
t.Errorf("Latest should fail with an error; got %q", err)
}
if snap != nil {
t.Errorf("Latest shouldn't return a Snapshot; got %v", snap)
}
}
func runQuery(s snapshot.Store, q snapshot.Query) ([]snapshot.Snapshot, error) {
str, errs, err := s.Query(context.Background(), q)
if err != nil {
return nil, fmt.Errorf("expected store.Query to succeed; got %w", err)
}
return snapshot.Drain(context.Background(), str, errs)
}
func makeSnaps(as []aggregate.Aggregate) []snapshot.Snapshot {
snaps := make([]snapshot.Snapshot, len(as))
for i, a := range as {
snap, err := snapshot.New(a)
if err != nil {
panic(err)
}
snaps[i] = snap
}
return snaps
}
func assertEqual(t *testing.T, want, got []snapshot.Snapshot) {
if len(want) != len(got) {
t.Fatalf("(len(want) == %d) != (len(got) == %d)", len(want), len(got))
}
for i, snap := range want {
gs := got[i]
if snap.AggregateName() != gs.AggregateName() {
t.Errorf(
"want[%d].AggregateName() == %q; got[%d].AggregateName() == %q",
i,
snap.AggregateName(),
i,
gs.AggregateName(),
)
}
if snap.AggregateID() != gs.AggregateID() {
t.Errorf(
"want[%d].AggregateID() == %s; got[%d].AggregateID() == %s",
i,
snap.AggregateID(),
i,
gs.AggregateID(),
)
}
if snap.AggregateVersion() != gs.AggregateVersion() {
t.Errorf(
"want[%d].AggregateVersion() == %d; got[%d].AggregateVersion() == %d",
i,
snap.AggregateVersion(),
i,
gs.AggregateVersion(),
)
}
}
}
func assertSame(t *testing.T, want, got []snapshot.Snapshot) {
sort.Slice(want, func(a, b int) bool {
return want[a].AggregateID().String() <= want[b].AggregateID().String()
})
sort.Slice(got, func(a, b int) bool {
return got[a].AggregateID().String() <= got[b].AggregateID().String()
})
assertEqual(t, want, got)
}
type snapshotter struct {
*aggregate.Base
state state
}
type state struct {
Foo int
}
func (ss *snapshotter) MarshalSnapshot() ([]byte, error) {
return json.Marshal(ss.state)
}
func (ss *snapshotter) UnmarshalSnapshot(b []byte) error {
return json.Unmarshal(b, &ss.state)
}
|
Apparently the author of The Hundred and One Dalmatians wrote a sequel some 12 years later, which has been largely forgotten by the public, but I recently learned of its existence when I was picking up Dodie Smith's first Dalmatian book at the library, and thought it might be fun to have a double feature. That seems to have been a poor decision. While the first book is charming and exciting, a delightful animal rescue story about family and courage and becoming more than you think you are, the s
Apparently the author of The Hundred and One Dalmatians wrote a sequel some 12 years later, which has been largely forgotten by the public, but I recently learned of its existence when I was picking up Dodie Smith's first Dalmatian book at the library, and thought it might be fun to have a double feature. That seems to have been a poor decision. While the first book is charming and exciting, a delightful animal rescue story about family and courage and becoming more than you think you are, the sequel takes a major turn in style and content and tells a completely different story.
It was nice at the start to pick up in the years following the events of the first book, getting reacquainted with Pongo, Missis, and their "Dynasty of Dalmatians," but by the end of the first chapter, things get pretty wonky. The mystery is intriguing enough at the start--every living creature except for dogs (and some non-living entities, such as the wind) seems to have fallen under some kind of enchantment causing them not to wake up. It's then up to the dogs to discover the source of this curious turn of events, and it just gets more bizarre from there. Later developments include mind-reading across hundreds of miles, doors opening by themselves, no feelings of hunger, thirst or fatigue, traveling at great speeds without touching the ground (a phenomenon they call "swooshing"), and a strange interaction at Trafalfar Square with an other-worldly dog from outer space (who first communicates with them through a glowing television set) who has a plan that threatens the society and future of the world's population of dogs. It was fun to read about the sort of social structure and government of dogs (largely relative to their human counterparts), but all the charm is lost in the mystical and odd fantasy of it. While the universe and the peril of the first novel were firmly grounded and rooted in reality, the sequel takes things to a very odd level. I gave it ()barely) two stars because the writing was still charming, and some of the characters uttered rather profound statements at times (especially Missis, who seems to really have grown up since her naive days as a new mother, and Cadpig, one of the original fifteen puppies who has by now taken up residence with the Prime Minister, and now acts in that capacity in dog society), but it's hard to care when the surrounding events are so silly. There were some really contrived plot points that seemed to have been arbitrarily included to add interest and help propel the story, and a lot of the story seemed a little bit too (to use a word that becomes a recurring theme throughout the book) metaphysical. I like my English Dalmatians a little more believable. For a moment it seemed like there were going to be some interesting references or parallels to religion and God, as there were in the first book, but then they went a totally different direction and just became pseudo-religious mumbo-jumbo instead. And then, for good measure, why not throw in a muddled message about the evils of war and the hopelessness in the good of mankind?
This might just be one of the weirdest books I've ever read. One good thing that can be said about this book is that it's a pretty quick read. The bottom line: There is some nice writing, and some of the great characters return in Dodie Smith's continuation of the Dalmatian saga, but there are a LOT of reasons this is (and probably should have remained) a "long-forgotten sequel". I guess we can all be grateful that none of the film sequels have used this book as inspiration for story. Yikes. |
import "../src/globalUtils"
import assert = require("assert");
import {List} from "../src/Interface";
import {ArrayList} from "../src/ArrayList";
// equals
assert.strictEqual("abc".equals("abc"), true);
assert.strictEqual("abc".equals("bc"), false);
assert.strictEqual("abc".equals(null), false);
// Number
assert.strictEqual(Number(10).equals(10), true);
assert.strictEqual(Number(10).equals(99), false);
assert.strictEqual(Number(10).equals(null), false);
// Boolean
assert.strictEqual(Boolean(true).equals(true), true);
assert.strictEqual(Boolean(false).equals(false), true);
assert.strictEqual(Boolean(false).equals(null), false);
assert.strictEqual(Boolean(false).equals(true), false);
assert.strictEqual(Boolean(true).equals(false), false);
// equalsIgnoreCase
assert.strictEqual("abc".equalsIgnoreCase("abC"), true);
assert.strictEqual("AbC".equalsIgnoreCase("abc"), true);
assert.strictEqual("abc".equalsIgnoreCase("bC"), false);
assert.strictEqual("abc".equalsIgnoreCase(null), false);
// equalsIgnoreCase
assert.strictEqual("abc".equalsIgnoreCase("abC"), true);
assert.strictEqual("AbC".equalsIgnoreCase("abc"), true);
assert.strictEqual("abc".equalsIgnoreCase("bC"), false);
assert.strictEqual("abc".equalsIgnoreCase(null), false);
// repeatString
assert.strictEqual(String.repeatString("0",5).length, 5);
assert.strictEqual(String.repeatString("0",0).length, 0);
try{
// !!defect!!
assert.strictEqual(String.repeatString("0",-1).length, 0);
}catch (e){
assert.strictEqual(false,true);
}
// equals
assert.strictEqual("abc".contains("abc"), true);
assert.strictEqual("abc".contains(/b/), true);
assert.strictEqual("abc".contains(null), false);
// isEmpty
assert.strictEqual("".isEmpty(), true);
assert.strictEqual("abc".isEmpty(), false);
// explodeAsList
let exploder:List<string> = "foo;bar;123;4".explodeAsList(";");
assert.strictEqual(exploder instanceof ArrayList, true);
assert.strictEqual(exploder.size(), 4);
// orDefault
assert.strictEqual("abc".orDefault("foo"), "abc");
assert.strictEqual("".orDefault("foo"), "foo");
console.log("".contains(null))
//assert.strictEqual("".contains(null), "");
// compareTo
assert.strictEqual("abc".compareTo("foo"), -5);
assert.strictEqual("".compareTo("foo"), -3);
// AsList
assert.strictEqual((Array.asList(["a","b","c"])) instanceof ArrayList, true);
assert.strictEqual(Array.newList<string>("a","b","c").size(), 3);
// Number
assert.strictEqual(Number.of("4"), 4);
assert.strictEqual(Number.of("10.00"), 10);
assert.strictEqual(Number.of(null), NaN);
// requireNotNull
let control:boolean = false;
try{
Object.requireNotNull(null,"messsage");
}catch (e){
control=true;
}
assert.strictEqual(control, true);
control = true;
try{
Object.requireNotNull({},"messsage");
}catch (e){
control=false;
}
assert.strictEqual(control, true);
///
class Test{
private c:number;
private b:string;
constructor() {
}
public getC():void{
}
}
class des{
private a:string = "fooBar";
constructor() {
}
public toString():string{
return "[ a = "+this.a+" ]";
}
}
console.log((new Test()).toString(), "/", Object.toString(new Test()));
console.log( [new Test(), new des()].toString());
console.log(Array.newList<string>("a","b","c").toString())
console.log(Array.newList<Test>(new Test(),new Test(),new Test(),new Test(),new Test(),new Test(),new Test(),new Test()).toString()); |
// /Main application frame that hosts the main window.
public class Application extends JFrame implements GameFinishListener
{
/**
*
*/
private static final long serialVersionUID = 754390673491159252L;
JTextField width_input = new JTextField("16", 3);
JTextField height_input = new JTextField("30", 3);
JTextField mines_input = new JTextField("99", 5);
GuiTimeCounter counter = new GuiTimeCounter();
HighscoreManager manager;
Board board;
public Application(HighscoreManager manager)
{
this.manager = manager;
setTitle("Minesweeper");
JPanel control = new JPanel();
control.add(new JLabel("W:"));
control.add(width_input);
control.add(new JLabel("H:"));
control.add(height_input);
control.add(new JLabel("M:"));
control.add(mines_input);
JButton button = new JButton("Reset");
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
makeBoard();
}
});
control.add(button);
getContentPane().add(control, BorderLayout.WEST);
getContentPane().add(counter, BorderLayout.EAST);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
/// Destroy any previous board and set up a new one with the current properties.
public void makeBoard()
{
if(board != null) // We have an active board
{
getContentPane().remove(board);
board = null;
}
try
{
int width = Integer.parseInt(width_input.getText());
int height = Integer.parseInt(height_input.getText());
int mines = Integer.parseInt(mines_input.getText());
board = new Board(new GameDimensions(width, height, mines), this);
}
catch (Exception e)
{
// Erroneous user input, ignore whatever exception we got
}
finally
{
getContentPane().add(board, BorderLayout.SOUTH);
counter.reset();
counter.start();
}
pack();
}
/// Our current board's callback about the user winning or losing.
@Override
public void gameFinished(boolean won, GameDimensions dims)
{
counter.stop();
int score = counter.getSeconds();
if(won && manager.isScoreHighscore(dims, score)) // User scored a highscore, ask for their name
new HighscoreNameEntryFrame(dims, score, manager);
else // User lost or didn't have a top score, just show the highscore board
new HighscoreFrame(manager.getHighscores(dims));
}
/// Entry point.
public static void main(String[] args)
{
Application app = new Application(new FileBackedHighscoreManager("top.dat"));
app.makeBoard();
}
} |
<filename>experimental/portappb/src/main/java/com/com619/group6/startup/views/EditPortService.java
package com.com619.group6.startup.views;
import com.com619.group6.jpadao.DaoFactoryJpa;
import com.com619.group6.model.PortService;
import com.com619.group6.model.ServiceType;
import com.com619.group6.model.dao.PortServiceDao;
import com.com619.group6.model.dao.DaoFactory;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.*;
@Route("/port-service/edit/:portServiceId")
public class EditPortService extends Div implements RouterLayout, BeforeEnterObserver {
PortServiceDao portServiceDao;
PortService originalPortService;
private long portServiceId;
TextField idField = new TextField();
//TextField nameField = new TextField();
TextField serviceTypeField = new TextField();
NumberField costField = new NumberField();
@Override
public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
final RouteParameters urlParameters = beforeEnterEvent.getRouteParameters();
portServiceId = Long.parseLong(urlParameters.get("portServiceId").get());
DaoFactory factory = new DaoFactoryJpa();
portServiceDao = factory.getPortServiceDao();
originalPortService = portServiceDao.getOne(portServiceId);
idField.setValue(String.valueOf(originalPortService.getId()));
idField.setReadOnly(true);
//nameField.setValue(originalPortService.getName());
ServiceType pst = originalPortService.getServiceType();
if (pst != null) {
serviceTypeField.setValue(originalPortService.getServiceType().toString());
}
costField.setValue(originalPortService.getCost());
FormLayout formLayout = new FormLayout();
formLayout.addFormItem(idField, "ID");
//formLayout.addFormItem(nameField, "Name");
formLayout.addFormItem(serviceTypeField, "ServiceType");
formLayout.addFormItem(costField, "Cost");
add(formLayout, getActionButtons());
}
private HorizontalLayout getActionButtons() {
Button saveButton = new Button("Save");
Button cancelButton = new Button("Cancel");
cancelButton.addClickListener(e -> cancelButton.getUI().ifPresent(ui -> {
ui.navigate("port-services");
}));
saveButton.addClickListener(e -> saveButton.getUI().ifPresent(ui -> {
saveChanges();
UI.getCurrent().navigate("/port-services");
}));
HorizontalLayout buttons = new HorizontalLayout(saveButton, cancelButton);
buttons.addClassName("action-buttons");
return buttons;
}
private void saveChanges() {
PortService updatedPortService = new PortService();
updatedPortService.setId(originalPortService.getId());
//updatedPortService.setName(nameField.getValue());
//updatedPortService.setServiceType(serviceTypeField.getValue());
updatedPortService.setCost(costField.getValue());
portServiceDao.update(updatedPortService);
}
}
|
Double-field orientation of unity power factor synchronous motor drive
There is proposed a vector control structure for wound-excited synchronous motor drives fed by voltage-source inverter with feed-forward voltage pulse-width modulation, working at unity power factor, which combines the advantages of two types of field-orientation procedure, i.e. stator-field orientation and control for power factor control, and rotor-position- or exciting field-orientation for generating the voltage control variables and self-commutation. |
<reponame>timyinshi/openyurt<filename>pkg/yurtctl/cmd/convert/convert.go
/*
Copyright 2020 The OpenYurt Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package convert
import (
"errors"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
appsv1 "k8s.io/api/apps/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/klog"
"github.com/alibaba/openyurt/pkg/yurtctl/constants"
"github.com/alibaba/openyurt/pkg/yurtctl/lock"
kubeutil "github.com/alibaba/openyurt/pkg/yurtctl/util/kubernetes"
strutil "github.com/alibaba/openyurt/pkg/yurtctl/util/strings"
tmpltil "github.com/alibaba/openyurt/pkg/yurtctl/util/templates"
)
// Provider signifies the provider type
type Provider string
const (
// ProviderMinikube is used if the target kubernetes is run on minikube
ProviderMinikube Provider = "minikube"
// ProviderACK is used if the target kubernetes is run on ack
ProviderACK Provider = "ack"
)
// ConvertOptions has the information that required by convert operation
type ConvertOptions struct {
clientSet *kubernetes.Clientset
CloudNodes []string
Provider Provider
YurhubImage string
YurtControllerManagerImage string
YurctlServantImage string
}
// NewConvertOptions creates a new ConvertOptions
func NewConvertOptions() *ConvertOptions {
return &ConvertOptions{}
}
// NewConvertCmd generates a new convert command
func NewConvertCmd() *cobra.Command {
co := NewConvertOptions()
cmd := &cobra.Command{
Use: "convert -c CLOUDNODES",
Short: "Converts the kubernetes cluster to a yurt cluster",
Run: func(cmd *cobra.Command, _ []string) {
if err := co.Complete(cmd.Flags()); err != nil {
klog.Fatalf("fail to complete the convert option: %s", err)
}
if err := co.Validate(); err != nil {
klog.Fatalf("convert option is invalid: %s", err)
}
if err := co.RunConvert(); err != nil {
klog.Fatalf("fail to convert kubernetes to yurt: %s", err)
}
},
}
cmd.Flags().StringP("cloud-nodes", "c", "",
"The list of cloud nodes.(e.g. -c cloudnode1,cloudnode2)")
cmd.Flags().StringP("provider", "p", "ack",
"The provider of the original Kubernetes cluster.")
cmd.Flags().String("yurthub-image",
"openyurt/yurthub:latest",
"The yurthub image.")
cmd.Flags().String("yurt-controller-manager-image",
"openyurt/yurt-controller-manager:latest",
"The yurt-controller-manager image.")
cmd.Flags().String("yurtctl-servant-image",
"openyurt/yurtctl-servant:latest",
"The yurtctl-servant image.")
return cmd
}
// Complete completes all the required options
func (co *ConvertOptions) Complete(flags *pflag.FlagSet) error {
cnStr, err := flags.GetString("cloud-nodes")
if err != nil {
return err
}
co.CloudNodes = strings.Split(cnStr, ",")
pStr, err := flags.GetString("provider")
if err != nil {
return err
}
co.Provider = Provider(pStr)
yhi, err := flags.GetString("yurthub-image")
if err != nil {
return err
}
co.YurhubImage = yhi
ycmi, err := flags.GetString("yurt-controller-manager-image")
if err != nil {
return err
}
co.YurtControllerManagerImage = ycmi
ycsi, err := flags.GetString("yurtctl-servant-image")
if err != nil {
return err
}
co.YurctlServantImage = ycsi
// parse kubeconfig and generate the clientset
co.clientSet, err = kubeutil.GenClientSet(flags)
if err != nil {
return err
}
return nil
}
// Validate makes sure provided values for ConvertOptions are valid
func (co *ConvertOptions) Validate() error {
if co.Provider != ProviderMinikube &&
co.Provider != ProviderACK {
return fmt.Errorf("unknown provider: %s, valid providers are: minikube, ack",
co.Provider)
}
return nil
}
// RunConvert performs the conversion
func (co *ConvertOptions) RunConvert() (err error) {
if err = lock.AcquireLock(co.clientSet); err != nil {
return
}
defer func() {
if releaseLockErr := lock.ReleaseLock(co.clientSet); releaseLockErr != nil {
klog.Error(releaseLockErr)
}
}()
klog.V(4).Info("successfully acquire the lock")
// 1. check the server version
if err = kubeutil.ValidateServerVersion(co.clientSet); err != nil {
return
}
klog.V(4).Info("the server version is valid")
// 2. label nodes as cloud node or edge node
nodeLst, err := co.clientSet.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
return
}
var edgeNodeNames []string
for _, node := range nodeLst.Items {
if strutil.IsInStringLst(co.CloudNodes, node.GetName()) {
// label node as cloud node
klog.Infof("mark %s as the cloud-node", node.GetName())
if _, err = kubeutil.LabelNode(co.clientSet,
&node, constants.LabelEdgeWorker, "false"); err != nil {
return
}
continue
}
// label node as edge node
klog.Infof("mark %s as the edge-node", node.GetName())
edgeNodeNames = append(edgeNodeNames, node.GetName())
_, err = kubeutil.LabelNode(co.clientSet,
&node, constants.LabelEdgeWorker, "true")
if err != nil {
return
}
}
// 3. deploy yurt controller manager
ycmdp, err := tmpltil.SubsituteTemplate(constants.YurtControllerManagerDeployment,
map[string]string{"image": co.YurtControllerManagerImage})
if err != nil {
return
}
dpObj, err := kubeutil.YamlToObject([]byte(ycmdp))
if err != nil {
return
}
ecmDp, ok := dpObj.(*appsv1.Deployment)
if !ok {
err = errors.New("fail to assert YurtControllerManagerDeployment")
return
}
if _, err = co.clientSet.AppsV1().Deployments("kube-system").Create(ecmDp); err != nil {
return
}
klog.Info("deploy the yurt controller manager")
// 4. delete the node-controller service account to disable node-controller
if err = co.clientSet.CoreV1().ServiceAccounts("kube-system").
Delete("node-controller", &metav1.DeleteOptions{
PropagationPolicy: &kubeutil.PropagationPolicy,
}); err != nil && !apierrors.IsNotFound(err) {
klog.Errorf("fail to delete ServiceAccount(node-controller): %s", err)
return
}
// 5. deploy yurt-hub and reset the kubelet service
klog.Infof("deploying the yurt-hub and resetting the kubelet service...")
if err = kubeutil.RunServantJobs(co.clientSet, map[string]string{
"provider": string(co.Provider),
"action": "convert",
"yurtctl_servant_image": co.YurctlServantImage,
"yurthub_image": co.YurhubImage,
}, edgeNodeNames); err != nil {
klog.Errorf("fail to run ServantJobs: %s", err)
return
}
return
}
|
“No promo homo” states are those that prohibit educators from discussing homosexuality in a positive way or, in some cases, at all. States that prohibit enumeration are those that don’t allow local school districts from enacting policies aimed specifically at preventing bullying over sexual orientation or gender identity. ( Gay, Lesbian & Straight Education Network
Eight states limit speech about homosexuality in ways similar to, though not as far-reaching as, the Russian ban that has received international criticism ahead of the Winter Olympics in Sochi.
The states have so-called “no promo homo” bans—prohibitions on classroom instruction that promotes homosexuality. In a Washington Post opinion piece last week, a pair of Yale University law professors reviewed some of those laws:
It is Utah that prohibits “the advocacy of homosexuality.” Arizona prohibits portrayals of homosexuality as a “positive alternative life-style” and has legislatively determined that it is inappropriate to even suggest to children that there are “safe methods of homosexual sex.” Alabama and Texas mandate that sex-education classes emphasize that homosexuality is “not a lifestyle acceptable to the general public.” Moreover, the Alabama and Texas statutes mandate that children be taught that “homosexual conduct is a criminal offense” even though criminalizing private, consensual homosexual conduct has been unconstitutional since 2003.
The professors, Ian Ayres and William Eskridge, point out that in 2002 the United States hosted the Winter Olympics in Utah, one of the eight states, and argue that those criticizing Russia should also focus on changing the similar domestic laws.
The eight states that have such prohibitions in place are Alabama, Arizona, Louisiana, Mississippi, Oklahoma, South Carolina, Texas and Utah, according to the Gay, Lesbian & Straight Education Network. |
// Fix if info and loop info for the given sc.
void
CFG::Fix_info(SC_NODE * sc)
{
SC_NODE * sc_tmp;
BB_NODE * bb_tmp;
BB_LIST_ITER bb_list_iter;
SC_TYPE type = sc->Type();
if (type == SC_IF) {
BB_NODE * bb_head = sc->Head();
BB_IFINFO * ifinfo = bb_head->Ifinfo();
sc_tmp = sc->Find_kid_of_type(SC_THEN);
ifinfo->Set_then(sc_tmp->First_bb());
sc_tmp = sc->Find_kid_of_type(SC_ELSE);
ifinfo->Set_else(sc_tmp->First_bb());
sc_tmp = sc->Next_sibling();
ifinfo->Set_merge(sc_tmp->First_bb());
}
else if (type == SC_LOOP) {
BB_LOOP * loop = sc->Loopinfo();
sc_tmp = sc->Find_kid_of_type(SC_LP_BODY);
if (sc_tmp)
loop->Set_body(sc_tmp->First_bb());
sc_tmp = sc->Find_kid_of_type(SC_LP_STEP);
if (sc_tmp)
loop->Set_step(sc_tmp->First_bb());
sc_tmp = sc->Find_kid_of_type(SC_LP_START);
if (sc_tmp)
loop->Set_start(sc_tmp->First_bb());
sc_tmp = sc->Find_kid_of_type(SC_LP_COND);
if (sc_tmp)
loop->Set_end(sc_tmp->First_bb());
sc_tmp = sc->Next_sibling();
if (sc_tmp)
loop->Set_merge(sc_tmp->First_bb());
else {
sc_tmp = sc->Find_kid_of_type(SC_LP_COND);
if (sc_tmp) {
FOR_ALL_ELEM(bb_tmp, bb_list_iter, Init(sc_tmp->Last_bb()->Succ())) {
if (!sc->Contains(bb_tmp)) {
loop->Set_merge(bb_tmp);
break;
}
}
}
}
}
} |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.memory.ui;
import com.intellij.debugger.DebuggerManager;
import com.intellij.debugger.engine.*;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.debugger.memory.component.MemoryViewDebugProcessData;
import com.intellij.debugger.memory.tracking.ConstructorInstancesTracker;
import com.intellij.debugger.memory.tracking.TrackerForNewInstances;
import com.intellij.debugger.memory.utils.AndroidUtil;
import com.intellij.debugger.memory.utils.LowestPriorityCommand;
import com.intellij.debugger.requests.ClassPrepareRequestor;
import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.DoubleClickListener;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XDebugSessionListener;
import com.intellij.xdebugger.XDebuggerManager;
import com.intellij.xdebugger.frame.XSuspendContext;
import com.intellij.xdebugger.memory.component.InstancesTracker;
import com.intellij.xdebugger.memory.event.InstancesTrackerListener;
import com.intellij.xdebugger.memory.tracking.TrackingType;
import com.intellij.xdebugger.memory.ui.ClassesFilteredViewBase;
import com.intellij.xdebugger.memory.ui.ClassesTable;
import com.intellij.xdebugger.memory.ui.InstancesWindowBase;
import com.intellij.xdebugger.memory.ui.TypeInfo;
import com.intellij.xdebugger.memory.utils.InstancesProvider;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.request.ClassPrepareRequest;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.intellij.xdebugger.memory.ui.ClassesTable.DiffViewTableModel.CLASSNAME_COLUMN_INDEX;
import static com.intellij.xdebugger.memory.ui.ClassesTable.DiffViewTableModel.DIFF_COLUMN_INDEX;
public class ClassesFilteredView extends ClassesFilteredViewBase {
private static final Logger LOG = Logger.getInstance(ClassesFilteredView.class);
public static final DataKey<InstancesProvider> NEW_INSTANCES_PROVIDER_KEY =
DataKey.create("ClassesTable.NewInstances");
private final InstancesTracker myInstancesTracker;
/**
* Indicates that the debug session had been stopped at least once.
* <p>
* State: false to true
*/
private final AtomicBoolean myIsTrackersActivated = new AtomicBoolean(false);
private final Map<ReferenceType, ConstructorInstancesTracker> myConstructorTrackedClasses = new ConcurrentHashMap<>();
private final XDebugSessionListener additionalSessionListener;
public ClassesFilteredView(@NotNull XDebugSession debugSession, @NotNull DebugProcessImpl debugProcess, @NotNull InstancesTracker tracker) {
super(debugSession);
final DebuggerManagerThreadImpl managerThread = debugProcess.getManagerThread();
myInstancesTracker = tracker;
final InstancesTrackerListener instancesTrackerListener = new InstancesTrackerListener() {
@Override
public void classChanged(@NotNull String name, @NotNull TrackingType type) {
ClassesTable table = getTable();
TypeInfo typeInfo = table.getClassByName(name);
if (typeInfo == null)
return;
ReferenceType ref = ((JavaTypeInfo) typeInfo).getReferenceType();
if (ref != null) {
final boolean activated = myIsTrackersActivated.get();
managerThread.schedule(new DebuggerCommandImpl() {
@Override
protected void action() {
trackClass(debugSession, debugProcess, ref, type, activated);
}
});
}
table.repaint();
}
@Override
public void classRemoved(@NotNull String name) {
ClassesTable table = getTable();
TypeInfo ref = table.getClassByName(name);
if (ref == null)
return;
JavaTypeInfo javaTypeInfo = (JavaTypeInfo) ref;
if (myConstructorTrackedClasses.containsKey(javaTypeInfo.getReferenceType())) {
ConstructorInstancesTracker removed = myConstructorTrackedClasses.remove(javaTypeInfo.getReferenceType());
Disposer.dispose(removed);
table.getRowSorter().allRowsChanged();
}
}
};
debugSession.addSessionListener(new XDebugSessionListener() {
@Override
public void sessionStopped() {
myInstancesTracker.removeTrackerListener(instancesTrackerListener);
}
});
debugProcess.addDebugProcessListener(new DebugProcessListener() {
@Override
public void processAttached(@NotNull DebugProcess process) {
debugProcess.removeDebugProcessListener(this);
managerThread.invoke(new DebuggerCommandImpl() {
@Override
protected void action() {
final boolean activated = myIsTrackersActivated.get();
final VirtualMachineProxyImpl proxy = debugProcess.getVirtualMachineProxy();
if (!proxy.canBeModified()) {
return;
}
tracker.getTrackedClasses().forEach((className, type) -> {
List<ReferenceType> classes = proxy.classesByName(className);
if (classes.isEmpty()) {
trackWhenPrepared(className, debugSession, debugProcess, type);
}
else {
for (ReferenceType ref : classes) {
trackClass(debugSession, debugProcess, ref, type, activated);
}
}
});
tracker.addTrackerListener(instancesTrackerListener);
}
});
}
private void trackWhenPrepared(@NotNull String className,
@NotNull XDebugSession session,
@NotNull DebugProcessImpl process,
@NotNull TrackingType type) {
final ClassPrepareRequestor request = new ClassPrepareRequestor() {
@Override
public void processClassPrepare(DebugProcess debuggerProcess, ReferenceType referenceType) {
process.getRequestsManager().deleteRequest(this);
trackClass(session, process, referenceType, type, myIsTrackersActivated.get());
}
};
final ClassPrepareRequest classPrepareRequest = process.getRequestsManager()
.createClassPrepareRequest(request, className);
if (classPrepareRequest != null) {
classPrepareRequest.enable();
}
else {
LOG.warn("Cannot create a 'class prepare' request. Class " + className + " not tracked.");
}
}
});
additionalSessionListener = new XDebugSessionListener() {
@Override
public void sessionResumed() {
myConstructorTrackedClasses.values().forEach(ConstructorInstancesTracker::obsolete);
}
@Override
public void sessionStopped() {
myConstructorTrackedClasses.values().forEach(Disposer::dispose);
myConstructorTrackedClasses.clear();
}
};
ClassesTable table = getTable();
table.addMouseMotionListener(new MyMouseMotionListener());
table.addMouseListener(new MyOpenNewInstancesListener());
new MyDoubleClickListener().installOn(table);
}
private void trackClass(@NotNull XDebugSession session,
@NotNull DebugProcessImpl debugProcess,
@NotNull ReferenceType ref,
@NotNull TrackingType type,
boolean isTrackerEnabled) {
DebuggerManagerThreadImpl.assertIsManagerThread();
if (!debugProcess.getVirtualMachineProxy().canBeModified()) {
return;
}
if (type == TrackingType.CREATION) {
final ConstructorInstancesTracker old = myConstructorTrackedClasses.getOrDefault(ref, null);
if (old != null) {
Disposer.dispose(old);
}
final ConstructorInstancesTracker tracker = new ConstructorInstancesTracker(ref, session, myInstancesTracker);
tracker.setBackgroundMode(!myIsActive);
if (isTrackerEnabled) {
tracker.enable();
}
else {
tracker.disable();
}
myConstructorTrackedClasses.put(ref, tracker);
}
}
@Override
protected void scheduleUpdateClassesCommand(XSuspendContext context) {
SuspendContextImpl suspendContext = (SuspendContextImpl) context;
suspendContext.getDebugProcess().getManagerThread().schedule(new MyUpdateClassesCommand(suspendContext));
}
@Nullable
@Override
protected TrackerForNewInstances getStrategy(@NotNull TypeInfo ref) {
JavaTypeInfo javaTypeInfo = (JavaTypeInfo) ref;
return myConstructorTrackedClasses.getOrDefault(javaTypeInfo.getReferenceType(), null);
}
@Override
protected InstancesWindowBase getInstancesWindow(@NotNull TypeInfo ref, XDebugSession debugSession) {
return new InstancesWindow(debugSession, limit -> ref.getInstances(limit), ref.name());
}
@Override
protected void doActivate() {
myConstructorTrackedClasses.values().forEach(x -> x.setBackgroundMode(false));
super.doActivate();
}
@Override
protected void doPause() {
super.doPause();
myConstructorTrackedClasses.values().forEach(x -> x.setBackgroundMode(true));
}
@Override
public void dispose() {
myConstructorTrackedClasses.clear();
}
@Override
public Object getData(@NotNull String dataId) {
if (NEW_INSTANCES_PROVIDER_KEY.is(dataId)) {
TypeInfo selectedClass = getTable().getSelectedClass();
if (selectedClass != null) {
TrackerForNewInstances strategy = getStrategy(selectedClass);
if (strategy != null && strategy.isReady()) {
List<ObjectReference> newInstances = strategy.getNewInstances();
return (InstancesProvider)limit -> ContainerUtil.map(newInstances, JavaReferenceInfo::new);
}
}
}
return null;
}
@Nullable
@Override
protected XDebugSessionListener getAdditionalSessionListener() {
return additionalSessionListener;
}
public void setActive(boolean active, @NotNull DebuggerManagerThreadImpl managerThread) {
if (myIsActive == active) {
return;
}
myIsActive = active;
managerThread.schedule(new DebuggerCommandImpl() {
@Override
protected void action() {
if (active) {
doActivate();
}
else {
doPause();
}
}
});
}
private void commitAllTrackers() {
myConstructorTrackedClasses.values().forEach(ConstructorInstancesTracker::commitTracked);
}
private boolean isShowNewInstancesEvent(@NotNull MouseEvent e) {
ClassesTable table = getTable();
final int col = table.columnAtPoint(e.getPoint());
final int row = table.rowAtPoint(e.getPoint());
if (col == -1 || row == -1 || table.convertColumnIndexToModel(col) != DIFF_COLUMN_INDEX) {
return false;
}
final int modelRow = table.convertRowIndexToModel(row);
final JavaTypeInfo ref = (JavaTypeInfo) table.getModel().getValueAt(modelRow, CLASSNAME_COLUMN_INDEX);
final ConstructorInstancesTracker tracker = myConstructorTrackedClasses.getOrDefault(ref.getReferenceType(), null);
return tracker != null && tracker.isReady() && tracker.getCount() > 0;
}
private class MyOpenNewInstancesListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() != 1 || e.getButton() != MouseEvent.BUTTON1 || !isShowNewInstancesEvent(e)) {
return;
}
TypeInfo selectedTypeInfo = getTable().getSelectedClass();
final ReferenceType ref = selectedTypeInfo != null ? ((JavaTypeInfo) selectedTypeInfo).getReferenceType(): null;
final TrackerForNewInstances strategy = ref == null ? null : getStrategy(selectedTypeInfo);
XDebugSession debugSession = XDebuggerManager.getInstance(myProject).getCurrentSession();
if (strategy != null && debugSession != null) {
final DebugProcess debugProcess =
DebuggerManager.getInstance(myProject).getDebugProcess(debugSession.getDebugProcess().getProcessHandler());
final MemoryViewDebugProcessData data = debugProcess.getUserData(MemoryViewDebugProcessData.KEY);
if (data != null) {
final List<ObjectReference> newInstances = strategy.getNewInstances();
data.getTrackedStacks().pinStacks(ref);
final InstancesWindow instancesWindow = new InstancesWindow(debugSession,
limit -> ContainerUtil.map(newInstances, JavaReferenceInfo::new), ref.name());
Disposer.register(instancesWindow.getDisposable(), () -> data.getTrackedStacks().unpinStacks(ref));
instancesWindow.show();
}
else {
LOG.warn("MemoryViewDebugProcessData not found in debug session user data");
}
}
}
}
private class MyMouseMotionListener implements MouseMotionListener {
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
ClassesTable table = getTable();
if (table.isInClickableMode()) return;
if (isShowNewInstancesEvent(e)) {
table.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else {
table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
private class MyDoubleClickListener extends DoubleClickListener {
@Override
protected boolean onDoubleClick(@NotNull MouseEvent event) {
if (!isShowNewInstancesEvent(event)) {
handleClassSelection(getTable().getSelectedClass());
return true;
}
return false;
}
}
private final class MyUpdateClassesCommand extends LowestPriorityCommand {
MyUpdateClassesCommand(@Nullable SuspendContextImpl suspendContext) {
super(suspendContext);
}
@Override
public void contextAction(@NotNull SuspendContextImpl suspendContext) {
handleTrackers();
final VirtualMachineProxyImpl proxy = suspendContext.getDebugProcess().getVirtualMachineProxy();
final List<ReferenceType> classes = proxy.allClasses();
ClassesTable table = getTable();
if (!classes.isEmpty()) {
final VirtualMachine vm = classes.get(0).virtualMachine();
if (vm.canGetInstanceInfo()) {
final Map<TypeInfo, Long> counts = getInstancesCounts(classes, vm);
ApplicationManager.getApplication().invokeLater(() -> table.updateContent(counts));
}
else {
ApplicationManager.getApplication().invokeLater(() -> table.updateClassesOnly(JavaTypeInfo.wrap(classes)));
}
}
ApplicationManager.getApplication().invokeLater(() -> table.setBusy(false));
viewUpdated();
}
private void handleTrackers() {
if (!myIsTrackersActivated.get()) {
myConstructorTrackedClasses.values().forEach(ConstructorInstancesTracker::enable);
myIsTrackersActivated.set(true);
}
else {
commitAllTrackers();
}
}
private Map<TypeInfo, Long> getInstancesCounts(@NotNull List<ReferenceType> classes, @NotNull VirtualMachine vm) {
final int batchSize = DebuggerUtils.isAndroidVM(vm)
? AndroidUtil.ANDROID_COUNT_BY_CLASSES_BATCH_SIZE
: DEFAULT_BATCH_SIZE;
final int size = classes.size();
final Map<TypeInfo, Long> result = new LinkedHashMap<>();
for (int begin = 0, end = Math.min(batchSize, size);
begin != size;
begin = end, end = Math.min(end + batchSize, size)) {
final List<ReferenceType> batch = classes.subList(begin, end);
final long start = System.nanoTime();
final long[] counts = vm.instanceCounts(batch);
final long delay = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
for (int i = 0; i < batch.size(); i++) {
result.put(new JavaTypeInfo(batch.get(i)), counts[i]);
}
final int waitTime = (int)Math.min(DELAY_BEFORE_INSTANCES_QUERY_COEFFICIENT * delay, MAX_DELAY_MILLIS);
mySingleAlarm.setDelay(waitTime);
LOG.debug(String.format("Instances query time = %d ms. Count of classes = %d", delay, batch.size()));
}
return result;
}
}
}
|
def main_integrate(expr, facets, hp_params, max_degree=None):
dims = (x, y)
dim_length = len(dims)
result = {}
integral_value = S.Zero
if max_degree:
grad_terms = [[0, 0, 0, 0]] + gradient_terms(max_degree)
for facet_count, hp in enumerate(hp_params):
a, b = hp[0], hp[1]
x0 = facets[facet_count].points[0]
for i, monom in enumerate(grad_terms):
m, x_d, y_d, _ = monom
value = result.get(m, None)
degree = S.Zero
if b.is_zero:
value_over_boundary = S.Zero
else:
degree = x_d + y_d
value_over_boundary = \
integration_reduction_dynamic(facets, facet_count, a,
b, m, degree, dims, x_d,
y_d, max_degree, x0,
grad_terms, i)
monom[3] = value_over_boundary
if value is not None:
result[m] += value_over_boundary * \
(b / norm(a)) / (dim_length + degree)
else:
result[m] = value_over_boundary * \
(b / norm(a)) / (dim_length + degree)
return result
else:
polynomials = decompose(expr)
for deg in polynomials:
poly_contribute = S.Zero
facet_count = 0
for hp in hp_params:
value_over_boundary = integration_reduction(facets,
facet_count,
hp[0], hp[1],
polynomials[deg],
dims, deg)
poly_contribute += value_over_boundary * (hp[1] / norm(hp[0]))
facet_count += 1
poly_contribute /= (dim_length + deg)
integral_value += poly_contribute
return integral_value |
<filename>src/main/java/com/dasun/employeedemo/service/FamilyMemberService.java<gh_stars>0
package com.dasun.employeedemo.service;
import com.dasun.employeedemo.entity.FamilyMember;
import java.util.List;
public interface FamilyMemberService {
FamilyMember create(FamilyMember familyMember);
FamilyMember update(Long id, FamilyMember familyMember);
FamilyMember get(Long id);
void delete(Long id);
List<FamilyMember> getAll();
}
|
You know how it goes: you're at a party having a couple of brews, then you utter a few careless whispers, things get a little too funky, and -- boom -- next thing you know, you're slumped across the leather seat of a Range Rover, being roughed up by policemen. (Not in the good way.)
We've all been there. The only difference being that we are not George Michael.
Michael -- né Georgios Panayiotou -- was arrested last summer for driving while baked and for possessing the joints that got him that way. Now, he's been sentenced to eight weeks in jail, though he'll probably serve only half that behind bars. Which isn't as good a deal as Lindsay, but then, he probably won't be as much of a menace to the other prisoners.
[BBC via Marty] |
// WithRistretto will set the cache client for both Read & Write clients
func WithRistretto(config *ristretto.Config) ClientOps {
return func(c *clientOptions) {
if config != nil {
c.cacheStore.options = append(c.cacheStore.options, cachestore.WithRistretto(config))
}
}
} |
/**
* Created by Alon Eirew on 7/12/2017.
*/
public class RestHeartClientResponse {
private static final String ETAG_LABEL = "ETag";
private static final String LOCATION_LABEL = "Location";
private final StatusLine statusLine;
private final JsonObject responseObject;
private final Header[] headers;
public RestHeartClientResponse(final StatusLine statusLine, final Header[] headers,
final JsonObject responseObject) {
this.statusLine = statusLine;
this.responseObject = responseObject;
this.headers = headers;
}
public RestHeartClientResponse(final StatusLine statusLine, final Header[] headers) {
this(statusLine, headers, null);
}
public StatusLine getStatusLine() {
return statusLine;
}
public int getStatusCode() {
if (statusLine != null) {
return statusLine.getStatusCode();
}
return -1;
}
public String getEtag() {
return getHeaderByName(ETAG_LABEL);
}
public String getDocumentUrlLocation() {
return getHeaderByName(LOCATION_LABEL);
}
public String getHeaderByName(String headerName) {
String value = null;
if (this.headers != null) {
for (Header header : this.headers) {
if (header.getName().equalsIgnoreCase(headerName)) {
value = header.getValue();
}
}
}
return value;
}
public JsonObject getResponseObject() {
return responseObject;
}
public Header[] getHeaders() {
return headers;
}
} |
1 SHARES Facebook Twitter Google Whatsapp Pinterest Print Mail Flipboard
Glenn Beck went completely off the deep end today by claiming that if John F. Kennedy were alive today he would be a radical tea partier.
Audio via Media Matters:
Beck said, “So, who was John F. Kennedy? He’s been coopted by the left, but would he be? Would people like Orrin Hatch? Would people like Mitch McConnell even accept a man like John F. Kennedy today? You see, the left would say that he would be right there with the left today. Well, he might be. Because when you boil a frog as long as the water is tepid when he gets in, right? But if you do it slowly, do it slowly, he’ll be boiled. But if it’s hot, he’ll jump out. I contend that the water would be so hot right now that JFK, if you could bring him back. If you could bring back the politician that JFK was, he wouldn’t be accepted by the Republican Party because he would be a tea party radical. He wouldn’t even recognize what this country has become, and I’m basing that on his words.”
According to Beck, JFK would be a radical fringe Republican running around with a tea bag on his head, who would be appearing on stage with Ted Cruz and Sarah Palin.
Since Glenn claimed to be using JFK’s words as his basis, here are a few quotes that demonstrate that President Kennedy would be repulsed by the tea party:
JFK on equality for all, “The heart of the question is whether all Americans are to be afforded equal rights and equal opportunities; whether we are going to treat our fellow Americans as we want to be treated.” This a very un-Republican position. Kennedy’s quote can be applied to voting rights, equal pay, and equal rights for same sex couples. These are all things that the Republican Party is opposed to.
President Kennedy on the real evil of extremism, “What is objectionable, what is dangerous about extremists is not that they are extreme, but that they are intolerant. The evil is not what they say about their cause, but what they say about their opponents.” One look at the things that Republicans have said about President Obama would be enough for Kennedy to denounce their words and tactics.
At a time when obstructionism and isolationism dominate the Republican Party, this quote from Kennedy’s inaugural address stands out, “So let us begin anew — remembering on both sides that civility is not a sign of weakness, and sincerity is always subject to proof. Let us never negotiate out of fear, but let us never fear to negotiate.”
John F. Kennedy is the latest in a long line of heroes that the right has tried to posthumously turn Republican. They try this same thing yearly with Martin Luther King. The reality is that if JFK was around today, he would be a centrist Democrat, and he would be appalled by the extremism of the Republican Party.
Glenn Beck was making things up, because the arrogant right believes that they own heroism and patriotism. Any American who is viewed as a hero or patriot must be shoehorned into the right wing camp.
JFK was a Democrat, and if he were alive today, he still would be a Democrat. No amount of tea party mythmaking, and Glenn Beck fairy tales can change the facts.
If you’re ready to read more from the unbossed and unbought Politicus team, sign up for our newsletter here! Email address: Leave this field empty if you're human: |
//-----------------------------------------------------------------------------
// Name: D3DTextr_SetTexturePath()
// Desc: Enumeration callback routine to find a best-matching texture format.
//-----------------------------------------------------------------------------
VOID D3DTextr_SetTexturePath( TCHAR* strTexturePath )
{
if( NULL == strTexturePath )
strTexturePath = _T("");
lstrcpy( g_strTexturePath, strTexturePath );
} |
/**
* Demonstrates usage the <i>andThen</i>
*
* @author Yuriy Stul
*/
public class AndThenEx01 {
private static final Logger logger = LoggerFactory.getLogger(AndThenEx01.class);
private void test1() {
logger.info("==>test1");
subscribe()
.subscribe(
item -> logger.info("item: {}", item),
error -> logger.error(error.getMessage())
);
logger.info("<==test1");
}
private void test2() {
logger.info("==>test2");
subscribe2()
.subscribe(
item -> logger.info("item: {}", item),
error -> logger.error(error.getMessage())
);
logger.info("<==test2");
}
private Completable handshake() {
logger.info("==>handshake");
return Completable.create(observer -> {
logger.info("Making handshake");
observer.onComplete();
});
}
private Flowable<String> subscription() {
logger.info("==>subscription");
return Flowable.fromArray("text1", "text2", "text3");
}
/**
* Bad code - <i>subscription</i> starts to work before <i>handshake</i> is finished.
*
* @return stream with texts
*/
private Flowable<String> subscribe() {
logger.info("==>subscribe");
return handshake().andThen(subscription());
}
/**
* Right code - <i>subscription</i> starts to work after <i>handshake</i> is finished.
*
* @return stream with texts
*/
private Flowable<String> subscribe2() {
logger.info("==>subscribe2");
return Flowable.create(emitter ->
handshake()
.subscribe(() ->
subscription()
.subscribe(emitter::onNext,
emitter::onError),
emitter::onError),
BackpressureStrategy.BUFFER);
}
public static void main(String[] args) {
logger.info("==>main");
var c = new AndThenEx01();
c.test1();
c.test2();
logger.info("<==main");
}
} |
.
OBJECTIVE
To assess the association of TLR4 gene polymorphisms with large artery atherosclerosis (LAA) stroke and liability to atherosclerosis in an ethnic Han population from northern China.
METHODS
The study has involved 286 LAA stroke patients and 300 healthy controls. The LAA group has been divided 4 subsets according to angiostenosis conditions. Polymerase chain reaction-restriction fragment length polymorphism and pyrosequencing were employed to analyze three single nucleotide polymorphism (SNPs) (rs1927914, rs1927911 and rs2149356) of the TLR4 gene. A Haploview software package was used to analyze the haplotypes.
RESULTS
SNPs rs1927911 and rs2149356 were associated with LAA stroke. Genotypic and allelic frequencies of rs1927914 did not differ significantly between the two groups. Genetic variants of the three SNPs did not vary significantly between all subsets. Haplotype analysis was revealed a significant difference between the LAA group and the control group. Compared with the controls, the frequencies of haplotypes H2 and H8 were lower, and that of H3 was greater in the LAA group.
CONCLUSION
An association between the TLR4 gene polymorphisms and LAA stroke subtype in ethnic Han population in northern China has been found. However, no association of liability to atherosclerosis in different vascular bed has been found with these polymorphisms. |
import java.util.*;
public class DreamoonAndWiFi {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
String s2 = scanner.next();
scanner.close();
int plus = 0, minus = 0, question = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == '+') plus++;
else minus++;
if (s2.charAt(i) == '+') plus--;
else if (s2.charAt(i) == '-') minus--;
else if (s2.charAt(i) == '?') question++;
}
DreamoonAndWiFi dre = new DreamoonAndWiFi();
if (question == dre.abs(plus) + dre.abs(minus)){
double ct = 1.0*dre.factorial(question)/(dre.factorial(dre.abs(plus)) * dre.factorial(question - dre.abs(plus)));
System.out.print(ct/dre.pow(2, question));
}
else System.out.println(0.0);
}
private long factorial(int n) {
if (n <= 1) return 1;
long res = 1;
for (int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
private int abs(int a){
return (a > 0) ? a : -a;
}
private long pow(int x, int y) {
if (y == 0) return 1;
else if (y == 1) return x;
else if (y % 2 == 0) {
return pow(x*x, y/2);
}
else return x*pow(x, y - 1);
}
} |
#include "stdafx.h"
#include "MeshComponent.h"
#include "Script.h"
#include "Resource.h"
CMeshComponent::CMeshComponent(const std::string& file_path)
{
}
void CMeshComponent::InitLuaAPI(lua_State *L)
{
luabridge::getGlobalNamespace(L)
.deriveClass<CMeshComponent,CComponent>("MeshComponent")
.addConstructor<void(*)(const std::string&)>()
.endClass();
} |
def tvLogs(
cmppicks: list([np.ndarray]),
tvpicks: list([[np.ndarray], [np.ndarray]]),
H: dict
)->np.ndarray:
cmppicks=np.array(cmppicks)
time = np.arange(0, H['ns'])*H['dt']*1e-06
tvLog = np.zeros((cmppicks.shape[0], time.shape[0], 2))
tvLog[:,:,0] = time
for i in range(len(tvpicks[0])):
vInterp = np.interp(time, np.array(tvpicks[0][i]), np.array(tvpicks[1][i]))
tvLog[i,:,1] = vInterp
return tvLog |
/**
* Handles the left and right buttons.
*
* @param screen The current screen.
* @param right True if the right button is pressed, else false.
*/
private boolean handleLeftRight(@NotNull Screen screen, boolean right)
{
Element focused = screen.getFocused();
if (focused != null)
if (this.handleRightLeftElement(focused, right))
return this.changeFocus(screen, right);
return true;
} |
/**
* Remove all the emitters from the system
*/
public void removeAllEmitters() {
for (int i=0;i<emitters.size();i++) {
removeEmitter((ParticleEmitter) emitters.get(i));
i--;
}
} |
/**
* Created by ibrahimabdulkadir on 06/07/2017.
*/
public class RecipeDetailFragment extends BaseFragment implements
RecipeDetailMvpView, RecipeDetailAdapter.Callback {
@Inject
RecipeDetailMvpPresenter<RecipeDetailMvpView> mPresenter;
@Inject
RecipeDetailAdapter mRecipeDetailAdapter;
@Inject
LinearLayoutManager mLayoutManager;
@BindView(R.id.recipe_details_ingredients)
TextView recipeDetailsIngredients;
@BindView(R.id.recipe_detail_recycler_view)
RecyclerView recipeDetailsRecyclerView;
@BindBool(R.bool.master_detail_mode)
boolean masterDetailMode;
@BindString(R.string.error_default)
String errorMessage;
private int recipeId;
private List<Step> mSteps;
public static RecipeDetailFragment newInstance(int recipeId) {
Bundle args = new Bundle();
args.putInt(AppConstants.BUNDLE_RECIPE_ID, recipeId);
RecipeDetailFragment fragment = new RecipeDetailFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recipeId = getArguments().getInt(AppConstants.BUNDLE_RECIPE_ID);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recipe_detail, container, false);
ActivityComponent component = getActivityComponent();
if (component != null) {
component.inject(this);
setUnBinder(ButterKnife.bind(this, view));
mPresenter.onAttach(this);
mRecipeDetailAdapter.setCallback(this);
mRecipeDetailAdapter.setHasStableIds(true);
}
return view;
}
@Override
protected void setUp(View view) {
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recipeDetailsRecyclerView.setLayoutManager(mLayoutManager);
recipeDetailsRecyclerView.setItemAnimator(new DefaultItemAnimator());
recipeDetailsRecyclerView.setAdapter(mRecipeDetailAdapter);
mPresenter.loadRecipeNameFromRepo(recipeId);
mPresenter.loadIngredientsFromRepo(recipeId);
mPresenter.loadStepsFromRepo(recipeId);
}
@Override
public void onRecipeStepClick(int stepId) {
mPresenter.openStepDetails(recipeId, stepId);
}
@Override
public void onDestroyView() {
mPresenter.onDetach();
super.onDestroyView();
}
@Override
public void showIngredientsList(List<Ingredient> ingredients) {
StringBuilder sb = new StringBuilder();
for (Ingredient ingredient : ingredients) {
String name = ingredient.ingredient();
float quantity = ingredient.quantity();
String measure = ingredient.measure();
sb.append("\n");
sb.append(StringUtils.formatIngredient(getContext(), name, quantity, measure));
}
recipeDetailsIngredients.setText(sb.toString());
}
@Override
public void showStepsList(List<Step> steps) {
mSteps = steps;
mRecipeDetailAdapter.refreshStepList(steps);
}
@Override
public void showRecipeNameInActivityTitle(String recipeName) {
getActivity().setTitle(recipeName);
}
@Override
public void showStepDetails(int stepId, Step step) {
if (masterDetailMode) {
RecipeStepFragment fragment =
RecipeStepFragment.newInstance(step);
FragmentUtils.replaceFragmentIn(
getActivity().getSupportFragmentManager(),
fragment,
R.id.detail_fragment_container);
} else {
startActivity(RecipeStepActivity.getStartIntent(getContext(), stepId, mSteps));
}
}
@Override
public void showErrorMessage() {
// User should not see this
onError(errorMessage);
}
} |
Fighting sedentary lifestyle and obesity in the 21st century: what the fitness business services can learn from the tobacco industry
This essay sought to analyze the strategies adopted by the tobacco industry to promote itself and reach its target audience and identified that, in essence, communication-related to smoking as a passport to a more intense, adventurous, and sporting life does not belong to what smoking habits bring. These communication strategies best serve the fitness and wellness industry, a true ambassador of these benefits and an essential ally against NCDs in the 21st century. In addition, the worldwide anti-smoking campaign is being observed and based on it, a campaign against sedentary lifestyle and in favor of consumption habits that prevent obesity is proposed. These are contributions both to the literature on social marketing and to corporate and public health management. New research paths are pointed out.
Introduction
• Non-communicable chronic diseases (NCDs) are co-responsible for 3 out • The tobacco industry skillfully instigated the smoking habit, and their marketing strategies gave tobacco consumption a feeling of belonging, dominance, sexual appeal, and search for adventure (Sargent et al., 2001).
• For the harm caused by smoking globally, the WHO and national governments created campaigns against cigarette consumption and its habit, using the same tool previously used in the tobacco industry: communication strategies (WHO, 2017).
Introduction
• This essay proposes a look at the successful strategies of the tobacco industry and proposes to be the fitness and wellness market the proper campaigns' "spokesperson" for many made by tobacco brands.
• We seek to answer two research questions (RQ).
• RQ 1) Is it possible to point out ways of action of the marketing operator in achieving the decision of the potential consumer for the fitness business by observing marketing strategies found by the tobacco industry to win over its audience? • RQ2) Can public campaigns discouraging smoking serves as a way for the public authorities to discourage sedentary lifestyle, consequently stimulating the population to practice physical activity in a regular and oriented way?
Tobacco consumption and industry strategies
• Brand personality can be defined as a set of human characteristics associated with the brand, in a symbolic or selfexpressive function that allows consumers to associate human personality traits with the brand ( • Tobacco brands, which showed their products as passports for a more active, adventurous, and safe life, used branding strategies and the attributes that awaken consumer's brand loyalty, such as brand personality .
• It is possible to observe the tobacco brands strategies using what Maslow (1958Maslow ( , 1970 called the human needs in the hierarchy of human motivations.
Tobacco consumption and industry strategies
• The various marketing plans described in tobacco companies' internal documents lead us to consider that smoking is a communicable disease conveyed by economic interests, which use complex strategies -most often unfair (Cavalcante, 2005;Dewhirst & Sparks, 2003).
• The reference groups' role is a significant factor in smoking adoption (Cavalcante, 2005;Sargent et al., 2001).
• The reference groups exert direct or indirect influence on the person's attitudes or behavior (Park & Lessig, 1977). • While the tobacco industry seeks to draw attention to pleasure, health organizations try to highlight the consequences of this momentary pleasure.
• According to Reitsma et al. (2017), Brazil achieved the third most significant fall in tobacco consumption, by age, since 1990.
• Between 1990 and 2015, the daily percentage of smokers in Brazil fell from 29% to 12% among men and 19% to 8% among women, but the country still ranks 8th in the world's ranking of smoking (Reitsma et al. 2017; WHO, 2017).
• Campaigns have been aired worldwide to reduce nicotine intake by smokers (WHO, 2017).
• The efforts of the State and health organizations have been to deconstruct the narrative that the smoker is sensual and popular, socially dominant, and fun has had an effect.
Sedentary lifestyle, obesity and the Fitness Business Services (FBS) • Obesity and overweight in adults bring as consequences diseases widely documented by science and causing premature death by NCDs.
• Wannmacher (2016, p.2) warns that "obese children have breathing difficulties, increased risk of fractures, psychological and early effects indicators of cardiovascular disease and insulin resistance".
• Hawkins and Mothersbaugh (2018) define that, in consumption, perception is a process by which the individual selects, analyzes, and interprets the information collected by sensory receptors. • Their research points out that, in countries with a ratio of more than 10 gyms per 100,000 inhabitants, the population's penetration rate to physical activity is more than 15%. • In these countries, the average life expectancy is more than 80 years old. In times of COVID-19, gyms have also proved to be important allies in raising awareness of the importance of physical activity. • The tobacco industry has built powerful narratives to associate with its products affiliation, belonging, and self-realization, key elements of Maslow's theory • Some of its iconic brands have taken on personalities such as: • Marlboro and its cowboy, tying its consumer to the figure of the alpha male.
• Hollywood to the sporting world or the conqueror.
• Lucky Strike tied to the slender woman.
• Marketing operators can be a powerful component in the construction of the narrative that conquers and the practitioner of physical activity through the lessons arising from the successful campaigns of the tobacco industry, however contradictory it may seem.
• As a matter of fact, what was contradictory was the tobacco industry taking over assets such as sportsmanship, safety, and aesthetic issues due to its consumption.
Security
All age groups and all possibilities of activity. Examples: swimming and martial arts Physical safety is ultimately the essence of physical activity results, as described in the literature review on the physical activity benefits.
Level of affiliation or love
All age groups and in all modalities. Example: CrossFit, and Les Mills programs Belonging is one of the most critical elements in the value co-creation in the FBS usage experience.
Level of esteem: selfesteem, status, recognition, attention, importance, and appreciation All age groups and in all modalities. Especially for those seeking treatment against depression. Example: bodybuilding and running groups The physical activity practice can be an antidote to depression. Physical activity is effective in treating depression. The effect is of the same magnitude as psychotherapeutic interventions.
Level of selfrealization: what the individual has the potential to be All age groups and in all modalities. Example: functional training and indoor cycling Practitioners can use physical activity to achieve their best performance within their limitations and genetic predispositions. Furthermore, the gym can engage employees and clients in community actions and offer them a sense of social contribution.
RQ2: Can public campaigns to discourage smoking serve as a way for the public government to discourage sedentary lifestyle?
• In addition to financial actions, the incentive for regular physical activity practice should be part of institutional campaigns to combat sedentary lifestyle and obesity, in the someway as campaigns against tobacco: • monitor more consistently sedentary lifestyle; • applying policies to prevent sedentary behavior; • protection of public spaces where people engage in physical activity; • offering financial help and psychological support to people against the habit of consuming over-processed foods; • warning intensely on the dangers of obesity and sedentary lifestyle; • imposing prohibitions on advertising, promotion, and sponsorship of foods considered harmful to health and increase taxes on them.
Conclusion
• Fitness companies are part of the solution to combat prosperity-related diseases such as obesity and coronary heart disease • The national health managers need to find the best narratives in creating value for the (non) users.
• It is possible to conclude that the FBS is a legitimate • Joint actions between the government and the private sector can bring mutual benefits • A government action plan is needed, along with what has been put into place to reduce smoking -and with positive effects already pointed here -to reduce sedentary lifestyle and obesity.
Conclusion
• The contribution to the advancement of social and corporate marketing literature lies in the unique approach of this essay, observing the practices used to attract smokers as validated marketing strategies to attract consumers to regular physical activity practice.
• As a contribution to public health and business management, it is aimed to contribute by proposing that managers observe risk awareness strategies to reduce tobacco consumption as an alternative to building awareness strategies about the sedentary lifestyle and obesity risks.
• Among the limitations, the fact that this essay is the result of the authors' observations raises the need for new perspectives on these topics of such relevant interest, both in the context of public health and business management.
• A quantitative investigation of predictors of human behavior and the modalities described in Figure 2 can advance the proposal presented here. |
So W Bush's approval rating has dipped to 42%. To give you an idea of how low that is, scabies gets a 36% approval rating and banging your elbow bone on a marble table edge gets a 32%. Heck, even the Devil gets a 4%. I think Cheney just scored a 9% (note: poll results reflect a margin of error of plus or minus fifty percent except the initial 42% one, which is real). The only people still supporting W and these evil goofs are the Brit Hume fan club and people who worry that if they admit they were wrong Al Franken gets some kind of bonus commission ipod or trip to Cancun.
That's right, finally after six years America is waking up to this ridiculously corrupt, secretive and arrogant administration. The reality of what these guys have done can no longer be fudged. The invasion/liberation of Iraq is a disaster, the trade deficit and oil prices are skyrocketing, numbers and facts have been altered and corporate lobbyists now swarm over and through our government like rats over an untended salad bar... Not to mention the fact that due to their politicking our country is more divided than it's been since people rode horses to work and treated broken bones with butter and leeches. If this all keeps up pretty soon FOX News will have to start airing reruns from five years ago to keep alive the myth that the corporate-backed right isn't ripping our country apart and off.
So what does Bush Jr. do in the face of this collapsing house of lies and ineptitude? He rides his bike.
Let me say that again. With support for his administration falling fast and American troops engaged in a crazily complicated war that requires 24/7 diplomacy, managing and oversight, our president has gone back to his fake ranch to ride his bike.
Now before the Bush zealots jump all over me for distorting facts, let me be more specific: he's also clearing brush.
Since he's been in office, Bush Jr. has had almost 400 days at his play ranch in Crawford. I make silly comedies for a living and I haven't had 400 days off total in my whole life. This guy is the president, and he is riding his bike like a seven year old who just figured out it makes a cool sound when you put baseball cards in your wheel spokes.
And George Jr. isn't just vacationing. He's vacationing mad. You know, like when people drive mad? "Well then fine! Let's just go to the store!" And then the person goes 110 in a 25 zone while insisting everything’s all right. Well George W is vacationing mad. "You think my war is a mess? Well I'm going to Crawford to ride bikes and I don't care what you say!" "You think I made a terrible appointment in sending Bolton to the U.N.? I don’t care... I'm going to Texas and I'm not even wearing a tie! So screw you all!" |
<reponame>xzrunner/terr<filename>source/device/BasicNoise.cpp<gh_stars>0
#include "terraingraph/device/BasicNoise.h"
#include <heightfield/HeightField.h>
#include <heightfield/Utility.h>
namespace terraingraph
{
namespace device
{
void BasicNoise::Execute(const std::shared_ptr<dag::Context>& ctx)
{
m_hf = std::make_shared<hf::HeightField>(m_width, m_height);
for (size_t y = 0; y < m_height; ++y) {
for (size_t x = 0; x < m_width; ++x) {
m_hf->Set(x, y, hf::Utility::HeightFloatToShort(GetValue(x, y)));
}
}
}
float BasicNoise::GetValue(size_t x, size_t y) const
{
return m_amplitude * Total(x, y);
}
float BasicNoise::Total(size_t x, size_t y) const
{
//properties of one octave (changing each loop)
float t = 0.0f;
float _amplitude = 1;
float freq = m_frequency;
for(int i = 0; i < m_octaves; i++)
{
t += GetValue(y * freq + m_randomseed, x * freq + m_randomseed) * _amplitude;
_amplitude *= m_persistence;
freq *= 2;
}
return t;
}
float BasicNoise::GetValue(float x, float y) const
{
int Xint = (int)x;
int Yint = (int)y;
float Xfrac = x - Xint;
float Yfrac = y - Yint;
//noise values
float n01 = Noise(Xint-1, Yint-1);
float n02 = Noise(Xint+1, Yint-1);
float n03 = Noise(Xint-1, Yint+1);
float n04 = Noise(Xint+1, Yint+1);
float n05 = Noise(Xint-1, Yint);
float n06 = Noise(Xint+1, Yint);
float n07 = Noise(Xint, Yint-1);
float n08 = Noise(Xint, Yint+1);
float n09 = Noise(Xint, Yint);
float n12 = Noise(Xint+2, Yint-1);
float n14 = Noise(Xint+2, Yint+1);
float n16 = Noise(Xint+2, Yint);
float n23 = Noise(Xint-1, Yint+2);
float n24 = Noise(Xint+1, Yint+2);
float n28 = Noise(Xint, Yint+2);
float n34 = Noise(Xint+2, Yint+2);
//find the noise values of the four corners
float x0y0 = 0.0625f*(n01+n02+n03+n04) + 0.125f*(n05+n06+n07+n08) + 0.25f*(n09);
float x1y0 = 0.0625f*(n07+n12+n08+n14) + 0.125f*(n09+n16+n02+n04) + 0.25f*(n06);
float x0y1 = 0.0625f*(n05+n06+n23+n24) + 0.125f*(n03+n04+n09+n28) + 0.25f*(n08);
float x1y1 = 0.0625f*(n09+n16+n28+n34) + 0.125f*(n08+n14+n06+n24) + 0.25f*(n04);
//interpolate between those values according to the x and y fractions
float v1 = Interpolate(x0y0, x1y0, Xfrac); //interpolate in x direction (y)
float v2 = Interpolate(x0y1, x1y1, Xfrac); //interpolate in x direction (y+1)
float fin = Interpolate(v1, v2, Yfrac); //interpolate in y direction
return fin;
}
float BasicNoise::Interpolate(float x, float y, float a) const
{
float negA = 1.0f - a;
float negASqr = negA * negA;
float fac1 = 3.0f * (negASqr) - 2.0f * (negASqr * negA);
float aSqr = a * a;
float fac2 = 3.0f * aSqr - 2.0f * (aSqr * a);
return x * fac1 + y * fac2; //add the weighted factors
}
float BasicNoise::Noise(size_t x, size_t y) const
{
int n = x + y * 57;
n = (n << 13) ^ n;
int t = (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff;
return 1.0f - float(t * 0.931322574615478515625e-9);/// 1073741824.0f);
}
}
} |
<filename>c/photogrammetry/EOQuality.cpp<gh_stars>1-10
/**************************************************************************
EOQuality.cpp
**************************************************************************/
/*Copyright 2002-2021 e-foto team (UERJ)
This file is part of e-foto.
e-foto is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
e-foto is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with e-foto. If not, see <http://www.gnu.org/licenses/>.
*/
#include "EOQuality.h"
#include "ExteriorOrientation.h"
#include "SpatialRessection.h"
#include <sstream>
namespace br {
namespace uerj {
namespace eng {
namespace efoto {
EOQuality::~EOQuality()
{
}
/**
* Get the value of V.
* @return the value of V
*/
Matrix EOQuality::getV()
{
return V;
}
/**
* Get the value of sigma0Squared.
* @return the value of sigma0Squared
*/
double EOQuality::getsigma0Squared()
{
return sigma0Squared;
}
/**
* Get the value of SigmaXa.
* @return the value of SigmaXa
*/
Matrix EOQuality::getSigmaXa()
{
return SigmaXa;
}
/**
* Get the value of SigmaLa.
* @return the value of SigmaLa
*/
Matrix EOQuality::getSigmaLa()
{
return SigmaLa;
}
std::string EOQuality::objectType(void)
{
return "EOQuality";
}
std::string EOQuality::objectAssociations(void)
{
return "";
}
bool EOQuality::is(std::string s)
{
return (s == "EOQuality" ? true : false);
}
void EOQuality::xmlSetData(std::string xml)
{
EDomElement root(xml);
V.xmlSetData(root.elementByTagName("V").elementByTagName("mml:matrix").getContent());
if (root.elementByTagName("sigma0Squared").isAvailable()) {
sigma0Squared = root.elementByTagName("sigma0Squared").toDouble();
}
else {
sigma0Squared = 1.0;
}
if (root.elementByTagName("SigmaXa").isAvailable()) {
SigmaXa.xmlSetData(root.elementByTagName("SigmaXa").elementByTagName("mml:matrix").getContent());
}
else {
SigmaXa.identity(6);
}
if (root.elementByTagName("SigmaLa").isAvailable()) {
SigmaLa.xmlSetData(root.elementByTagName("SigmaLa").elementByTagName("mml:matrix").getContent());
}
else {
SigmaLa.identity(1);
}
}
std::string EOQuality::xmlGetData()
{
std::stringstream result;
result << "<quality>\n";
result << "<V>\n";
result << V.xmlGetData();
result << "</V>\n";
if (sigma0Squared == 1.0) {
result << "<sigma0Squared>Not Available</sigma0Squared>\n";
}
else {
result << "<sigma0Squared>" << Conversion::doubleToString(sigma0Squared) << "</sigma0Squared>\n";
}
if (SigmaXa.isIdentity()) {
result << "<SigmaXa>Not Available</SigmaXa>\n";
}
else {
result << "<SigmaXa>\n";
result << SigmaXa.xmlGetData();
result << "</SigmaXa>\n";
}
if (SigmaLa.isIdentity()) {
result << "<SigmaLa>Not Available</SigmaLa>\n";
}
else {
result << "<SigmaLa>\n";
result << SigmaLa.xmlGetData();
result << "</SigmaLa>\n";
}
result << "</quality>\n";
return result.str();
}
/**
* This method calculates the values of an IOQuality's attributes based on its Orientation's values.
*/
void EOQuality::calculate(SpatialRessection* myEO)
{
V = myEO->getLb() - myEO->getLastL0();
sigma0Squared = (((V.transpose() * myEO->getP()) * V) / (myEO->getLb().getRows() - myEO->getXa().getRows())).get(1, 1);
SigmaXa = ((myEO->getA().transpose() * myEO->getP()) * myEO->getA()).inverse() * sigma0Squared;
SigmaLa = ((myEO->getA() * ((myEO->getA().transpose() * myEO->getP()) * myEO->getA()).inverse()) * myEO->getA().transpose()) * sigma0Squared;
}
} // namespace efoto
} // namespace eng
} // namespace uerj
} // namespace br
|
// DropBoundingCapability attempts to drop capability cp from t's capability
// bounding set.
func (t *Task) DropBoundingCapability(cp linux.Capability) error {
t.mu.Lock()
defer t.mu.Unlock()
if !t.creds.HasCapability(linux.CAP_SETPCAP) {
return syserror.EPERM
}
t.creds = t.creds.Fork()
t.creds.BoundingCaps &^= auth.CapabilitySetOf(cp)
return nil
} |
__all__ = ['AsyncDocument']
from .async_document import AsyncDocument
|
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package model
import (
"strings"
"testing"
)
func TestAuthJson(t *testing.T) {
a1 := AuthData{}
a1.ClientId = NewId()
a1.UserId = NewId()
a1.Code = NewId()
json := a1.ToJson()
ra1 := AuthDataFromJson(strings.NewReader(json))
if a1.Code != ra1.Code {
t.Fatal("codes didn't match")
}
}
func TestAuthPreSave(t *testing.T) {
a1 := AuthData{}
a1.ClientId = NewId()
a1.UserId = NewId()
a1.Code = NewId()
a1.PreSave()
a1.IsExpired()
}
func TestAuthIsValid(t *testing.T) {
ad := AuthData{}
if err := ad.IsValid(); err == nil {
t.Fatal()
}
ad.ClientId = NewId()
if err := ad.IsValid(); err == nil {
t.Fatal()
}
ad.UserId = NewId()
if err := ad.IsValid(); err == nil {
t.Fatal()
}
ad.Code = NewId()
if err := ad.IsValid(); err == nil {
t.Fatal()
}
ad.ExpiresIn = 1
if err := ad.IsValid(); err == nil {
t.Fatal()
}
ad.CreateAt = 1
if err := ad.IsValid(); err != nil {
t.Fatal()
}
}
|
Minerals response to transportation stress at different flocking densities in hot humid and winter seasons and the assessment of ameliorative effect of pretreatment with vitamin C, electrolyte and jaggery in goats
ABSTRACT The present study evaluated the seasonal effects of transportation of goats (Alpine × Beetle) at different flocking densities, supplemented with vitamin C in group I, vitamin C + electrolyte in group II and jaggery in group III, 3 days before transport of animal, during winter and hot-humid seasons. The goats were selected from Livestock Research Centre (LRC), National Dairy Research Institute, Karnal, and were of 10–12 months old. Each group consisted of 25 goats each, divided into high (15) and low (10) flocking densities, transported for 8 h with an average speed of 25 km/h. All the animals were kept off-feed and deprived of water during the transportation period. Blood samples were taken just before transportation, immediately after transportation, 6 h, 12 h, 24 h and 2 days post-transportation from all the three groups. The blood samples were further analysed for estimation of different minerals (Na, K, Cl−, P and Mg). In both the seasons and in both the flocking density groups, higher pre-transportation values (P<0.05) of Na, K, Mg and Cl- were observed whereas P values post transportation (P<0.05) were higher in hot humid season in all the treated groups and also in group III. Except for P, minimum values (P < 0.05) of all other minerals were recorded just after unloading in both the density groups and in both the seasons, which then increased to basal values (P < 0.05) after 12–24 h of post-transportation. Supplementation with vitamin C, vitamin C + electrolyte and jaggery aided in reducing transportation stress but vitamin C + electrolyte combination proved more beneficial in alleviating transportation stress in the goats. Abbreviation: fd: flocking density; Na: sodium; K: potassium; Cl-: chloride; P: phosphorous; Mg: magnesium, HH: hot humid; AA: ascorbic acid; lfd: low flocking density; hfd: high flocking density; LRC: Livestock Research Centre |
/**
* Track in-progress downloads here and, if on an Android version >= O, make
* this a foreground service.
* @param id The {@link ContentId} of the download that has been started and should be tracked.
*/
private void startTrackingInProgressDownload(ContentId id) {
Log.w(TAG, "startTrackingInProgressDownload");
if (mDownloadsInProgress.size() == 0) startForegroundInternal();
if (!mDownloadsInProgress.contains(id)) mDownloadsInProgress.add(id);
} |
<reponame>LenardLee/k8s-container-image-promoter
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://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 container
// Set is a basic set-like data structure.
type Set map[Element]interface{}
// Element is a singleton item that goes with Set.
type Element interface{}
// Minus returns a new set, by subtracting everything in b from a.
func (a Set) Minus(b Set) Set {
c := make(Set)
for k, v := range a {
c[k] = v
}
for k := range b {
delete(c, k)
}
return c
}
// Union takes two sets and returns their union in a new set.
func (a Set) Union(b Set) Set {
c := make(Set)
for k, v := range a {
c[k] = v
}
for k, v := range b {
c[k] = v
}
return c
}
// Intersection takes two sets and returns elements common to both. Note that we
// throw away information about the values of the elements in b.
func (a Set) Intersection(b Set) Set {
c := make(Set)
for k, v := range a {
if _, ok := b[k]; ok {
c[k] = v
}
}
return c
}
|
<filename>src/main/java/com/technews/model/Vote.java
package com.technews.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;//figure out what these imports are about & when they're invoked
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
@Table(name="vote")
public class Vote implements Serializable{
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer id;//instance field
private Integer userId;
private Integer postId;
//instance fields above
public Vote(){}//what is this method for?
//constructor method below
public Vote(Integer id,Integer userId,Integer postId){
this.id=id;
this.userId=userId;
this.postId=postId;
}
public Vote(Integer userId,Integer postId){
this.userId=userId;
this.postId=postId;
}
public Integer getId(){
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
@Override
public boolean equals(Object o){
if(this==o)return true;
if(!(o instanceof Vote))return false;
Vote vote=(Vote) o;
return Objects.equals(getId(),vote.getId())&&
Objects.equals(getUserId(),vote.getUserId())&&
Objects.equals(getPostId(),vote.getUserId());
}
@Override
public int hashCode(){
return Objects.hash(getId(),getUserId(),getPostId());
}
@Override
public String toString(){
return "Vote{" +
"id=" + id +
", userId=" + userId +
", postId=" + postId +
'}';
}
}
|
// New returns a new Payment struct with default values for version 2
func New() *Payment {
return &Payment{
ServiceTag: "BCD",
Version: 2,
CharacterSet: 2,
IdentificationCode: "SCT",
RemittanceIsStructured: false,
}
} |
<filename>cots-match/src/test/java/nz/org/vincenzo/cots/match/service/ArbitrationServiceTest.java
package nz.org.vincenzo.cots.match.service;
import nz.org.vincenzo.cots.domain.Ship;
import nz.org.vincenzo.cots.match.service.impl.ArbitrationServiceImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* The test case for {@link ArbitrationService}.
*
* @author <NAME>
*/
@ExtendWith(MockitoExtension.class)
class ArbitrationServiceTest {
@InjectMocks
private ArbitrationServiceImpl arbitrationService;
@Test
void arbitrateWithNullArguments() {
assertThatThrownBy(() -> arbitrationService.arbitrate(null, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Attacking ship cannot be null or have null values");
}
@Test
void arbitrateWithInvalidCoordinates() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.AMERICA_CLASS_AMPHIBIOUS_ASSAULT_SHIP);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.INDEPENDENCE_CLASS_LITTORAL_COMBAT_SHIP_4);
defendingShip.setCoordinates(new Ship.Coordinates(4, 3));
assertThatThrownBy(() -> arbitrationService.arbitrate(attackingShip, defendingShip))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Coordinates are not the same");
}
@Test
void arbitrateWithSameColor() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.AMERICA_CLASS_AMPHIBIOUS_ASSAULT_SHIP);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.WHITE);
defendingShip.setShipClass(Ship.ShipClass.INDEPENDENCE_CLASS_LITTORAL_COMBAT_SHIP_4);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThatThrownBy(() -> arbitrationService.arbitrate(attackingShip, defendingShip))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Attacking own ship is not allowed");
}
@Test
void arbitrateWithUnknownShipClass() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.UNKNOWN);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.INDEPENDENCE_CLASS_LITTORAL_COMBAT_SHIP_4);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThatThrownBy(() -> arbitrationService.arbitrate(attackingShip, defendingShip))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Attacking ship class cannot be unknown");
}
@Test
void arbitrateBetweenSubmarineAndLittoralCombatShip() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.VIRGINIA_CLASS_ATTACK_SUBMARINE_0);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.INDEPENDENCE_CLASS_LITTORAL_COMBAT_SHIP_4);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThat(arbitrationService.arbitrate(attackingShip, defendingShip)).isEqualTo(defendingShip);
}
@Test
void arbitrateBetweenLittoralCombatShipAndSubmarine() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.BLACK);
attackingShip.setShipClass(Ship.ShipClass.INDEPENDENCE_CLASS_LITTORAL_COMBAT_SHIP_4);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.WHITE);
defendingShip.setShipClass(Ship.ShipClass.VIRGINIA_CLASS_ATTACK_SUBMARINE_0);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThat(arbitrationService.arbitrate(attackingShip, defendingShip)).isEqualTo(attackingShip);
}
@Test
void arbitrateBetweenCommandShips() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.BLUE_RIDGE_CLASS_COMMAND_SHIP);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.BLUE_RIDGE_CLASS_COMMAND_SHIP);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThat(arbitrationService.arbitrate(attackingShip, defendingShip)).isEqualTo(attackingShip);
}
@Test
void arbitrateBetweenDestroyerAndCarrier() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.ZUMWALT_CLASS_GUIDED_MISSILE_DESTROYER);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.NIMITZ_SUBCLASS_AIRCRAFT_CARRIER);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThat(arbitrationService.arbitrate(attackingShip, defendingShip)).isEqualTo(defendingShip);
}
@Test
void arbitrateBetweenLittoralCombatShipAndCommandShip() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.INDEPENDENCE_CLASS_LITTORAL_COMBAT_SHIP_4);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.BLUE_RIDGE_CLASS_COMMAND_SHIP);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThat(arbitrationService.arbitrate(attackingShip, defendingShip)).isEqualTo(attackingShip);
}
@Test
void arbitrateBetweenCarrierAndSubmarine() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.ENTERPRISE_CLASS_AIRCRAFT_CARRIER);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.VIRGINIA_CLASS_ATTACK_SUBMARINE_0);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThat(arbitrationService.arbitrate(attackingShip, defendingShip)).isEqualTo(defendingShip);
}
@Test
void arbitrateBetweenSameShips() {
Ship attackingShip = new Ship();
attackingShip.setColor(Ship.Color.WHITE);
attackingShip.setShipClass(Ship.ShipClass.ARLEIGH_BURKE_CLASS_GUIDED_MISSILE_DESTROYER);
attackingShip.setCoordinates(new Ship.Coordinates(3, 4));
Ship defendingShip = new Ship();
defendingShip.setColor(Ship.Color.BLACK);
defendingShip.setShipClass(Ship.ShipClass.ARLEIGH_BURKE_CLASS_GUIDED_MISSILE_DESTROYER);
defendingShip.setCoordinates(new Ship.Coordinates(3, 4));
assertThat(arbitrationService.arbitrate(attackingShip, defendingShip)).isNull();
}
}
|
package models
import (
"gorm.io/gorm"
"time"
)
type Comment struct {
gorm.Model
ArticleID int16
Article Article `gorm:"foreignKey:ArticleID;references:Id"`
Content string `gorm:"varchar(200)"`
Posted time.Time
Author string `gorm:"varchar(10)"`
}
func (Comment) TableName() string {
return "comments"
}
|
// interesting bit here is proof that DB is ok
@Override
public void checkpoint(boolean sync) throws IOException {
Connection connection = null;
try {
connection = getDataSource().getConnection();
if (!connection.isValid(10)) {
throw new IOException("isValid(10) failed for: " + connection);
}
} catch (SQLException e) {
LOG.debug("Could not get JDBC connection for checkpoint: " + e, e);
throw IOExceptionSupport.create(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (Throwable ignored) {
}
}
}
} |
Demonstrators stand in front of a rainbow flag of the Supreme Court in Washington, Tuesday, April 28, 2015. The Supreme Court is set to hear historic arguments in cases that could make same-sex marriage the law of the land. The justices are meeting Tuesday to offer the first public indication of where they stand in the dispute over whether states can continue defining marriage as the union of a man and a woman, or whether the Constitution gives gay and lesbian couples the right to marry. (AP Photo/Jose Luis Magana)
Larry Ysunza met his partner Tim Love in 1980 and told his mother that very day that he had met the man he was going to marry. Thirty-five years later, Larry and Tim are among the plaintiffs in the marriage cases that the Supreme Court will hear today. They will be in the courtroom eagerly listening for clues from the justices about whether their long engagement will finally end in marriage vows.
"I never thought this would happen, and certainly not so fast!" That's Larry expressing his surprise at how fast the country is moving towards the freedom to marry for same-sex couples.
I hear the same sentiment -- that marriage equality nationwide was once unimaginable -- from so many people. And I feel it myself, every day. When I was a closeted junior high school kid on rural Long Island in the late 1970s, marriage just wasn't a possibility. I couldn't imagine coming out to anyone, much less a future in which I could live openly and with dignity. How surprised I would have been back then to know that there would be a man in my future that I could marry, with my family in attendance.
Even putting aside how the marriage cases come out (and we can never count on a win, although I'm hopeful), there has been a striking transformation of the country's attitude towards our marriages. That trend has snowballed since 2013, when the Supreme Court struck down the core of the Defense of Marriage Act in the ACLU's United States v. Windsor case.
In short, America is recognizing the common humanity of gay people.
We've gone from 13 marriage states at the end of June 2013, to 37 today. Twenty of those new marriage states came just in the last year. On the cultural side, polls show 61 percent support for marriage equality nationwide, America's biggest businesses are supporting us before the Supreme Court, and even Republican presidential primary candidates are wrestling with whether to attend our weddings or embrace their LGBT children.
That's progress at a rate that genuinely makes my head spin. And it's becoming hard to remember how difficult the struggle was just a few years ago. America today is in a very different place from 2004, when voters in 13 states amended their state constitutions to exclude us from marriage; from the summer of 2006, when we lost marriage cases in New York, Washington, and Nebraska; from 2008, when we lost Prop 8 at the polls, which took marriage away from us in California; and even from early 2011, when the U.S. Department of Justice was still defending the constitutionality of DOMA.
I know I felt different about our prospects for success back then. I was confident in our legal arguments but also thought that the cultural change was happening slowly. I didn't see the acceleration coming. The tsunami of new marriage cases filed all across the country in the wake ofWindsor took me by surprise, as did the even more astounding pile of lower court decisions ruling our way again and again. Something profound has changed about how the country sees gay people.
That change comes from the cultural power of marriage. A central part of homophobia is the assumption that gay people don't have relationships the same way that straight people do. That our relationships are all about sex rather than about love, that we're interested in kids as pedophiles rather than as parents, and that any relationships we do have are short, furtive, and shameful.
Marriage in America means the opposite of those anti-gay stereotypes. Marriage is about love, about having kids, about a very public celebration of two people's commitment to each other.
A primary driver of the cultural change around gay people is the country's growing realization that we're not so different from straight folks. Relationships play the same role in our lives as in theirs. And many of us are living the commitment at the core of marriage and are harmed when the law treats us as legal strangers. In short, America is recognizing the common humanity of gay people.
And today before the Supreme Court, we will be making the same argument: That the common humanity of gay people is the core reason that excluding us from marriage violates the Constitution. We are similarly situated to heterosexuals with regard to the purposes of marriage, and the Constitution's guarantees of liberty and equality apply to us as well. Once the country and the courts appreciate our core similarity, the legal arguments in these cases just aren't very difficult. The inequality becomes quite stark and unjustifiable.
It's taken many years to get to this point, both in the courts and in the culture. Though we've gotten here more quickly than I expected, we have also waited a long time to stand with equal dignity in America. We have lost friends and partners, had children and grandchildren, loved and lost all without the legal protections that so many count on. It's about time -- for Tim and Larry, for my junior high school self, and for millions of other lesbian, gay, and bisexual people all across the country that we be recognized in our full humanity. |
/*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:42:38 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/Message.framework/Message
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <Message/MFDAStreamingContentConsumer.h>
@protocol MFCollectingDataConsumer, MFMessageDataConsumerFactory;
@class NSMutableData, DAMailMessage, NSString;
@interface MFDAMessageContentConsumer : NSObject <MFDAStreamingContentConsumer> {
int _requestedFormat;
id<MFCollectingDataConsumer> _dataConsumer;
id<MFCollectingDataConsumer> _alternatePartConsumer;
id<MFMessageDataConsumerFactory> _consumerFactory;
BOOL _triedCreatingAlternatePartConsumer;
BOOL _didBeginStreaming;
BOOL _succeeded;
NSMutableData* _bodyData;
double _timeOfLastActivity;
DAMailMessage* _message;
}
@property (assign,nonatomic) int requestedFormat; //@synthesize requestedFormat=_requestedFormat - In the implementation block
@property (nonatomic,retain) id<MFCollectingDataConsumer> dataConsumer; //@synthesize dataConsumer=_dataConsumer - In the implementation block
@property (nonatomic,retain) id<MFCollectingDataConsumer> alternatePartConsumer; //@synthesize alternatePartConsumer=_alternatePartConsumer - In the implementation block
@property (nonatomic,retain) id<MFMessageDataConsumerFactory> consumerFactory; //@synthesize consumerFactory=_consumerFactory - In the implementation block
@property (nonatomic,retain,readonly) DAMailMessage * message; //@synthesize message=_message - In the implementation block
@property (nonatomic,retain,readonly) NSMutableData * bodyData; //@synthesize bodyData=_bodyData - In the implementation block
@property (nonatomic,readonly) double timeOfLastActivity; //@synthesize timeOfLastActivity=_timeOfLastActivity - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(void)dealloc;
-(id)data;
-(NSMutableData *)bodyData;
-(DAMailMessage *)message;
-(id<MFCollectingDataConsumer>)dataConsumer;
-(void)setDataConsumer:(id<MFCollectingDataConsumer>)arg1 ;
-(BOOL)succeeded;
-(BOOL)didBeginStreaming;
-(double)timeOfLastActivity;
-(void)setRequestedFormat:(int)arg1 ;
-(void)setConsumerFactory:(id<MFMessageDataConsumerFactory>)arg1 ;
-(id)dataConsumerForPart:(id)arg1 ;
-(BOOL)shouldBeginStreamingForMailMessage:(id)arg1 format:(int)arg2 ;
-(void)consumeData:(char*)arg1 length:(int)arg2 format:(int)arg3 mailMessage:(id)arg4 ;
-(void)didEndStreamingForMailMessage:(id)arg1 ;
-(id<MFMessageDataConsumerFactory>)consumerFactory;
-(void)setAlternatePartConsumer:(id<MFCollectingDataConsumer>)arg1 ;
-(id<MFCollectingDataConsumer>)alternatePartConsumer;
-(int)requestedFormat;
@end
|
<gh_stars>1-10
package com.ksy.designer.entity.model;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ObjectUtils;
public class ModelGroupNode extends ModelNode {
private List<ModelNode> nodeList;
public ModelGroupNode(String id, String name) {
super(id, name);
nodeList = new ArrayList<ModelNode>();
}
@Override
public int getType() {
return ModelNode.TYPE_GROUP;
}
public List<ModelNode> getNodeList() {
return nodeList;
}
public void setNodeList(List<ModelNode> nodeList) {
this.nodeList = nodeList;
}
public ModelGroupNode addNode(ModelNode node) {
if (nodeList != null) {
this.nodeList.add(node);
}
return this;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((nodeList == null) ? 0 : nodeList.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ModelGroupNode other = (ModelGroupNode) obj;
if (!ObjectUtils.equals(this.nodeList, other.nodeList)) {
return false;
}
return true;
}
}
|
use rocket_sync_db_pools::{database, diesel};
#[database("rps")]
pub struct RpsDatabaseConnection(diesel::PgConnection);
|
New global minima of 6-vertex dicarboranes: classical but unexpected.
Dicarboranes generally adopt global minimum predicted by the well-known Wade-Mingos rules, although one classical non-closo structure in the benzvalene form has long been pursued and later synthesized. Here we predicted two new non-closo global minima for 6-vertex dicarboranes (C2B4R6), i.e., trigonal bipyramid (R = SH) and butterfly (R = Cl, NH2, OH, F). The long expected classical benzvalene-like structure, however, is not the global minimum for any of the nine substituents. |
<gh_stars>10-100
from tasks.socrata import LoadSocrataCSV
from luigi import Task, Parameter
class Deeds(Task):
def requires(self):
yield LoadSocrataCSV(domain='data.cityofnewyork.us', dataset='636b-3b5g') # real parties
yield LoadSocrataCSV(domain='data.cityofnewyork.us', dataset='8h5j-fqxa') # real legals
yield LoadSocrataCSV(domain='data.cityofnewyork.us', dataset='bnx9-e6tj') # real master
yield LoadSocrataCSV(domain='data.cityofnewyork.us', dataset='7isb-wh4c') # control codes
#yield PLUTO(year=2014)
|
<filename>src/test/test_mtmodule.py
import pytest
import os
from pathlib import Path
from lib.common.exceptions import ImproperLoggedPhaseError
from lib.common.mtmodule import MTModule
from lib.common.storage import LocalStorage
from test.utils import scaffold_empty
class EmptyMTModule(MTModule):
pass
@pytest.fixture
def additionals(utils):
obj = lambda: None
obj.BASE_DIR = utils.TEMP_ELEMENT_DIR
obj.mod = EmptyMTModule({}, "empty", LocalStorage(folder=utils.TEMP_ELEMENT_DIR))
yield obj
utils.cleanup()
def test_class_variables(additionals):
assert additionals.mod.name == "empty"
assert additionals.mod.disk.base_dir == Path(additionals.BASE_DIR)
assert additionals.mod._MTModule__LOGS == []
assert (additionals.mod.disk._LocalStorage__LOGS_DIR == f"{additionals.BASE_DIR}/logs")
assert (additionals.mod.disk._LocalStorage__LOGS_FILE == f"{additionals.BASE_DIR}/logs/logs.txt")
assert os.path.exists(f"{additionals.BASE_DIR}/logs")
def test_phase_decorator(additionals):
class BadClass:
@MTModule.phase("somekey")
def improper_func(self):
pass
class GoodClass(MTModule):
@MTModule.phase("somekey")
def proper_func(self):
self.logger("we did something.")
return "no error"
# test that a decorated method carries through its return value
gc = GoodClass({}, "my_good_mod", storage=LocalStorage(folder=additionals.BASE_DIR))
# test that a decorated method carries through its return value
gc = GoodClass({}, "my_good_mod", storage=LocalStorage(folder=additionals.BASE_DIR))
assert gc.proper_func() == "no error"
with open(f"{additionals.BASE_DIR}/logs/logs.txt", "r") as f:
lines = f.readlines()
assert len(lines) == 1
assert lines[0] == "my_good_mod: somekey: we did something.\n"
# check that logs were cleared after phase
assert gc._MTModule__LOGS == []
def test_parallel_phase_decorator(additionals):
class GoodClass(MTModule):
@MTModule.phase("somekey")
def func(self, gen):
self.logger("This function only takes a generator of elements.")
return "no error"
@MTModule.phase("somekey", remove_db=False)
def func_no_remove(self, gen):
return "no error"
@MTModule.phase("secondkey")
def func_w_arg(self, gen, extra):
self.logger(f"Running func with {list(gen)}, with extra arg {extra}.")
return "no error"
# test that a decorated method carries through its return value
gc = GoodClass({}, "my_good_mod", storage=LocalStorage(folder=additionals.BASE_DIR))
# test parallel logs
eg_gen = (a for a in range(0, 100))
assert gc.func(eg_gen) == "no error"
with open(f"{additionals.BASE_DIR}/logs/logs.txt", "r") as f:
lines = f.readlines()
assert len(lines) == 100
# test db file generation
eg_gen = (a for a in range(0, 100))
assert gc.func_no_remove(eg_gen) == "no error"
dbfile = f"{gc.disk.base_dir}/{gc.UNIQUE_ID}.db"
with open(dbfile, "rb") as f:
_bytes = f.read()
assert len(_bytes) == 800 # 2 4-byte entries per item for 100 items
os.remove(dbfile)
# test that a function is resumed properly
eg_gen = (a for a in range(0, 50))
assert gc.func_no_remove(eg_gen) == "no error"
eg_gen = (a for a in range(0, 100))
assert gc.func(eg_gen) == "no error"
with open(f"{additionals.BASE_DIR}/logs/logs.txt", "r") as f:
lines = f.readlines()
assert len(lines) == 150
# test function with argument
eg_gen = (a for a in range(0, 100))
assert gc.func_w_arg(eg_gen, 10) == "no error"
|
/**
* Retrieves a ArtesaniaEntity with the fields of this ArtesaniaDTO
*/
public ArtesaniaEntity toEntity( )
{
ArtesaniaEntity entity = super.toEntity( );
entity.setArtesano( artesano.toEntity( ) );
return entity;
} |
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input1.txt", "r", stdin);
// for writing output to output.txt
freopen("output1.txt", "w", stdout);
#endif
int n;
cin >> n;
int t(0);
for(int a = 1; a <=n; a++){
for(int b = 1; b <=n; b++){
int c = sqrt(a*a+b*b);
if(c<=n && c>=b && c*c == a*a+b*b){
t++;
}
}
}
cout << t/2;
}
// #include<bits/stdc++.h>
// using namespace std;
// int n,a;
// main()
// {cin>>n;for(int i=1;i<=n;i++)
// {for(int j=i;j<=n;j++)
// {int x=sqrt(i*i+j*j);
// if(x<=n&&x>=j&&x*x==(i*i+j*j))a++;}}cout<<a;} |
// JSTypedArray returns a javascript TypedArray
// for the corresponding Go type.
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
func JSTypedArray(sliceOrArray interface{}) (js.Value, error) {
TypedArray, _ := typedArrayNameSize(sliceOrArray)
v := reflect.ValueOf(sliceOrArray)
len := v.Len()
array := js.Global().Get(TypedArray).New(len)
for i := 0; i < len; i++ {
array.SetIndex(i, v.Index(i).Interface())
}
return array, nil
} |
def error_correction():
if not path.exists("Databases"):
mkdir("Databases")
def check_db(db_name):
conn = sqlite3.connect(f"Databases/{db_name}")
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM user_music WHERE name=?", (encode_text("test_name"),)).fetchone()
except sqlite3.DatabaseError:
conn.close()
remove(f"Databases/{db_name}")
conn = sqlite3.connect(f"Databases/{db_name}")
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM user_playlists WHERE name=?", (encode_text("test_name"),)).fetchone()
except sqlite3.DatabaseError:
conn.close()
remove(f"Databases/{db_name}")
conn = sqlite3.connect(f"Databases/{db_name}")
cursor = conn.cursor()
try: cursor.execute("CREATE TABLE user_music (name, author, url, song_time, num, song_id)")
except: pass
try: cursor.execute("CREATE TABLE user_playlists (name, music, playlist_id)")
except: pass
conn.commit()
conn.close()
check_db("database2.sqlite")
check_db("database3.sqlite") |
import { JupyterFrontEndPlugin } from '@jupyterlab/application';
import { CommandEntryPoint } from '../../command_manager';
export declare const FileEditorContextMenuEntryPoint: CommandEntryPoint;
export declare const FILE_EDITOR_ADAPTER: JupyterFrontEndPlugin<void>;
|
/**
* Directory in Giraffa is a row, which associates file and sub-directory names
* contained in the directory with their row keys.
*/
public class DirectoryTable implements Serializable {
private static final long serialVersionUID = 987654321098765432L;
private Map<String,RowKey> childrenKeys;
public DirectoryTable() {
childrenKeys = new HashMap<String,RowKey>();
}
@SuppressWarnings("unchecked")
public
DirectoryTable(byte[] list) throws IOException, ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(list));
try {
childrenKeys = (HashMap<String,RowKey>) in.readObject();
} catch (IOException e) {
throw e;
} catch (ClassNotFoundException e) {
throw e;
} finally {
in.close();
}
}
public Collection<RowKey> getEntries() {
return Collections.unmodifiableCollection(childrenKeys.values());
}
int size() {
return childrenKeys.size();
}
public boolean isEmpty() {
return size() == 0;
}
boolean contains(String fileName) {
return childrenKeys.containsKey(fileName);
}
RowKey getEntry(String fileName) {
return childrenKeys.get(fileName);
}
public boolean addEntry(RowKey child) {
return childrenKeys.put(new Path(child.getPath()).getName(), child) == null;
}
public boolean removeEntry(String fileName) {
return childrenKeys.remove(fileName) != null;
}
public byte[] toBytes() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(bos);
objOut.writeObject(childrenKeys);
byte[] retVal = bos.toByteArray();
objOut.close();
return retVal;
}
} |
def make_new_store(
product_config_path
):
engine = create_engine('sqlite://')
m.Base.metadata.create_all(engine)
store = sessionmaker(bind=engine)()
with open(product_config_path) as f:
product_dict = yaml.safe_load(f)
populate(
product_dict,
store
)
return store |
EllaOne: More Effective Morning-After Contraceptive Pill Now Available in UK Without Prescription
[email protected] By Staff Writer May 03, 2015 06:15 PM EDT
An emergency after-morning pill that works up to five days after unprotected sexual intercourse is now for sale in UK pharmacies.
The pill called ellaOne is an effective contraceptive method to prevent pregnancy in women and can be taken up to 120 hours or five days after unprotected sexual intercourse, 48 hours or 2 days longer than the conventional commercially-available morning-after pill according to Daily Mail UK.
But according to Tony Fraser of HRA Pharma, it is more effective if you take the pill as soon as possible. "The pills work by stopping the egg being released. The longer you wait there is more chance the egg will be released, which is why taking it as soon as possible is key," he said via a BBC report.
EllaOne has been available since 2009 in UK but could only be acquired through family planning clinics or from a doctor. It was then since made available across UK pharmacies after its licensing was amended by the European Union. Each pill is now sold without prescription at a retail price of around £30.
Fraser also explained via the BBC report why this "great news for women" wasn't announced to the general public for a month.
"One of the reasons we haven't gone out to get media attention is because what we want to do first is get the product into pharmacies, and roll out a training package to pharmacists in the UK.
"We wanted to make sure pharmacists are aware of what they are doing in terms of bringing another morning-after pill into the consultation that women have."
A previous clinical study published in The Lancet found that there is only nine out of 1000 chance that they could get pregnant after unprotected sexual intercourse if they take ellaOne. The article was published in 2010 and sponsored by HRA Pharma.
Jason Warriner, clinical director at Marie Stopes, a family planning clinic believes ellaOne is effective as a contraceptive pill.
"It's a brilliant step forward, looking at women's rights and empowering women," he said.
"It widens the choices around emergency contraception for women. For example at bank holiday weekends when other main services could be closed."
However, Mark Bhagwandin from Life charity criticized the pill availability when it comes to teenagers.
"Powerful pills like these are going to do nothing to curb extremely high rates of STIs among teenagers," he said via UK Daily Mail.
"The five-day pill will only have the effect of lulling teenagers into a false sense of security, convincing them that they are fine to have unprotected sex followed by emergency contraception.
"We have to address high levels of STIs, and the five-day pill does not help things."
0 Subscribe to the latinos health newsletter! |
import os
import sys
import logging
from sys import path
from root_logging import create_logger, exception
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, dir_path)
LOGS = False
# Create Logger for debug mode in local
if LOGS:
logs_filename = os.path.join(dir_path, 'exc_logs.log')
logger = create_logger(logs_filename=logs_filename)
else:
logger = None
# while not content:
# if time() - start > timeout:
# break
# sleep(1)
if __name__=='__main__':
print('there')
logger = create_logger('main', debug=True)
DEBUG=True
@exception(logger, DEBUG)
def test_logger(a):
return a/0
test_logger(2)
logger.debug('¤¤¤This is a debug message¤¤¤') |
package docker
import (
"bytes"
"context"
"errors"
"io/ioutil"
"net/http"
"testing"
dtypes "github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/stretchr/testify/assert"
"github.com/guumaster/hostctl/pkg/types"
)
func TestNew(t *testing.T) {
opts := &Options{
Domain: "test",
}
err := checkCli(opts)
assert.NoError(t, err)
assert.NotNil(t, opts)
assert.NotNil(t, opts.Cli)
}
func TestGetNetworkID(t *testing.T) {
cli := newClientWithResponse(t, map[string]string{
"/v1.22/networks": `[
{"Id": "networkId1", "Name": "networkName1" },
{"Id": "networkId2", "Name": "networkName2" }
]`,
})
t.Run("By Name", func(t *testing.T) {
net, err := GetNetworkID(context.Background(), cli, "networkName2")
assert.NoError(t, err)
assert.Equal(t, "networkId2", net)
})
t.Run("By Name error", func(t *testing.T) {
_, err := GetNetworkID(context.Background(), cli, "invent")
assert.True(t, errors.Is(err, types.ErrUnknownNetworkID))
})
t.Run("By Name empty", func(t *testing.T) {
list, err := GetNetworkID(context.Background(), cli, "")
assert.NoError(t, err)
assert.Empty(t, list)
})
}
func TestGetContainerList(t *testing.T) {
cli := newClientWithResponse(t, map[string]string{
"/v1.22/networks": `[
{"Id": "networkId1", "Name": "networkName1" },
{"Id": "networkId2", "Name": "networkName2" }
]`,
"/v1.22/containers/json": `[{
"Id": "container_id1", "Names": ["container1"],
"NetworkSettings": { "Networks": { "networkName1": { "NetworkID": "networkID1", "IPAddress": "172.16.58.3" }}}
}, {
"Id": "container_id2", "Names": ["container2"],
"NetworkSettings": { "Networks": { "networkName1": { "NetworkID": "networkID1", "IPAddress": "192.168.127.12" }}}
}]`,
})
list, err := GetContainerList(&Options{
Cli: cli,
})
assert.NoError(t, err)
assert.Len(t, list, 2)
assert.IsType(t, dtypes.Container{}, list[0])
assert.IsType(t, dtypes.Container{}, list[1])
assert.Equal(t, "networkID1", list[1].NetworkSettings.Networks["networkName1"].NetworkID)
assert.Equal(t, dtypes.Container{
ID: "container_id1",
Names: []string{"container1"},
NetworkSettings: list[0].NetworkSettings, // simplify the comparison
}, list[0])
assert.Equal(t, dtypes.Container{
ID: "container_id2",
Names: []string{"container2"},
NetworkSettings: list[1].NetworkSettings, // simplify the comparison
}, list[1])
}
type transportFunc func(*http.Request) (*http.Response, error)
func (tf transportFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return tf(req)
}
func newClientWithResponse(t *testing.T, resp map[string]string) *client.Client {
t.Helper()
v := "1.22"
c, err := client.NewClient("tcp://fake:2345", v,
&http.Client{
Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
url := req.URL.Path
b, ok := resp[url]
if !ok {
b = "{}"
}
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(b))),
}, nil
}),
},
map[string]string{})
assert.NoError(t, err)
return c
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.