content
stringlengths 10
4.9M
|
---|
n = int(raw_input())
res = 0
x = 1
while True:
t = x
p = 1
s = 0
while t:
s += p*(t%2)
t /= 2
p *= 10
if s > n: break
res += 1
x += 1
print res
|
//Set sets the value for the average counting.
func (a *Avg) Set(in int) {
a.mlock.Lock()
defer a.mlock.Unlock()
a.count++
a.sum += in
} |
<reponame>edotau/goFish<filename>code/code.go
// Package code describes biological sequence letters coded by bytes and sometimes encoded into hash int64s
package code
|
<gh_stars>0
//import { App, AppProps, Annotations } from 'aws-cdk-lib';
//import { Construct } from 'constructs';
import { Project } from '../src/project';
import { resetRegionEnvironmentalVariables } from './utils/reset-region';
const config = {
name: 'foo',
author: {
organization: 'Acme Corp',
name: '<NAME>',
email: '<EMAIL>',
},
accounts: {
dev: {
id: '111111111111',
config: {
baseDomain: 'example.net',
some: {
deep: {
object: 'foo',
},
},
},
},
prod: {
id: '222222222222',
config: {
baseDomain: 'example.com',
some: {
deep: {
object: 'foo',
},
},
},
},
},
};
describe('Project initialization', () => {
beforeEach(resetRegionEnvironmentalVariables);
afterEach(resetRegionEnvironmentalVariables);
test('without region', () => {
const project = new Project({ ...config });
expect(project.node.tryGetContext(Project.CONTEXT_SCOPE)).toMatchObject({ ...config, defaultRegion: 'us-east-1' });
});
test('with explicit region', () => {
const project = new Project({ ...config, defaultRegion: 'eu-west-1' });
expect(project.node.tryGetContext(Project.CONTEXT_SCOPE)).toMatchObject({ ...config, defaultRegion: 'eu-west-1' });
});
test('with region via CDK_DEFAULT_REGION', () => {
process.env.CDK_DEFAULT_REGION = 'eu-north-1';
const project = new Project({ ...config });
expect(project.node.tryGetContext(Project.CONTEXT_SCOPE)).toMatchObject({ ...config, defaultRegion: 'eu-north-1' });
});
test('with region via AWS_REGION', () => {
process.env.AWS_REGION = 'eu-central-1';
const project = new Project({ ...config });
expect(project.node.tryGetContext(Project.CONTEXT_SCOPE)).toMatchObject({ ...config, defaultRegion: 'eu-central-1' });
});
});
|
// handle DownloadRequests by sending the request to the book server
func (c *Client) sendDownloadRequest(d *DownloadRequest) {
core.DownloadBook(c.irc, d.Book)
c.send <- WaitResponse{
MessageType: WAIT,
Status: "Download request received",
}
} |
class StarSystem:
"""A star system."""
def __init__( self, aName):
self._name = aName
self._techLevel = fudgeThrow()
self._envLevel = fudgeThrow()
self._resLevel = fudgeThrow()
def getName( self):
return self._name
def getScore( self):
"""System's "score": sum of tech, env and res levels."""
return self._techLevel + self._envLevel + self._resLevel
def getTechLevel( self):
return self._techLevel
def setTechLevel( self, aTechLevel):
self._techLevel = aTechLevel
def getEnvLevel( self):
return self._envLevel
def getResLevel( self):
return self._resLevel
def toString( self):
return "{0}: T{1} E{2} R{3}, score= {4}".format(
self._name, self._techLevel, self._envLevel, self._resLevel, self.getScore()) |
import java.util.*;
public class codeforces {
public static void main(String[] args){
//System.out.println(maxPath(new long[][]{{1,1,1},{1,-1,1},{1,1,1}}));
Scanner input = new Scanner(System.in);
int n = input.nextInt();
long[][] a = new long[3][n];
for(int i = 0; i < 3;i++){
for(int j = 0; j < n;j++){
a[i][j] = input.nextLong();
}
}
System.out.println(maxPath(a));
}
private static long max(long first,long ... ls){
long max = first;
for(long number:ls){
max = Math.max(number, max);
}
return max;
}
static long maxPath(long[][] arr){
long[][] sol = new long[3][arr[0].length + 20];
for(int i = 0; i < 3;i++){
for(int j = 0; j < sol[i].length;j++){
sol[i][j] = -1000000000000000000L;
}
}
long s = 0L;
sol[0][0] = 0L;
for(int i = 0; i < arr[0].length;i++){
sol[0][i + 1] = max(sol[0][i + 1],sol[0][i] + arr[0][i], sol[1][i] + arr[1][i] + arr[0][i], sol[2][i] + arr[2][i] + arr[1][i] + arr[0][i]);
sol[1][i + 1] = max(sol[1][i + 1],sol[0][i] + arr[1][i] + arr[0][i],sol[1][i] + arr[1][i],sol[2][i] + arr[2][i] + arr[1][i]);
sol[2][i + 1] = max(sol[2][i + 1],sol[0][i] + arr[0][i] + arr[1][i] + arr[2][i], sol[1][i] + arr[1][i] + arr[2][i],sol[2][i] + arr[2][i]);
if(i + 2 <= arr[0].length){
s = arr[0][i] + arr[1][i] + arr[2][i] + arr[0][i + 1] + arr[1][i + 1] + arr[2][i + 1];
sol[0][i + 2] = max(sol[0][i + 2],sol[0][i] + s);
sol[0][i + 2] = max(sol[0][i + 2],sol[2][i] + s);
sol[2][i + 2] = max(sol[2][i + 2],sol[0][i] + s);
sol[2][i + 2] = max(sol[2][i + 2],sol[2][i] + s);
}
}
return sol[2][arr[0].length];
}
} |
def PrepareClientVm(self, vm):
super(Redshift, self).PrepareClientVm(vm)
self.InstallAndAuthenticateRunner(vm) |
Ron Dziuda’s family calls it "the black cloud.’’
When Ron applies for hundreds of jobs and no one calls back with an offer? The Black Cloud. When his daughter applies for her dream position and someone else gets it? The Black Cloud. Or when he and his wife Sue celebrate their anniversary with a dinner out and they suffer pangs of guilt over the bill?
Advertisement:
Sue shakes her head and tries to explain this concept at her dining room table.
"There’s that black cloud again.’’
The black cloud – this nagging sense that things will go wrong and never get quite right again – appeared over the Dziudas’ life in July 2009 when he lost his sales and marketing job at industrial components-maker Misumi USA. At first, it didn’t seem that bad. This father of four had lost jobs before. His experience, smarts and can-do attitude always helped him bounce back.
But this was in the depths of America’s most punishing economic crisis since the Great Depression. Unemployment was rising fast and job-seekers of any age were having the toughest times of their lives finding work. And Ron wasn’t just any age – at 54, he started finding his gray hair and crow’s feet overshadowed his expertise and energy.
So the black cloud moved in to stay. For three years – 33 months, to be exact – Ron endured a drumbeat of humiliations: he lost his job, his savings, his confidence. He and Sue burned down their retirement accounts one by one; they borrowed from their own son to pay the mortgage; they racked up credit card debt to put food on the table. Ron applied for 800 jobs. One night he turned to Sue and confessed he didn’t think he’d ever get back on his feet.
He finally emerged in the spring of 2012 with a position selling sandblasters for Pangborn Group. At last he was out of the woods. But the black cloud barely budged. They shake their heads when I ask if they’ll ever feel secure again.
Advertisement:
"Now to rebuild everything I had, and build from there and even try to build for retirement? It's going to be incredible,’’ Ron says. ``I mean all the credit cards are maxed out, so those got to be paid off, and there's no equity in the house ...’’
Sue is blunter.
"I’ll still live in fear,’’ she says. "I don’t know if I’ll ever feel comfortable.’’
The Great Recession took down millions of people like Dziuda, bringing devastation in very specific ways to older workers. It upended the final decade of their careers, drained their nest eggs and sentenced them to years of joblessness. It sapped the confidence of a generation of Americans on the cusp of a comfortable retirement. Above all, the recession has helped create a core group of Americans in their 50s and 60s who need to work many more years to make back what they lost.
Advertisement:
Many may never get there.
The most immediate effect of the recession on older Americans was a sharp spike in joblessness. In May 2012, the unemployment rate for workers aged 55 and older stood at 6.5 percent—less than the overall rate that month of 8.2 percent, but double what it was for older workers five years earlier. By January 2015, it had come down to 5.1 percent, but still significantly higher than pre-recession rates.
And that might not be a disaster, if it didn’t take jobless 55-year-olds so long to get hired again. An AARP analysis of April 2014 labor numbers showed unemployed workers aged 55 and older were jobless for an average of 51 weeks, compared to 35 weeks for younger Americans.
Advertisement:
So an older worker who loses a job can look forward to many months—or even years—struggling to get hired again.
That’s exactly what happened to Ron Dziuda.
* * *
The axe was about to fall. He could feel it.
It was July 2009 and the economy had bottomed out. Unemployment was at 9.5 percent and still headed south. Dziuda had been working for Misumi USA in Schaumburg, Illinois, about 40 miles north of his home in Plainfield, for more than five years, selling components like switches and sensors and ball screws.
Advertisement:
But he had a bad feeling. In the spring, managers told him his performance was falling short. Dziuda thought that couldn’t be. To his mind, the problem was unrealistic expectations. Misumi’s sales targets were just too high, he argued. They weren’t convinced.
“It was coming,” he said. “The writing was on the wall.”
Still, Dziuda didn’t panic. After getting a night-school degree in marketing from University of Detroit in 1985, Dziuda—the oldest of five children—worked at a series of employers across the Midwest. Each job change usually meant something better.
In the late 1990s, he and his family settled into a four-bedroom home in a subdivision called Wesmere Estates. Portraits of the Dziudas and their four children hang in the wall along the carpeted stairs in their home. Stenciled in script above the photos is the legend, “All Because Two People Fell in Love.”
Advertisement:
Still, Dziuda was subject to the ebb and flow of the economy. In 2001, he picked up a part-time job at Target to tide him over between jobs. Then Misumi came along in 2004 with an offer that fit perfectly. He liked them, they liked him, and Dziuda hoped the years of bouncing from job to job were over.
But by July 2009, his prospects had dimmed. One morning a human resources manager called him into a meeting where company officials told him it was over. He signed an agreement not to take a job with a competitor for a year in exchange for a three-month severance package.
He was 54, out of a job at the bottom of the worst recession since the 1930s, with one kid in college, another one about enter. And it would be a long time before he got back on his feet.
* * *
Advertisement:
Dziuda could see he was part of a growing wave. From the outset of the recession in December 2007 until his last full month at Misumi, the number of unemployed 50-plus workers more than doubled, from 1.4 million to 3.2 million.
Thanks to previous bouts of unemployment, he knew the drill. He updated his resume. He signed up at job clubs like the one at the nearby St Mary Immaculate Church. He called up people he used to work with, applied for every job he could find. He registered on Internet job boards like Monster and Careerbuilder. He went to collect unemployment, despite the humilation; he had a family to feed.
Interviews were a little harder to come by than they had been in the past, but things were moving. He’d sold himself, communicated his ideas and the value he’d bring to the company. He’d met company officials over several hours in the morning, gone to lunch, parted with warm handshakes.
And then nothing happened.
Advertisement:
By the opening of 2010, Dziuda could see the economy wasn’t going to roar back into shape anytime soon. Instead of getting better with the official end of the recession in June 2009, things seemed to be getting worse. Unemployment was higher than when Dziuda was laid off, edging up to 9.7 percent. He was plugging away part-time at Target at $13 an hour. When he wasn’t working, he pounded the pavement.
His family struggled to adjust. Sue loaded on the jobs. She subbed at the local school district and worked as a teachers’ aide. In the late afternoons she sold fragrances at the mall. After dinner, she gave fitness classes. Back home at 10 p.m., she worked till midnight marking standardized tests online.
"My fitness training was actually my sanity,’’ Sue recalls. "I needed to work out at that point – otherwise I would have cried.’’
Dziuda’s doubts began to gnaw at him as the months went by, and the Excel log of job applications he kept on his computer ran to the dozens, and then the hundreds. Before he knew it, he was part of that statistic he’d never expected to join: the long-term unemployed. Dziuda says Sue kept any doubts she had largely to herself, but he could almost hear the tape of thoughts running through her mind:
Advertisement:
What do you think? You think you’re going to find something? Really? Do you really think you’re going to find something?
By the second half of 2010, Dziuda was in deep unemployment. He and Sue began to consume the nest eggs that had been meant to grow, hatch and mature in retirement. One by one, these keepsakes of Dziuda’s employment history were taken from the safe and sold off.
The $4,000 pension left over from from Panasonic.
Gone.
Advertisement:
The $4,000 IRA.
Cashed in.
The $5,000 in stock from his days at GM and Detroit Edison.
Turned to dust when GM filed for bankruptcy.
Then came 2011. Another year of dwindling faith.
* * *
While his wife worked at the school, or in the aerobics studio, or at the mall selling fragrances, Dziuda was at home loading the washer or unloading the dryer, vacuuming the living room carpet. They bickered over the way he folded the laundry. The new job wasn’t materializing, and the money just wasn’t coming in. But the water bill arrived every month on time. And the electricity bill. And the gas bill. And the mortgage.
With their savings depleted, the couple took a deep breath and did what many desperate families of the Great Recession did: they went into debt. Dziuda turned to his own son, the eldest, a Purdue grad with an engineering job, for a $5,000 loan to make the house payment and avoid foreclosure. Then came a second mortgage on the house. They dipped into their daughter’s student loan fund and ended up owing her $3,000.
All the while, prospective employers seemed impossible to please. The companies were just too scared to hire, holding out for a sure thing, leaving hopefuls—by August 2011, 3.3 million 50-plus workers were jobless and looking for employment—to wallow for months while they deliberated. Or, Dziuda found, employers would hold his experience against him. You’re over-qualified, they told him, and even if we hire you, you’ll be out the door once something better comes along.
In September 2011, his unemployment insurance tapped out. Now the Dziudas were truly on their own. He would have to take whatever full-time work he could find to stay afloat.
Target, where he’d worked off and on since 2002, was the logical choice. The position was called Store Facilities Technician, but some of the duties—tending to clogged toilets and blown-out light bulbs—weren’t so technical. But Dziuda was desperate and willing to work hard for the sake of boosting his hourly pay by three bucks, from $13 to $16.
So he applied – and endured nine interviews for the sake of an annual salary of about $30,000—a fraction of what he’d made in his former life. That was above the poverty line for a family of four in 2011, but not by much. He filled in the gaps by substitute teaching at the local school district.
Rock bottom was not that far away. Dziuda had applied for 653 jobs in two years, fully documented on the family computer, with at least another 100 or so on top of that – with not a single viable offer. They had stopped buying anything beyond bedrock essentials, scraped by just to get clothes for the kids at Christmas. Retirement gone. The credit cards were close to maxed out; Sue was using them for food and gas.
Their children struggled to understand.
"My kids were embarrassed that their dad worked at Target and their daddy substitute taught and they were like, 'Don’t come to my school, I don’t want anybody to know,’’’ said Sue. "It was very embarrassing.’’
Dziuda wondered: Was Target the best he could hope for? Was this the end of the road?
He turned to Sue.
“You know what?” he told her. “This might be it. I hate to say it, and I’ll never stop looking for something better. But this might be it.”
Sue shook her head.
"No, you’ve gone this far, you can’t stop,’’ she told him. "There’s something out there for you and you have to believe and you just have to keep going for it.’’
* * *
By early 2012 Dziuda was trying really hard to feel lucky. He was turning to the basics for sustenance: His 30-year marriage; the health of his four children.
And his faith. Dziuda had been a steadily practicing Catholic, carrying on the religion his family had brought with them from Poland in the early 20th century. He’d memorized a prayer for the unemployed which he recited to himself. And now, in his resignation, he and Sue were ready to put their fate in God’s hands.
Can God get you a job? Dziuda says He can. That’s how he explains the mystery that once he acknowledged his exhaustion and leaned on his faith for help, a door opened.
Dziuda came across a job ad on the Internet for selling sandblasters. Pangborn Group. Around since 1904. Then a guy at St. Mary pointed out the same job. Did you see this ad? Was this the sign Dziuda was waiting for? He applied.
Before he knew it, he was at a hotel in Chicago for an interview with two managers. Two guys his age, no impression that his gray hair or wrinkles around the eyes bothered them. Then a plane ride to headquarters in Atlanta for more talks.
Nothing happened for a while. Just like all the other times.
One day the phone rang.
One of the recruiters Dziuda had met in Atlanta was going up to Chicago for work and he asked to meet. He put on a tie and jacket, drove to a Longhorn Steakhouse off I-55. The recruiter took one look at Dziuda and shook his head. There was no reason for a tie. After all, the tough part was over: the recruiter was there to make Dziuda an offer.
Dziuda listened to the details, but his head was already drifting into the clouds. He got in his car and pulled carefully out of the parking lot, trying to contain his excitement. He drove home with the same thoughts over and over running through his head: My God, I got a job. I actually have a job. Oh my God, I never thought this would happen.
I have a job.
Three years of searching were at an end. The eating up the savings, the racking up of credit card debt, the sad, desperate move to borrow money from their own children. The dinners of instant ramen and hot dogs. But Dziuda says there were no tears of gratitude. Instead, he and Sue just sighed heavily with exhausted relief. They could start making the house payment again.
* * *
It was a few days later when I watched him stand up at the job group at St. Mary and make his announcement: after three years in the wilderness, he had finally landed a job. At 57, he was back in the game.
“I had to let go. That’s the toughest part. Let it go. Let God. We continue to use our God-given skills to find that job,’’ he said as heads around the room nodded.
“Continue to find that job – it’s out there.’’
The celebration was short. He had a long struggle ahead to dig his family out of a financial hole. Dziuda and his wife have started making payments on their mortgage from their income again, and their youngest child, a son, left the house for the University of Wisconsin, Madison, in August 2012. His children have resigned themselves to facing college debt loads when they go out into the work world.
The scars—financial and emotional—from his three-year battle with the job market are still there. They may never fade entirely. He’s kept his part-time job at Target. Will the job at Pangborn still be here next year? Can he learn shot-blast equipment fast enough and well enough to be successful? Will he be able to retire from this job, or will he again be on the job-search rollercoaster at an even older age?
Dziuda’s answer to all those questions is the same: I don’t know.
“I guess my biggest thing is: how long is this going to last?”
The world, in some ways, has dimmed. The past several years have been ones of disappointment and humiliation. The future is uncertain. He sees his kids graduating with loads of debt, moving into a shaky job market. It doesn’t seem fair.
And the black cloud is still there, just over their shoulders. It hovered over them at Ron and Sue’s 30th wedding anniversary celebration in the fall of 2013, when they hesitated to buy themselves a nice dinner out, thinking about how much it would cost.
"There’s a guilt that comes with everything we do now, and my kids are like, 'You gotta stop that,’’’ says Sue. "Because sometimes I think it’s too good, it’s gonna end. Is it gonna be taken away from us again? I don’t like that feeling, but that’s what this experience has done. It’s like I don’t ever feel secure.’’
At the same time, though, Dziuda is deeply thankful. He kept his house. He has a solid job.
But he’s clear about one thing: he won’t be retiring anytime soon. At this point, he’s hoping to stay healthy enough to work for at least for 15 years to rebuild—putting him in his 70s before he can downshift. For now, he’s putting all expectations of retirement out of his mind.
“In one way, shape or form, or another,” he said, “I will probably work for the rest of my life.”
Reprinted from "Unfinished Work: The Struggle to Build an Aging American Workforce" by Joseph Coleman, with permission from Oxford University Press, USA, ©Joseph Coleman, 2015. All rights reserved. |
// parent = parent of current node
private static void dfs(int root, int parent, int[] disc, int[] low, boolean[] visited, Map<Integer, List<Integer>> graph, List<List<Integer>> out) {
visited[root] = true;
disc[root] = time++;
low[root] = disc[root];
List<Integer> neighbors = graph.get(root);
if (neighbors == null) {
return;
}
for (Integer nei : neighbors) {
if (nei == parent) {
continue;
}
if (!visited[nei]) {
dfs(nei, root, disc, low, visited, graph, out);
low[root] = Math.min(low[root], low[nei]);
if (disc[root] < low[nei]) {
out.add(Arrays.asList(root, nei));
}
} else {
low[root] = Math.min(low[root], disc[nei]);
}
}
} |
use crate::buffer::Buffer;
use crate::term::Term;
use crate::term_seq::ClearScreen;
use crate::term_seq::Goto;
use std::io;
use std::io::prelude::*;
pub struct Tui {
buf: Buffer,
term: Term<io::Stdout>,
}
impl Tui {
pub fn new() -> Self {
Self {
buf: Buffer::new(),
term: Term::new(io::stdout()).expect("Failed to set up terminal"),
}
}
fn handle_input(&mut self, input: u8) {
self.buf.insert(input);
}
pub fn run(&mut self) {
if cfg!(feature = "debug_inputs") {
loop {
match read_input(&mut io::stdin()) {
Ok(Input::Etx) => return,
Ok(input) => write!(self.term, "Input = {:?}\r\n", input).unwrap(),
Err(err) => write!(self.term, "{}\r\n", err).unwrap(),
}
}
} else {
loop {
if let Ok(input) = read_input(&mut io::stdin()) {
match input {
Input::Etx => return,
Input::Left => {
self.buf.seek(io::SeekFrom::Current(-1)).unwrap();
}
Input::Right => {
self.buf.seek(io::SeekFrom::Current(1)).unwrap();
}
Input::Enter => self.handle_input(b'\n'),
Input::Utf8(c) => self.handle_input(c as u8),
_ => {}
};
self.draw().expect("Failed to draw to the screen");
}
}
}
}
fn draw(&mut self) -> io::Result<()> {
let mut out = io::stdout();
write!(
self.term,
"{}{}{}",
Goto(1, 1),
ClearScreen,
self.buf.to_string()
)?;
out.flush()?;
Ok(())
}
}
impl Default for Tui {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, PartialEq)]
enum Input {
Etx, // End of text (Ctrl-C interrupt)
Sub, // Substitute (Ctrl-Z suspend)
Esc,
Enter,
Tab,
BackTab,
Up,
Down,
Right,
Left,
Backspace,
Insert,
Delete,
Home,
End,
PgUp,
PgDown,
Utf8(char),
}
fn read_input<R>(stdin: &mut R) -> Result<Input, String>
where
R: Read,
{
let mut buf = [0u8; 512]; // Arbitrary choice of 512
let len = stdin.read(&mut buf).unwrap();
match &buf[0..len] {
[0x03] => Ok(Input::Etx),
[0x09] => Ok(Input::Tab),
[0x1A] => Ok(Input::Sub),
[0x1B] => Ok(Input::Esc),
[0x7F] => Ok(Input::Backspace),
[0x0A] => Ok(Input::Enter),
[0x0D] => Ok(Input::Enter),
b"\x1B[A" => Ok(Input::Up),
b"\x1B[B" => Ok(Input::Down),
b"\x1B[C" => Ok(Input::Right),
b"\x1B[D" => Ok(Input::Left),
b"\x1B[F" => Ok(Input::End),
b"\x1B[H" => Ok(Input::Home),
b"\x1B[Z" => Ok(Input::BackTab),
b"\x1B[1~" => Ok(Input::Home),
b"\x1B[2~" => Ok(Input::Insert),
b"\x1B[3~" => Ok(Input::Delete),
b"\x1B[4~" => Ok(Input::End),
b"\x1B[5~" => Ok(Input::PgUp),
b"\x1B[6~" => Ok(Input::PgDown),
b"\x1B[7~" => Ok(Input::Home),
b"\x1B[8~" => Ok(Input::End),
buf if len == 1 && buf[0] >= 0x20 && buf[0] < 0x7F => Ok(Input::Utf8(buf[0] as char)),
_ => Err(format!(
"Unhandled input. Length = {}, Buf = {:?}",
len,
&buf[0..len]
)),
}
}
|
def _config2von(self, config: dict, access: str = None) -> dict:
rv = {k: config.get(k, self._defaults[k]) for k in ('auto_create', 'auto_remove')}
rv['access'] = access or self.default_access
for key in ('seed', 'did', 'link_secret_label'):
if key in config:
rv[key] = config[key]
return rv |
TERMS OF SALE EVERYTHING IS SOLD “AS IS - WHERE-IS”. EVERYTHING MUST BE PAID FOR IN FULL AND REMOVED BY 4:00 P.M. DAY OF SALE. Although we believe the descriptions of the items to be correct, neither Rosen Auctions, The Attorney General nor any Consignor makes any representations or warranty as to the condition of the property or as to the correctness of description of said property. NO PERSONAL OR BUSINESS CHECKS . Payment f or vehicles may only be made by Cash, Cashier’s Check (payable to C&E Auctions) or Travelers Checks . Visa & MasterCard accepted for the other items. Everything is sold “as-is”. All sales are final. Several Items have current appraisals. Some items may be subject to a minimum bid. Answers To Frequently Asked Auction Questions |
IMPROVED ARTIFICIAL NEURAL NETWORK THROUGH METAHEURISTIC METHODS AND ROUGH SET THEORY FOR MODERN MEDICAL DIAGNOSIS
A novel meta-heuristic soft computing model with feature selection implemented using Rough set (RS) theory for the diagnosis of coronary artery disease in diabetes patients is proposed in this study. The binary classification method in multiclass classification problems is applied by the One Versus Rest approach (OVR) is incorporated. To avoid the redundancy problem, a mathematical approach known as rough-set theory (RS) is applied to identify the most significant features from the dataset. The Artificial Neural Network with improved hidden layers is used as the classifier which is optimized through a metaheuristic population-based method, known as the Grasshopper Optimization Algorithm (GOA) with a single objective optimization approach integrated for improving the accuracy of the model. Mean Square Error (MSE) is taken as the objective function and the result shows that the accuracy of the model has been improved significantly from 89.1% to 95.25% after optimization. |
<gh_stars>0
package com.k1l3.wheredoesithurt.models;
import java.io.Serializable;
public class Day implements Serializable {
DayClick dayClick;
public Day() {
dayClick = new DayClick();
}
public DayClick getDayClick() {
return dayClick;
}
public void setDayClick(DayClick dayClick) {
this.dayClick = dayClick;
}
}
|
def top_right(self):
return self.rects[Scale.TOP_RIGHT] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.PreRepayPlanTermVO import PreRepayPlanTermVO
class AlipayPcreditLoanBudgetQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayPcreditLoanBudgetQueryResponse, self).__init__()
self._pre_repay_plan_term_list = None
self._repay_amt_total = None
self._repay_int_amt_total = None
self._repay_prin_amt_total = None
@property
def pre_repay_plan_term_list(self):
return self._pre_repay_plan_term_list
@pre_repay_plan_term_list.setter
def pre_repay_plan_term_list(self, value):
if isinstance(value, list):
self._pre_repay_plan_term_list = list()
for i in value:
if isinstance(i, PreRepayPlanTermVO):
self._pre_repay_plan_term_list.append(i)
else:
self._pre_repay_plan_term_list.append(PreRepayPlanTermVO.from_alipay_dict(i))
@property
def repay_amt_total(self):
return self._repay_amt_total
@repay_amt_total.setter
def repay_amt_total(self, value):
self._repay_amt_total = value
@property
def repay_int_amt_total(self):
return self._repay_int_amt_total
@repay_int_amt_total.setter
def repay_int_amt_total(self, value):
self._repay_int_amt_total = value
@property
def repay_prin_amt_total(self):
return self._repay_prin_amt_total
@repay_prin_amt_total.setter
def repay_prin_amt_total(self, value):
self._repay_prin_amt_total = value
def parse_response_content(self, response_content):
response = super(AlipayPcreditLoanBudgetQueryResponse, self).parse_response_content(response_content)
if 'pre_repay_plan_term_list' in response:
self.pre_repay_plan_term_list = response['pre_repay_plan_term_list']
if 'repay_amt_total' in response:
self.repay_amt_total = response['repay_amt_total']
if 'repay_int_amt_total' in response:
self.repay_int_amt_total = response['repay_int_amt_total']
if 'repay_prin_amt_total' in response:
self.repay_prin_amt_total = response['repay_prin_amt_total']
|
package test
import (
"github.com/stretchr/testify/mock"
bussiness "gomux_gorm/src/auth_module/bussiness/entities"
token "gomux_gorm/src/auth_module/frameworks/token"
)
// DecodedTokenSpy ...
type DecodedTokenSpy struct {
mock.Mock
token.IDecodedToken
}
// Decoded ...
func (d *DecodedTokenSpy) Decoded(t string) (*bussiness.TokenDecodedEntity, error) {
args := d.Called(t)
return args.Get(0).(*bussiness.TokenDecodedEntity), args.Error(1)
}
|
/**
* This returns a statically allocated iterator that is backed by a vector. The vector
* makes it safe against concurrent modification exceptions, but after calling
* this function, you should iterate fully through the returned Iterator
* for garbage collection to be fully optimized.
* @return An Iterator that would otherwise return a concurrent modification
* exception. remove() is not supported.
*/
public Iterator<T> resetIterator() {
while( true ) {
try {
reusedIt.reset( data );
break;
} catch (ConcurrentModificationException cme) {
System.out.println( "WARNING: ConcurrentModificationException Occurred. Retrying..." );
}
}
return reusedIt;
} |
import numpy as np
import tifffile as tif
import torch
from pathlib import Path
import random
from torch.utils.data import Dataset
from typing import Callable, Optional, List, Tuple
class USGSSegmentationDataset:
def __init__(self, data_folder: Path, transform: Callable = None, mask: Optional[List[bool]] = None) -> None:
self.transform = transform
# We will only segment the images which we know have solar panels in them; the
# other images should be filtered out by the classifier
solar_folder = data_folder / 'solar'
self.org_solar_files = list((solar_folder / 'org').glob("*.tif"))
self.mask_solar_files = [solar_folder / 'mask' / f.name for f in self.org_solar_files]
assert len(self.org_solar_files) > 0, "No images found!"
assert len(self.org_solar_files) == len(self.mask_solar_files), "Length mismatch between images and masks!"
if mask is not None:
self.add_mask(mask)
def add_mask(self, mask: List[bool]) -> None:
"""Filters out files and masks not required for the current dataset split.add()
Args:
mask (List[bool]): list of bollean values, one for each tile, to decide whether to keep it or not.
"""
assert len(mask) == len(self.org_solar_files), \
f"Mask is the wrong size! Expected {len(self.org_solar_files)}, got {len(mask)}"
self.org_solar_files = [x for include, x in zip(mask, self.org_solar_files) if include]
self.mask_solar_files = [x for include, x in zip(mask, self.mask_solar_files) if include]
def __len__(self) -> int:
return len(self.org_solar_files)
def __getitem__(self, index: int) -> Tuple[torch.Tensor, torch.Tensor]:
x = tif.imread(self.org_solar_files[index]).transpose(1, 2, 0)
y = tif.imread(self.mask_solar_files[index])
if self.transform is not None:
pair = self.transform(image=x, mask=y)
x = pair.get("image")
y = pair.get("mask")
return x, y
class DydasSegmentationDataset(Dataset):
def __init__(
self,
data_folder: Path,
transform: Callable = True,
) -> None:
self.transform = transform
# find images and masks inside the specified folder
self.solar_files = sorted(list(data_folder.glob("*_rgbir.tif")))
self.mask_files = sorted(list(data_folder.glob("*_bin.tif")))
# check consistency
assert len(self.solar_files) == len(self.mask_files), "Images and masks mismatch!"
for img_path, msk_path in zip(self.solar_files, self.mask_files):
assert img_path.stem.replace("_rgbir", "") == msk_path.stem.replace("_bin", ""), \
f"Image and mask mismatch: '{img_path.stem}' - '{msk_path.stem}'"
def __getitem__(self, index: int) -> Tuple[torch.Tensor, torch.Tensor]:
x = tif.imread(self.solar_files[index]).astype(np.float32)[:3]
y = tif.imread(self.mask_files[index]).astype(np.float32) / 255.0
if self.transform is not None:
pair = self.transform(image=x, mask=y)
x = pair.get("image")
y = pair.get("mask")
return x, y
def __len__(self) -> int:
return len(self.solar_files)
|
/*Ham nhan ket qua tra ve*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode == RESULT_OK)
{Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
thumbnail = (BitmapFactory.decodeFile(picturePath));
if(thumbnail == null){
Toast.makeText(this,"Canh bao: khong the giai ma file chuong trinh co the dong!",Toast.LENGTH_LONG);
Log.e("MainActivity open fail:","Chuong trinh se dong!!");
}
else {
bmCache.putBitmap(picturePath, thumbnail);
Log.w("path of image from gallery......******************.........", picturePath + "");
chooseIamge = true;
main_openfileImage.setVisibility(View.INVISIBLE);
main_ImageView.setImageBitmap(thumbnail);
displayView(0);
}
}
break;
default:
break;
}
} |
/*
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.developer_cloud.assistant.v1;
import com.google.gson.JsonObject;
import com.ibm.watson.developer_cloud.assistant.v1.model.Counterexample;
import com.ibm.watson.developer_cloud.assistant.v1.model.CounterexampleCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateCounterexampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateDialogNodeOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateEntityOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateExampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateIntentOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateSynonymOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateValueOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.CreateWorkspaceOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteCounterexampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteDialogNodeOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteEntityOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteExampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteIntentOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteSynonymOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteUserDataOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteValueOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DeleteWorkspaceOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.DialogNode;
import com.ibm.watson.developer_cloud.assistant.v1.model.DialogNodeCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.Entity;
import com.ibm.watson.developer_cloud.assistant.v1.model.EntityCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.EntityExport;
import com.ibm.watson.developer_cloud.assistant.v1.model.EntityMentionCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.Example;
import com.ibm.watson.developer_cloud.assistant.v1.model.ExampleCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetCounterexampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetDialogNodeOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetEntityOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetExampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetIntentOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetSynonymOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetValueOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.GetWorkspaceOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.Intent;
import com.ibm.watson.developer_cloud.assistant.v1.model.IntentCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.IntentExport;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListAllLogsOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListCounterexamplesOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListDialogNodesOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListEntitiesOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListExamplesOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListIntentsOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListLogsOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListMentionsOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListSynonymsOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListValuesOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.ListWorkspacesOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.LogCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.MessageOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.MessageResponse;
import com.ibm.watson.developer_cloud.assistant.v1.model.Synonym;
import com.ibm.watson.developer_cloud.assistant.v1.model.SynonymCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateCounterexampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateDialogNodeOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateEntityOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateExampleOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateIntentOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateSynonymOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateValueOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.UpdateWorkspaceOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.Value;
import com.ibm.watson.developer_cloud.assistant.v1.model.ValueCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.ValueExport;
import com.ibm.watson.developer_cloud.assistant.v1.model.Workspace;
import com.ibm.watson.developer_cloud.assistant.v1.model.WorkspaceCollection;
import com.ibm.watson.developer_cloud.assistant.v1.model.WorkspaceExport;
import com.ibm.watson.developer_cloud.http.RequestBuilder;
import com.ibm.watson.developer_cloud.http.ServiceCall;
import com.ibm.watson.developer_cloud.service.WatsonService;
import com.ibm.watson.developer_cloud.service.security.IamOptions;
import com.ibm.watson.developer_cloud.util.GsonSingleton;
import com.ibm.watson.developer_cloud.util.ResponseConverterUtils;
import com.ibm.watson.developer_cloud.util.Validator;
/**
* The IBM Watson™ Assistant service combines machine learning, natural language understanding, and integrated
* dialog tools to create conversation flows between your apps and your users.
*
* @version v1
* @see <a href="http://www.ibm.com/watson/developercloud/assistant.html">Assistant</a>
*/
public class Assistant extends WatsonService {
private static final String SERVICE_NAME = "assistant";
private static final String URL = "https://gateway.watsonplatform.net/assistant/api";
private String versionDate;
/**
* Instantiates a new `Assistant`.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
*/
public Assistant(String versionDate) {
super(SERVICE_NAME);
if ((getEndPoint() == null) || getEndPoint().isEmpty()) {
setEndPoint(URL);
}
Validator.isTrue((versionDate != null) && !versionDate.isEmpty(), "version cannot be null.");
this.versionDate = versionDate;
}
/**
* Instantiates a new `Assistant` with username and password.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param username the username
* @param password the password
*/
public Assistant(String versionDate, String username, String password) {
this(versionDate);
setUsernameAndPassword(username, password);
}
/**
* Instantiates a new `Assistant` with IAM. Note that if the access token is specified in the
* iamOptions, you accept responsibility for managing the access token yourself. You must set a new access token
* before this
* one expires or after receiving a 401 error from the service. Failing to do so will result in authentication errors
* after this token expires.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param iamOptions the options for authenticating through IAM
*/
public Assistant(String versionDate, IamOptions iamOptions) {
this(versionDate);
setIamCredentials(iamOptions);
}
/**
* Get response to user input.
*
* Send user input to a workspace and receive a response.
*
* There is no rate limit for this operation.
*
* @param messageOptions the {@link MessageOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link MessageResponse}
*/
public ServiceCall<MessageResponse> message(MessageOptions messageOptions) {
Validator.notNull(messageOptions, "messageOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "message" };
String[] pathParameters = { messageOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (messageOptions.nodesVisitedDetails() != null) {
builder.query("nodes_visited_details", String.valueOf(messageOptions.nodesVisitedDetails()));
}
final JsonObject contentJson = new JsonObject();
if (messageOptions.input() != null) {
contentJson.add("input", GsonSingleton.getGson().toJsonTree(messageOptions.input()));
}
if (messageOptions.alternateIntents() != null) {
contentJson.addProperty("alternate_intents", messageOptions.alternateIntents());
}
if (messageOptions.context() != null) {
contentJson.add("context", GsonSingleton.getGson().toJsonTree(messageOptions.context()));
}
if (messageOptions.entities() != null) {
contentJson.add("entities", GsonSingleton.getGson().toJsonTree(messageOptions.entities()));
}
if (messageOptions.intents() != null) {
contentJson.add("intents", GsonSingleton.getGson().toJsonTree(messageOptions.intents()));
}
if (messageOptions.output() != null) {
contentJson.add("output", GsonSingleton.getGson().toJsonTree(messageOptions.output()));
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(MessageResponse.class));
}
/**
* Create workspace.
*
* Create a workspace based on component objects. You must provide workspace components defining the content of the
* new workspace.
*
* This operation is limited to 30 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createWorkspaceOptions the {@link CreateWorkspaceOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Workspace}
*/
public ServiceCall<Workspace> createWorkspace(CreateWorkspaceOptions createWorkspaceOptions) {
String[] pathSegments = { "v1/workspaces" };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments));
builder.query(VERSION, versionDate);
if (createWorkspaceOptions != null) {
final JsonObject contentJson = new JsonObject();
if (createWorkspaceOptions.name() != null) {
contentJson.addProperty("name", createWorkspaceOptions.name());
}
if (createWorkspaceOptions.description() != null) {
contentJson.addProperty("description", createWorkspaceOptions.description());
}
if (createWorkspaceOptions.language() != null) {
contentJson.addProperty("language", createWorkspaceOptions.language());
}
if (createWorkspaceOptions.intents() != null) {
contentJson.add("intents", GsonSingleton.getGson().toJsonTree(createWorkspaceOptions.intents()));
}
if (createWorkspaceOptions.entities() != null) {
contentJson.add("entities", GsonSingleton.getGson().toJsonTree(createWorkspaceOptions.entities()));
}
if (createWorkspaceOptions.dialogNodes() != null) {
contentJson.add("dialog_nodes", GsonSingleton.getGson().toJsonTree(createWorkspaceOptions.dialogNodes()));
}
if (createWorkspaceOptions.counterexamples() != null) {
contentJson.add("counterexamples", GsonSingleton.getGson().toJsonTree(createWorkspaceOptions
.counterexamples()));
}
if (createWorkspaceOptions.metadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(createWorkspaceOptions.metadata()));
}
if (createWorkspaceOptions.learningOptOut() != null) {
contentJson.addProperty("learning_opt_out", createWorkspaceOptions.learningOptOut());
}
if (createWorkspaceOptions.systemSettings() != null) {
contentJson.add("system_settings", GsonSingleton.getGson().toJsonTree(createWorkspaceOptions.systemSettings()));
}
builder.bodyJson(contentJson);
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Workspace.class));
}
/**
* Create workspace.
*
* Create a workspace based on component objects. You must provide workspace components defining the content of the
* new workspace.
*
* This operation is limited to 30 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @return a {@link ServiceCall} with a response type of {@link Workspace}
*/
public ServiceCall<Workspace> createWorkspace() {
return createWorkspace(null);
}
/**
* Delete workspace.
*
* Delete a workspace from the service instance.
*
* This operation is limited to 30 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteWorkspaceOptions the {@link DeleteWorkspaceOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteWorkspace(DeleteWorkspaceOptions deleteWorkspaceOptions) {
Validator.notNull(deleteWorkspaceOptions, "deleteWorkspaceOptions cannot be null");
String[] pathSegments = { "v1/workspaces" };
String[] pathParameters = { deleteWorkspaceOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get information about a workspace.
*
* Get information about a workspace, optionally including all workspace content.
*
* With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the
* limit is 20 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param getWorkspaceOptions the {@link GetWorkspaceOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link WorkspaceExport}
*/
public ServiceCall<WorkspaceExport> getWorkspace(GetWorkspaceOptions getWorkspaceOptions) {
Validator.notNull(getWorkspaceOptions, "getWorkspaceOptions cannot be null");
String[] pathSegments = { "v1/workspaces" };
String[] pathParameters = { getWorkspaceOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getWorkspaceOptions.export() != null) {
builder.query("export", String.valueOf(getWorkspaceOptions.export()));
}
if (getWorkspaceOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getWorkspaceOptions.includeAudit()));
}
if (getWorkspaceOptions.sort() != null) {
builder.query("sort", getWorkspaceOptions.sort());
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(WorkspaceExport.class));
}
/**
* List workspaces.
*
* List the workspaces associated with a Watson Assistant service instance.
*
* This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listWorkspacesOptions the {@link ListWorkspacesOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link WorkspaceCollection}
*/
public ServiceCall<WorkspaceCollection> listWorkspaces(ListWorkspacesOptions listWorkspacesOptions) {
String[] pathSegments = { "v1/workspaces" };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments));
builder.query(VERSION, versionDate);
if (listWorkspacesOptions != null) {
if (listWorkspacesOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listWorkspacesOptions.pageLimit()));
}
if (listWorkspacesOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listWorkspacesOptions.includeCount()));
}
if (listWorkspacesOptions.sort() != null) {
builder.query("sort", listWorkspacesOptions.sort());
}
if (listWorkspacesOptions.cursor() != null) {
builder.query("cursor", listWorkspacesOptions.cursor());
}
if (listWorkspacesOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listWorkspacesOptions.includeAudit()));
}
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(WorkspaceCollection.class));
}
/**
* List workspaces.
*
* List the workspaces associated with a Watson Assistant service instance.
*
* This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @return a {@link ServiceCall} with a response type of {@link WorkspaceCollection}
*/
public ServiceCall<WorkspaceCollection> listWorkspaces() {
return listWorkspaces(null);
}
/**
* Update workspace.
*
* Update an existing workspace with new or modified data. You must provide component objects defining the content of
* the updated workspace.
*
* This operation is limited to 30 request per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateWorkspaceOptions the {@link UpdateWorkspaceOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Workspace}
*/
public ServiceCall<Workspace> updateWorkspace(UpdateWorkspaceOptions updateWorkspaceOptions) {
Validator.notNull(updateWorkspaceOptions, "updateWorkspaceOptions cannot be null");
String[] pathSegments = { "v1/workspaces" };
String[] pathParameters = { updateWorkspaceOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (updateWorkspaceOptions.append() != null) {
builder.query("append", String.valueOf(updateWorkspaceOptions.append()));
}
final JsonObject contentJson = new JsonObject();
if (updateWorkspaceOptions.name() != null) {
contentJson.addProperty("name", updateWorkspaceOptions.name());
}
if (updateWorkspaceOptions.description() != null) {
contentJson.addProperty("description", updateWorkspaceOptions.description());
}
if (updateWorkspaceOptions.language() != null) {
contentJson.addProperty("language", updateWorkspaceOptions.language());
}
if (updateWorkspaceOptions.intents() != null) {
contentJson.add("intents", GsonSingleton.getGson().toJsonTree(updateWorkspaceOptions.intents()));
}
if (updateWorkspaceOptions.entities() != null) {
contentJson.add("entities", GsonSingleton.getGson().toJsonTree(updateWorkspaceOptions.entities()));
}
if (updateWorkspaceOptions.dialogNodes() != null) {
contentJson.add("dialog_nodes", GsonSingleton.getGson().toJsonTree(updateWorkspaceOptions.dialogNodes()));
}
if (updateWorkspaceOptions.counterexamples() != null) {
contentJson.add("counterexamples", GsonSingleton.getGson().toJsonTree(updateWorkspaceOptions.counterexamples()));
}
if (updateWorkspaceOptions.metadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(updateWorkspaceOptions.metadata()));
}
if (updateWorkspaceOptions.learningOptOut() != null) {
contentJson.addProperty("learning_opt_out", updateWorkspaceOptions.learningOptOut());
}
if (updateWorkspaceOptions.systemSettings() != null) {
contentJson.add("system_settings", GsonSingleton.getGson().toJsonTree(updateWorkspaceOptions.systemSettings()));
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Workspace.class));
}
/**
* Create intent.
*
* Create a new intent.
*
* This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createIntentOptions the {@link CreateIntentOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Intent}
*/
public ServiceCall<Intent> createIntent(CreateIntentOptions createIntentOptions) {
Validator.notNull(createIntentOptions, "createIntentOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents" };
String[] pathParameters = { createIntentOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("intent", createIntentOptions.intent());
if (createIntentOptions.description() != null) {
contentJson.addProperty("description", createIntentOptions.description());
}
if (createIntentOptions.examples() != null) {
contentJson.add("examples", GsonSingleton.getGson().toJsonTree(createIntentOptions.examples()));
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Intent.class));
}
/**
* Delete intent.
*
* Delete an intent from a workspace.
*
* This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteIntentOptions the {@link DeleteIntentOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteIntent(DeleteIntentOptions deleteIntentOptions) {
Validator.notNull(deleteIntentOptions, "deleteIntentOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents" };
String[] pathParameters = { deleteIntentOptions.workspaceId(), deleteIntentOptions.intent() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get intent.
*
* Get information about an intent, optionally including all intent content.
*
* With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the
* limit is 400 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param getIntentOptions the {@link GetIntentOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link IntentExport}
*/
public ServiceCall<IntentExport> getIntent(GetIntentOptions getIntentOptions) {
Validator.notNull(getIntentOptions, "getIntentOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents" };
String[] pathParameters = { getIntentOptions.workspaceId(), getIntentOptions.intent() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getIntentOptions.export() != null) {
builder.query("export", String.valueOf(getIntentOptions.export()));
}
if (getIntentOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getIntentOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(IntentExport.class));
}
/**
* List intents.
*
* List the intents for a workspace.
*
* With **export**=`false`, this operation is limited to 2000 requests per 30 minutes. With **export**=`true`, the
* limit is 400 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listIntentsOptions the {@link ListIntentsOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link IntentCollection}
*/
public ServiceCall<IntentCollection> listIntents(ListIntentsOptions listIntentsOptions) {
Validator.notNull(listIntentsOptions, "listIntentsOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents" };
String[] pathParameters = { listIntentsOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listIntentsOptions.export() != null) {
builder.query("export", String.valueOf(listIntentsOptions.export()));
}
if (listIntentsOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listIntentsOptions.pageLimit()));
}
if (listIntentsOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listIntentsOptions.includeCount()));
}
if (listIntentsOptions.sort() != null) {
builder.query("sort", listIntentsOptions.sort());
}
if (listIntentsOptions.cursor() != null) {
builder.query("cursor", listIntentsOptions.cursor());
}
if (listIntentsOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listIntentsOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(IntentCollection.class));
}
/**
* Update intent.
*
* Update an existing intent with new or modified data. You must provide component objects defining the content of the
* updated intent.
*
* This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateIntentOptions the {@link UpdateIntentOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Intent}
*/
public ServiceCall<Intent> updateIntent(UpdateIntentOptions updateIntentOptions) {
Validator.notNull(updateIntentOptions, "updateIntentOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents" };
String[] pathParameters = { updateIntentOptions.workspaceId(), updateIntentOptions.intent() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
if (updateIntentOptions.newIntent() != null) {
contentJson.addProperty("intent", updateIntentOptions.newIntent());
}
if (updateIntentOptions.newExamples() != null) {
contentJson.add("examples", GsonSingleton.getGson().toJsonTree(updateIntentOptions.newExamples()));
}
if (updateIntentOptions.newDescription() != null) {
contentJson.addProperty("description", updateIntentOptions.newDescription());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Intent.class));
}
/**
* Create user input example.
*
* Add a new user input example to an intent.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createExampleOptions the {@link CreateExampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Example}
*/
public ServiceCall<Example> createExample(CreateExampleOptions createExampleOptions) {
Validator.notNull(createExampleOptions, "createExampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents", "examples" };
String[] pathParameters = { createExampleOptions.workspaceId(), createExampleOptions.intent() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("text", createExampleOptions.text());
if (createExampleOptions.mentions() != null) {
contentJson.add("mentions", GsonSingleton.getGson().toJsonTree(createExampleOptions.mentions()));
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Example.class));
}
/**
* Delete user input example.
*
* Delete a user input example from an intent.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteExampleOptions the {@link DeleteExampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteExample(DeleteExampleOptions deleteExampleOptions) {
Validator.notNull(deleteExampleOptions, "deleteExampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents", "examples" };
String[] pathParameters = { deleteExampleOptions.workspaceId(), deleteExampleOptions.intent(), deleteExampleOptions
.text() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get user input example.
*
* Get information about a user input example.
*
* This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**.
*
* @param getExampleOptions the {@link GetExampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Example}
*/
public ServiceCall<Example> getExample(GetExampleOptions getExampleOptions) {
Validator.notNull(getExampleOptions, "getExampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents", "examples" };
String[] pathParameters = { getExampleOptions.workspaceId(), getExampleOptions.intent(), getExampleOptions.text() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getExampleOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getExampleOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Example.class));
}
/**
* List user input examples.
*
* List the user input examples for an intent, optionally including contextual entity mentions.
*
* This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listExamplesOptions the {@link ListExamplesOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link ExampleCollection}
*/
public ServiceCall<ExampleCollection> listExamples(ListExamplesOptions listExamplesOptions) {
Validator.notNull(listExamplesOptions, "listExamplesOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents", "examples" };
String[] pathParameters = { listExamplesOptions.workspaceId(), listExamplesOptions.intent() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listExamplesOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listExamplesOptions.pageLimit()));
}
if (listExamplesOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listExamplesOptions.includeCount()));
}
if (listExamplesOptions.sort() != null) {
builder.query("sort", listExamplesOptions.sort());
}
if (listExamplesOptions.cursor() != null) {
builder.query("cursor", listExamplesOptions.cursor());
}
if (listExamplesOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listExamplesOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(ExampleCollection.class));
}
/**
* Update user input example.
*
* Update the text of a user input example.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateExampleOptions the {@link UpdateExampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Example}
*/
public ServiceCall<Example> updateExample(UpdateExampleOptions updateExampleOptions) {
Validator.notNull(updateExampleOptions, "updateExampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "intents", "examples" };
String[] pathParameters = { updateExampleOptions.workspaceId(), updateExampleOptions.intent(), updateExampleOptions
.text() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
if (updateExampleOptions.newText() != null) {
contentJson.addProperty("text", updateExampleOptions.newText());
}
if (updateExampleOptions.newMentions() != null) {
contentJson.add("mentions", GsonSingleton.getGson().toJsonTree(updateExampleOptions.newMentions()));
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Example.class));
}
/**
* Create counterexample.
*
* Add a new counterexample to a workspace. Counterexamples are examples that have been marked as irrelevant input.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createCounterexampleOptions the {@link CreateCounterexampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Counterexample}
*/
public ServiceCall<Counterexample> createCounterexample(CreateCounterexampleOptions createCounterexampleOptions) {
Validator.notNull(createCounterexampleOptions, "createCounterexampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "counterexamples" };
String[] pathParameters = { createCounterexampleOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("text", createCounterexampleOptions.text());
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Counterexample.class));
}
/**
* Delete counterexample.
*
* Delete a counterexample from a workspace. Counterexamples are examples that have been marked as irrelevant input.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteCounterexampleOptions the {@link DeleteCounterexampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteCounterexample(DeleteCounterexampleOptions deleteCounterexampleOptions) {
Validator.notNull(deleteCounterexampleOptions, "deleteCounterexampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "counterexamples" };
String[] pathParameters = { deleteCounterexampleOptions.workspaceId(), deleteCounterexampleOptions.text() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get counterexample.
*
* Get information about a counterexample. Counterexamples are examples that have been marked as irrelevant input.
*
* This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**.
*
* @param getCounterexampleOptions the {@link GetCounterexampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Counterexample}
*/
public ServiceCall<Counterexample> getCounterexample(GetCounterexampleOptions getCounterexampleOptions) {
Validator.notNull(getCounterexampleOptions, "getCounterexampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "counterexamples" };
String[] pathParameters = { getCounterexampleOptions.workspaceId(), getCounterexampleOptions.text() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getCounterexampleOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getCounterexampleOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Counterexample.class));
}
/**
* List counterexamples.
*
* List the counterexamples for a workspace. Counterexamples are examples that have been marked as irrelevant input.
*
* This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listCounterexamplesOptions the {@link ListCounterexamplesOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link CounterexampleCollection}
*/
public ServiceCall<CounterexampleCollection> listCounterexamples(
ListCounterexamplesOptions listCounterexamplesOptions) {
Validator.notNull(listCounterexamplesOptions, "listCounterexamplesOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "counterexamples" };
String[] pathParameters = { listCounterexamplesOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listCounterexamplesOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listCounterexamplesOptions.pageLimit()));
}
if (listCounterexamplesOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listCounterexamplesOptions.includeCount()));
}
if (listCounterexamplesOptions.sort() != null) {
builder.query("sort", listCounterexamplesOptions.sort());
}
if (listCounterexamplesOptions.cursor() != null) {
builder.query("cursor", listCounterexamplesOptions.cursor());
}
if (listCounterexamplesOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listCounterexamplesOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(CounterexampleCollection.class));
}
/**
* Update counterexample.
*
* Update the text of a counterexample. Counterexamples are examples that have been marked as irrelevant input.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateCounterexampleOptions the {@link UpdateCounterexampleOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Counterexample}
*/
public ServiceCall<Counterexample> updateCounterexample(UpdateCounterexampleOptions updateCounterexampleOptions) {
Validator.notNull(updateCounterexampleOptions, "updateCounterexampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "counterexamples" };
String[] pathParameters = { updateCounterexampleOptions.workspaceId(), updateCounterexampleOptions.text() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
if (updateCounterexampleOptions.newText() != null) {
contentJson.addProperty("text", updateCounterexampleOptions.newText());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Counterexample.class));
}
/**
* Create entity.
*
* Create a new entity, or enable a system entity.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createEntityOptions the {@link CreateEntityOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Entity}
*/
public ServiceCall<Entity> createEntity(CreateEntityOptions createEntityOptions) {
Validator.notNull(createEntityOptions, "createEntityOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities" };
String[] pathParameters = { createEntityOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("entity", createEntityOptions.entity());
if (createEntityOptions.description() != null) {
contentJson.addProperty("description", createEntityOptions.description());
}
if (createEntityOptions.metadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(createEntityOptions.metadata()));
}
if (createEntityOptions.values() != null) {
contentJson.add("values", GsonSingleton.getGson().toJsonTree(createEntityOptions.values()));
}
if (createEntityOptions.fuzzyMatch() != null) {
contentJson.addProperty("fuzzy_match", createEntityOptions.fuzzyMatch());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Entity.class));
}
/**
* Delete entity.
*
* Delete an entity from a workspace, or disable a system entity.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteEntityOptions the {@link DeleteEntityOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteEntity(DeleteEntityOptions deleteEntityOptions) {
Validator.notNull(deleteEntityOptions, "deleteEntityOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities" };
String[] pathParameters = { deleteEntityOptions.workspaceId(), deleteEntityOptions.entity() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get entity.
*
* Get information about an entity, optionally including all entity content.
*
* With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the
* limit is 200 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param getEntityOptions the {@link GetEntityOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link EntityExport}
*/
public ServiceCall<EntityExport> getEntity(GetEntityOptions getEntityOptions) {
Validator.notNull(getEntityOptions, "getEntityOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities" };
String[] pathParameters = { getEntityOptions.workspaceId(), getEntityOptions.entity() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getEntityOptions.export() != null) {
builder.query("export", String.valueOf(getEntityOptions.export()));
}
if (getEntityOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getEntityOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(EntityExport.class));
}
/**
* List entities.
*
* List the entities for a workspace.
*
* With **export**=`false`, this operation is limited to 1000 requests per 30 minutes. With **export**=`true`, the
* limit is 200 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listEntitiesOptions the {@link ListEntitiesOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link EntityCollection}
*/
public ServiceCall<EntityCollection> listEntities(ListEntitiesOptions listEntitiesOptions) {
Validator.notNull(listEntitiesOptions, "listEntitiesOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities" };
String[] pathParameters = { listEntitiesOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listEntitiesOptions.export() != null) {
builder.query("export", String.valueOf(listEntitiesOptions.export()));
}
if (listEntitiesOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listEntitiesOptions.pageLimit()));
}
if (listEntitiesOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listEntitiesOptions.includeCount()));
}
if (listEntitiesOptions.sort() != null) {
builder.query("sort", listEntitiesOptions.sort());
}
if (listEntitiesOptions.cursor() != null) {
builder.query("cursor", listEntitiesOptions.cursor());
}
if (listEntitiesOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listEntitiesOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(EntityCollection.class));
}
/**
* Update entity.
*
* Update an existing entity with new or modified data. You must provide component objects defining the content of the
* updated entity.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateEntityOptions the {@link UpdateEntityOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Entity}
*/
public ServiceCall<Entity> updateEntity(UpdateEntityOptions updateEntityOptions) {
Validator.notNull(updateEntityOptions, "updateEntityOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities" };
String[] pathParameters = { updateEntityOptions.workspaceId(), updateEntityOptions.entity() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
if (updateEntityOptions.newFuzzyMatch() != null) {
contentJson.addProperty("fuzzy_match", updateEntityOptions.newFuzzyMatch());
}
if (updateEntityOptions.newEntity() != null) {
contentJson.addProperty("entity", updateEntityOptions.newEntity());
}
if (updateEntityOptions.newMetadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(updateEntityOptions.newMetadata()));
}
if (updateEntityOptions.newValues() != null) {
contentJson.add("values", GsonSingleton.getGson().toJsonTree(updateEntityOptions.newValues()));
}
if (updateEntityOptions.newDescription() != null) {
contentJson.addProperty("description", updateEntityOptions.newDescription());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Entity.class));
}
/**
* List entity mentions.
*
* List mentions for a contextual entity. An entity mention is an occurrence of a contextual entity in the context of
* an intent user input example.
*
* This operation is limited to 200 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listMentionsOptions the {@link ListMentionsOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link EntityMentionCollection}
*/
public ServiceCall<EntityMentionCollection> listMentions(ListMentionsOptions listMentionsOptions) {
Validator.notNull(listMentionsOptions, "listMentionsOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "mentions" };
String[] pathParameters = { listMentionsOptions.workspaceId(), listMentionsOptions.entity() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listMentionsOptions.export() != null) {
builder.query("export", String.valueOf(listMentionsOptions.export()));
}
if (listMentionsOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listMentionsOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(EntityMentionCollection.class));
}
/**
* Add entity value.
*
* Create a new value for an entity.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createValueOptions the {@link CreateValueOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Value}
*/
public ServiceCall<Value> createValue(CreateValueOptions createValueOptions) {
Validator.notNull(createValueOptions, "createValueOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values" };
String[] pathParameters = { createValueOptions.workspaceId(), createValueOptions.entity() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("value", createValueOptions.value());
if (createValueOptions.metadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(createValueOptions.metadata()));
}
if (createValueOptions.synonyms() != null) {
contentJson.add("synonyms", GsonSingleton.getGson().toJsonTree(createValueOptions.synonyms()));
}
if (createValueOptions.patterns() != null) {
contentJson.add("patterns", GsonSingleton.getGson().toJsonTree(createValueOptions.patterns()));
}
if (createValueOptions.valueType() != null) {
contentJson.addProperty("type", createValueOptions.valueType());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Value.class));
}
/**
* Delete entity value.
*
* Delete a value from an entity.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteValueOptions the {@link DeleteValueOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteValue(DeleteValueOptions deleteValueOptions) {
Validator.notNull(deleteValueOptions, "deleteValueOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values" };
String[] pathParameters = { deleteValueOptions.workspaceId(), deleteValueOptions.entity(), deleteValueOptions
.value() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get entity value.
*
* Get information about an entity value.
*
* This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**.
*
* @param getValueOptions the {@link GetValueOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link ValueExport}
*/
public ServiceCall<ValueExport> getValue(GetValueOptions getValueOptions) {
Validator.notNull(getValueOptions, "getValueOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values" };
String[] pathParameters = { getValueOptions.workspaceId(), getValueOptions.entity(), getValueOptions.value() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getValueOptions.export() != null) {
builder.query("export", String.valueOf(getValueOptions.export()));
}
if (getValueOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getValueOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(ValueExport.class));
}
/**
* List entity values.
*
* List the values for an entity.
*
* This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listValuesOptions the {@link ListValuesOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link ValueCollection}
*/
public ServiceCall<ValueCollection> listValues(ListValuesOptions listValuesOptions) {
Validator.notNull(listValuesOptions, "listValuesOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values" };
String[] pathParameters = { listValuesOptions.workspaceId(), listValuesOptions.entity() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listValuesOptions.export() != null) {
builder.query("export", String.valueOf(listValuesOptions.export()));
}
if (listValuesOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listValuesOptions.pageLimit()));
}
if (listValuesOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listValuesOptions.includeCount()));
}
if (listValuesOptions.sort() != null) {
builder.query("sort", listValuesOptions.sort());
}
if (listValuesOptions.cursor() != null) {
builder.query("cursor", listValuesOptions.cursor());
}
if (listValuesOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listValuesOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(ValueCollection.class));
}
/**
* Update entity value.
*
* Update an existing entity value with new or modified data. You must provide component objects defining the content
* of the updated entity value.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateValueOptions the {@link UpdateValueOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Value}
*/
public ServiceCall<Value> updateValue(UpdateValueOptions updateValueOptions) {
Validator.notNull(updateValueOptions, "updateValueOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values" };
String[] pathParameters = { updateValueOptions.workspaceId(), updateValueOptions.entity(), updateValueOptions
.value() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
if (updateValueOptions.newSynonyms() != null) {
contentJson.add("synonyms", GsonSingleton.getGson().toJsonTree(updateValueOptions.newSynonyms()));
}
if (updateValueOptions.valueType() != null) {
contentJson.addProperty("type", updateValueOptions.valueType());
}
if (updateValueOptions.newMetadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(updateValueOptions.newMetadata()));
}
if (updateValueOptions.newPatterns() != null) {
contentJson.add("patterns", GsonSingleton.getGson().toJsonTree(updateValueOptions.newPatterns()));
}
if (updateValueOptions.newValue() != null) {
contentJson.addProperty("value", updateValueOptions.newValue());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Value.class));
}
/**
* Add entity value synonym.
*
* Add a new synonym to an entity value.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createSynonymOptions the {@link CreateSynonymOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Synonym}
*/
public ServiceCall<Synonym> createSynonym(CreateSynonymOptions createSynonymOptions) {
Validator.notNull(createSynonymOptions, "createSynonymOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values", "synonyms" };
String[] pathParameters = { createSynonymOptions.workspaceId(), createSynonymOptions.entity(), createSynonymOptions
.value() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("synonym", createSynonymOptions.synonym());
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Synonym.class));
}
/**
* Delete entity value synonym.
*
* Delete a synonym from an entity value.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteSynonymOptions the {@link DeleteSynonymOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteSynonym(DeleteSynonymOptions deleteSynonymOptions) {
Validator.notNull(deleteSynonymOptions, "deleteSynonymOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values", "synonyms" };
String[] pathParameters = { deleteSynonymOptions.workspaceId(), deleteSynonymOptions.entity(), deleteSynonymOptions
.value(), deleteSynonymOptions.synonym() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get entity value synonym.
*
* Get information about a synonym of an entity value.
*
* This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**.
*
* @param getSynonymOptions the {@link GetSynonymOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Synonym}
*/
public ServiceCall<Synonym> getSynonym(GetSynonymOptions getSynonymOptions) {
Validator.notNull(getSynonymOptions, "getSynonymOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values", "synonyms" };
String[] pathParameters = { getSynonymOptions.workspaceId(), getSynonymOptions.entity(), getSynonymOptions.value(),
getSynonymOptions.synonym() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getSynonymOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getSynonymOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Synonym.class));
}
/**
* List entity value synonyms.
*
* List the synonyms for an entity value.
*
* This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listSynonymsOptions the {@link ListSynonymsOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link SynonymCollection}
*/
public ServiceCall<SynonymCollection> listSynonyms(ListSynonymsOptions listSynonymsOptions) {
Validator.notNull(listSynonymsOptions, "listSynonymsOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values", "synonyms" };
String[] pathParameters = { listSynonymsOptions.workspaceId(), listSynonymsOptions.entity(), listSynonymsOptions
.value() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listSynonymsOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listSynonymsOptions.pageLimit()));
}
if (listSynonymsOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listSynonymsOptions.includeCount()));
}
if (listSynonymsOptions.sort() != null) {
builder.query("sort", listSynonymsOptions.sort());
}
if (listSynonymsOptions.cursor() != null) {
builder.query("cursor", listSynonymsOptions.cursor());
}
if (listSynonymsOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listSynonymsOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(SynonymCollection.class));
}
/**
* Update entity value synonym.
*
* Update an existing entity value synonym with new text.
*
* This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateSynonymOptions the {@link UpdateSynonymOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link Synonym}
*/
public ServiceCall<Synonym> updateSynonym(UpdateSynonymOptions updateSynonymOptions) {
Validator.notNull(updateSynonymOptions, "updateSynonymOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values", "synonyms" };
String[] pathParameters = { updateSynonymOptions.workspaceId(), updateSynonymOptions.entity(), updateSynonymOptions
.value(), updateSynonymOptions.synonym() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
if (updateSynonymOptions.newSynonym() != null) {
contentJson.addProperty("synonym", updateSynonymOptions.newSynonym());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Synonym.class));
}
/**
* Create dialog node.
*
* Create a new dialog node.
*
* This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param createDialogNodeOptions the {@link CreateDialogNodeOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link DialogNode}
*/
public ServiceCall<DialogNode> createDialogNode(CreateDialogNodeOptions createDialogNodeOptions) {
Validator.notNull(createDialogNodeOptions, "createDialogNodeOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "dialog_nodes" };
String[] pathParameters = { createDialogNodeOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("dialog_node", createDialogNodeOptions.dialogNode());
if (createDialogNodeOptions.description() != null) {
contentJson.addProperty("description", createDialogNodeOptions.description());
}
if (createDialogNodeOptions.conditions() != null) {
contentJson.addProperty("conditions", createDialogNodeOptions.conditions());
}
if (createDialogNodeOptions.parent() != null) {
contentJson.addProperty("parent", createDialogNodeOptions.parent());
}
if (createDialogNodeOptions.previousSibling() != null) {
contentJson.addProperty("previous_sibling", createDialogNodeOptions.previousSibling());
}
if (createDialogNodeOptions.output() != null) {
contentJson.add("output", GsonSingleton.getGson().toJsonTree(createDialogNodeOptions.output()));
}
if (createDialogNodeOptions.context() != null) {
contentJson.add("context", GsonSingleton.getGson().toJsonTree(createDialogNodeOptions.context()));
}
if (createDialogNodeOptions.metadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(createDialogNodeOptions.metadata()));
}
if (createDialogNodeOptions.nextStep() != null) {
contentJson.add("next_step", GsonSingleton.getGson().toJsonTree(createDialogNodeOptions.nextStep()));
}
if (createDialogNodeOptions.actions() != null) {
contentJson.add("actions", GsonSingleton.getGson().toJsonTree(createDialogNodeOptions.actions()));
}
if (createDialogNodeOptions.title() != null) {
contentJson.addProperty("title", createDialogNodeOptions.title());
}
if (createDialogNodeOptions.nodeType() != null) {
contentJson.addProperty("type", createDialogNodeOptions.nodeType());
}
if (createDialogNodeOptions.eventName() != null) {
contentJson.addProperty("event_name", createDialogNodeOptions.eventName());
}
if (createDialogNodeOptions.variable() != null) {
contentJson.addProperty("variable", createDialogNodeOptions.variable());
}
if (createDialogNodeOptions.digressIn() != null) {
contentJson.addProperty("digress_in", createDialogNodeOptions.digressIn());
}
if (createDialogNodeOptions.digressOut() != null) {
contentJson.addProperty("digress_out", createDialogNodeOptions.digressOut());
}
if (createDialogNodeOptions.digressOutSlots() != null) {
contentJson.addProperty("digress_out_slots", createDialogNodeOptions.digressOutSlots());
}
if (createDialogNodeOptions.userLabel() != null) {
contentJson.addProperty("user_label", createDialogNodeOptions.userLabel());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(DialogNode.class));
}
/**
* Delete dialog node.
*
* Delete a dialog node from a workspace.
*
* This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param deleteDialogNodeOptions the {@link DeleteDialogNodeOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteDialogNode(DeleteDialogNodeOptions deleteDialogNodeOptions) {
Validator.notNull(deleteDialogNodeOptions, "deleteDialogNodeOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "dialog_nodes" };
String[] pathParameters = { deleteDialogNodeOptions.workspaceId(), deleteDialogNodeOptions.dialogNode() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
/**
* Get dialog node.
*
* Get information about a dialog node.
*
* This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**.
*
* @param getDialogNodeOptions the {@link GetDialogNodeOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link DialogNode}
*/
public ServiceCall<DialogNode> getDialogNode(GetDialogNodeOptions getDialogNodeOptions) {
Validator.notNull(getDialogNodeOptions, "getDialogNodeOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "dialog_nodes" };
String[] pathParameters = { getDialogNodeOptions.workspaceId(), getDialogNodeOptions.dialogNode() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (getDialogNodeOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getDialogNodeOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(DialogNode.class));
}
/**
* List dialog nodes.
*
* List the dialog nodes for a workspace.
*
* This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param listDialogNodesOptions the {@link ListDialogNodesOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link DialogNodeCollection}
*/
public ServiceCall<DialogNodeCollection> listDialogNodes(ListDialogNodesOptions listDialogNodesOptions) {
Validator.notNull(listDialogNodesOptions, "listDialogNodesOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "dialog_nodes" };
String[] pathParameters = { listDialogNodesOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listDialogNodesOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listDialogNodesOptions.pageLimit()));
}
if (listDialogNodesOptions.includeCount() != null) {
builder.query("include_count", String.valueOf(listDialogNodesOptions.includeCount()));
}
if (listDialogNodesOptions.sort() != null) {
builder.query("sort", listDialogNodesOptions.sort());
}
if (listDialogNodesOptions.cursor() != null) {
builder.query("cursor", listDialogNodesOptions.cursor());
}
if (listDialogNodesOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(listDialogNodesOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(DialogNodeCollection.class));
}
/**
* Update dialog node.
*
* Update an existing dialog node with new or modified data.
*
* This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**.
*
* @param updateDialogNodeOptions the {@link UpdateDialogNodeOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link DialogNode}
*/
public ServiceCall<DialogNode> updateDialogNode(UpdateDialogNodeOptions updateDialogNodeOptions) {
Validator.notNull(updateDialogNodeOptions, "updateDialogNodeOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "dialog_nodes" };
String[] pathParameters = { updateDialogNodeOptions.workspaceId(), updateDialogNodeOptions.dialogNode() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
final JsonObject contentJson = new JsonObject();
if (updateDialogNodeOptions.nodeType() != null) {
contentJson.addProperty("type", updateDialogNodeOptions.nodeType());
}
if (updateDialogNodeOptions.newActions() != null) {
contentJson.add("actions", GsonSingleton.getGson().toJsonTree(updateDialogNodeOptions.newActions()));
}
if (updateDialogNodeOptions.newConditions() != null) {
contentJson.addProperty("conditions", updateDialogNodeOptions.newConditions());
}
if (updateDialogNodeOptions.newContext() != null) {
contentJson.add("context", GsonSingleton.getGson().toJsonTree(updateDialogNodeOptions.newContext()));
}
if (updateDialogNodeOptions.newPreviousSibling() != null) {
contentJson.addProperty("previous_sibling", updateDialogNodeOptions.newPreviousSibling());
}
if (updateDialogNodeOptions.newVariable() != null) {
contentJson.addProperty("variable", updateDialogNodeOptions.newVariable());
}
if (updateDialogNodeOptions.newUserLabel() != null) {
contentJson.addProperty("user_label", updateDialogNodeOptions.newUserLabel());
}
if (updateDialogNodeOptions.newMetadata() != null) {
contentJson.add("metadata", GsonSingleton.getGson().toJsonTree(updateDialogNodeOptions.newMetadata()));
}
if (updateDialogNodeOptions.newTitle() != null) {
contentJson.addProperty("title", updateDialogNodeOptions.newTitle());
}
if (updateDialogNodeOptions.newDescription() != null) {
contentJson.addProperty("description", updateDialogNodeOptions.newDescription());
}
if (updateDialogNodeOptions.newDigressOut() != null) {
contentJson.addProperty("digress_out", updateDialogNodeOptions.newDigressOut());
}
if (updateDialogNodeOptions.newEventName() != null) {
contentJson.addProperty("event_name", updateDialogNodeOptions.newEventName());
}
if (updateDialogNodeOptions.newDigressOutSlots() != null) {
contentJson.addProperty("digress_out_slots", updateDialogNodeOptions.newDigressOutSlots());
}
if (updateDialogNodeOptions.newNextStep() != null) {
contentJson.add("next_step", GsonSingleton.getGson().toJsonTree(updateDialogNodeOptions.newNextStep()));
}
if (updateDialogNodeOptions.newDigressIn() != null) {
contentJson.addProperty("digress_in", updateDialogNodeOptions.newDigressIn());
}
if (updateDialogNodeOptions.newOutput() != null) {
contentJson.add("output", GsonSingleton.getGson().toJsonTree(updateDialogNodeOptions.newOutput()));
}
if (updateDialogNodeOptions.newParent() != null) {
contentJson.addProperty("parent", updateDialogNodeOptions.newParent());
}
if (updateDialogNodeOptions.newDialogNode() != null) {
contentJson.addProperty("dialog_node", updateDialogNodeOptions.newDialogNode());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(DialogNode.class));
}
/**
* List log events in all workspaces.
*
* List the events from the logs of all workspaces in the service instance.
*
* If **cursor** is not specified, this operation is limited to 40 requests per 30 minutes. If **cursor** is
* specified, the limit is 120 requests per minute. For more information, see **Rate limiting**.
*
* @param listAllLogsOptions the {@link ListAllLogsOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link LogCollection}
*/
public ServiceCall<LogCollection> listAllLogs(ListAllLogsOptions listAllLogsOptions) {
Validator.notNull(listAllLogsOptions, "listAllLogsOptions cannot be null");
String[] pathSegments = { "v1/logs" };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments));
builder.query(VERSION, versionDate);
builder.query("filter", listAllLogsOptions.filter());
if (listAllLogsOptions.sort() != null) {
builder.query("sort", listAllLogsOptions.sort());
}
if (listAllLogsOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listAllLogsOptions.pageLimit()));
}
if (listAllLogsOptions.cursor() != null) {
builder.query("cursor", listAllLogsOptions.cursor());
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(LogCollection.class));
}
/**
* List log events in a workspace.
*
* List the events from the log of a specific workspace.
*
* If **cursor** is not specified, this operation is limited to 40 requests per 30 minutes. If **cursor** is
* specified, the limit is 120 requests per minute. For more information, see **Rate limiting**.
*
* @param listLogsOptions the {@link ListLogsOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link LogCollection}
*/
public ServiceCall<LogCollection> listLogs(ListLogsOptions listLogsOptions) {
Validator.notNull(listLogsOptions, "listLogsOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "logs" };
String[] pathParameters = { listLogsOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query(VERSION, versionDate);
if (listLogsOptions.sort() != null) {
builder.query("sort", listLogsOptions.sort());
}
if (listLogsOptions.filter() != null) {
builder.query("filter", listLogsOptions.filter());
}
if (listLogsOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listLogsOptions.pageLimit()));
}
if (listLogsOptions.cursor() != null) {
builder.query("cursor", listLogsOptions.cursor());
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(LogCollection.class));
}
/**
* Delete labeled data.
*
* Deletes all data associated with a specified customer ID. The method has no effect if no data is associated with
* the customer ID.
*
* You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes data.
* For more information about personal data and customer IDs, see [Information
* security](https://console.bluemix.net/docs/services/conversation/information-security.html).
*
* @param deleteUserDataOptions the {@link DeleteUserDataOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteUserData(DeleteUserDataOptions deleteUserDataOptions) {
Validator.notNull(deleteUserDataOptions, "deleteUserDataOptions cannot be null");
String[] pathSegments = { "v1/user_data" };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments));
builder.query(VERSION, versionDate);
builder.query("customer_id", deleteUserDataOptions.customerId());
return createServiceCall(builder.build(), ResponseConverterUtils.getVoid());
}
}
|
<filename>src/main/groovy/io/swagger/model/Ga4ghWesParameterTypes.java
package io.swagger.model;
/**
* Gets or Sets ga4gh_wes_parameter_types
*/
public enum Ga4ghWesParameterTypes {
DIRECTORY("Directory"),
FILE("File"),
PARAMETER("Parameter");
private String value;
Ga4ghWesParameterTypes(String value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static Ga4ghWesParameterTypes fromValue(String text) {
for (Ga4ghWesParameterTypes b : Ga4ghWesParameterTypes.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
|
<filename>src/config/options/index.ts<gh_stars>1-10
import Confidence from 'confidence'
import auth from './auth'
import cronJob from './cronJob'
import mongo from './mongo'
import swagger from './swagger'
import logger from './logger'
import hapiRateLimit from './hapiRateLimit'
// For development criteria based
const criteria = { env: process.env.NODE_ENV }
const config: any = {
$meta: 'Our main server config',
auth,
cronJob,
mongo,
logger,
swagger,
hapiRateLimit
}
config.payload = { maxBytes: 100000000 }
// Create store for confidence
const store = new Confidence.Store(config)
// Export confidence store for fetch data
export default {
get: (key: string) => store.get(key, criteria)
} |
/**
* Loads available resources from program arguments.
*
* @author Kelvin Kellner
* @author Nish Tewari
*/
void load_available_resources(int argc, char *args[]) {
num_resources = argc - 1;
available_resources = (int *)malloc((num_resources) * sizeof(int));
for (int i = 0; i < num_resources; i++) {
available_resources[i] = atoi(args[i + 1]);
}
} |
Performance Analysis of Energy Conservation Techniques for Wireless Sensor Networks
In this paper, the problem of energy management in Wireless Sensor Network (WSN) for data collecting, computing and transfer is investigated. Battery powered sensors need efficient management due to limited energy resources, and energy conservation is a vital design issue that needs to be boosted in order to increase the lifespan of a network. Therefore, the important aspect of WSN design is resistant, secure and efficient communication relevant to radio devices with limited energy resources. Algorithms for dynamic transmission power control, clustering, activity control of devices and power save routing protocols are briefly summarized. The results of the performance evaluation of selected solutions through simulation and experiments conducted in testbed networks are presented and discussed. |
// GetStances returns the Stances field value
func (o *ItemWeapon) GetStances() []ItemWeaponStances {
if o == nil {
var ret []ItemWeaponStances
return ret
}
return o.Stances
} |
// Decode reads the next packet from the underlying reader.
// It blocks other calls to Decode until return.
func (d *Decoder) Decode() (ctx *proto.PacketContext, err error) {
d.mu.Lock()
defer d.mu.Unlock()
return d.readPacket()
} |
import { mock } from 'mockjs';
module.exports = () => mock({
id: '@id',
name: '@cname',
comment: '@cword(20, 100)',
'type|1': [1, 2],
}) |
from Simulation.Agents import Proposer, Acceptor
from Simulation.Network import Network
from Simulation.Message import MessageTypes
from Inputs import read_input
def simulate(proposers, acceptors, max_ticks, events):
network = Network(proposers, acceptors)
for i in range(max_ticks):
if len(events) == 0 and len(network.queue) == 0:
break
print(f'\n{str(i).zfill(3)}: ', end='')
event = events.get(i)
if event is not None:
events.pop(i)
message = event.message
if message.message_type == MessageTypes.PROPOSE:
network.deliver_messsage(message)
elif message.message_type == MessageTypes.FAIL:
[agent.recieve_fail() for agent in event.fails]
elif message.message_type == MessageTypes.RECOVER:
[agent.recieve_repair() for agent in event.repairs]
else:
message = network.extract_message()
if message is not None:
network.deliver_messsage(message)
print()
for proposer in proposers.values():
if proposer.consensus:
print(f'\n{proposer} has reached consensus (suggested: {proposer.suggested_value}, accepted: {proposer.value})', end='')
if __name__ == "__main__":
input_variables = read_input('Inputs/advanced.txt')
simulate(*input_variables)
|
// Copyright 2013 bee 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 generate
import (
"os"
"strings"
"github.com/freespace8/bee/cmd/commands"
"github.com/freespace8/bee/cmd/commands/version"
"github.com/freespace8/bee/config"
"github.com/freespace8/bee/generate"
"github.com/freespace8/bee/generate/swaggergen"
"github.com/freespace8/bee/logger"
"github.com/freespace8/bee/utils"
)
var CmdGenerate = &commands.Command{
UsageLine: "generate [command]",
Short: "Source code generator",
Long: `▶ {{"To scaffold out your entire application:"|bold}}
$ bee generate scaffold [scaffoldname] [-fields="title:string,body:text"] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]
▶ {{"To generate a Model based on fields:"|bold}}
$ bee generate model [modelname] [-fields="name:type"]
▶ {{"To generate a controller:"|bold}}
$ bee generate controller [controllerfile]
▶ {{"To generate a CRUD view:"|bold}}
$ bee generate view [viewpath]
▶ {{"To generate a migration file for making database schema updates:"|bold}}
$ bee generate migration [migrationfile] [-fields="name:type"]
▶ {{"To generate swagger doc file:"|bold}}
$ bee generate docs
▶ {{"To generate a test case:"|bold}}
$ bee generate test [routerfile]
▶ {{"To generate appcode based on an existing database:"|bold}}
$ bee generate appcode [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-level=3]
`,
PreRun: func(cmd *commands.Command, args []string) { version.ShowShortVersionBanner() },
Run: GenerateCode,
}
func init() {
CmdGenerate.Flag.Var(&generate.Tables, "tables", "List of table names separated by a comma.")
CmdGenerate.Flag.Var(&generate.SQLDriver, "driver", "Database SQLDriver. Either mysql, postgres or sqlite.")
CmdGenerate.Flag.Var(&generate.SQLConn, "conn", "Connection string used by the SQLDriver to connect to a database instance.")
CmdGenerate.Flag.Var(&generate.Level, "level", "Either 1, 2 or 3. i.e. 1=models; 2=models and controllers; 3=models, controllers and routers.")
CmdGenerate.Flag.Var(&generate.Fields, "fields", "List of table Fields.")
CmdGenerate.Flag.Var(&generate.DDL, "ddl", "Generate DDL Migration")
commands.AvailableCommands = append(commands.AvailableCommands, CmdGenerate)
}
func GenerateCode(cmd *commands.Command, args []string) int {
currpath, _ := os.Getwd()
if len(args) < 1 {
beeLogger.Log.Fatal("Command is missing")
}
gps := utils.GetGOPATHs()
if len(gps) == 0 {
beeLogger.Log.Fatal("GOPATH environment variable is not set or empty")
}
gopath := gps[0]
beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath)
gcmd := args[0]
switch gcmd {
case "scaffold":
scaffold(cmd, args, currpath)
case "docs":
swaggergen.GenerateDocs(currpath)
case "appcode":
appCode(cmd, args, currpath)
case "migration":
migration(cmd, args, currpath)
case "controller":
controller(args, currpath)
case "model":
model(cmd, args, currpath)
case "view":
view(args, currpath)
default:
beeLogger.Log.Fatal("Command is missing")
}
beeLogger.Log.Successf("%s successfully generated!", strings.Title(gcmd))
return 0
}
func scaffold(cmd *commands.Command, args []string, currpath string) {
if len(args) < 2 {
beeLogger.Log.Fatal("Wrong number of arguments. Run: bee help generate")
}
cmd.Flag.Parse(args[2:])
if generate.SQLDriver == "" {
generate.SQLDriver = utils.DocValue(config.Conf.Database.Driver)
if generate.SQLDriver == "" {
generate.SQLDriver = "mysql"
}
}
if generate.SQLConn == "" {
generate.SQLConn = utils.DocValue(config.Conf.Database.Conn)
if generate.SQLConn == "" {
generate.SQLConn = "root:@tcp(127.0.0.1:3306)/test"
}
}
if generate.Fields == "" {
beeLogger.Log.Hint("Fields option should not be empty, i.e. -Fields=\"title:string,body:text\"")
beeLogger.Log.Fatal("Wrong number of arguments. Run: bee help generate")
}
sname := args[1]
generate.GenerateScaffold(sname, generate.Fields.String(), currpath, generate.SQLDriver.String(), generate.SQLConn.String())
}
func appCode(cmd *commands.Command, args []string, currpath string) {
cmd.Flag.Parse(args[1:])
if generate.SQLDriver == "" {
generate.SQLDriver = utils.DocValue(config.Conf.Database.Driver)
if generate.SQLDriver == "" {
generate.SQLDriver = "mysql"
}
}
if generate.SQLConn == "" {
generate.SQLConn = utils.DocValue(config.Conf.Database.Conn)
if generate.SQLConn == "" {
if generate.SQLDriver == "mysql" {
generate.SQLConn = "root:@tcp(127.0.0.1:3306)/test"
} else if generate.SQLDriver == "postgres" {
generate.SQLConn = "postgres://postgres:[email protected]:5432/postgres"
}
}
}
if generate.Level == "" {
generate.Level = "3"
}
beeLogger.Log.Infof("Using '%s' as 'SQLDriver'", generate.SQLDriver)
beeLogger.Log.Infof("Using '%s' as 'SQLConn'", generate.SQLConn)
beeLogger.Log.Infof("Using '%s' as 'Tables'", generate.Tables)
beeLogger.Log.Infof("Using '%s' as 'Level'", generate.Level)
generate.GenerateAppcode(generate.SQLDriver.String(), generate.SQLConn.String(), generate.Level.String(), generate.Tables.String(), currpath)
}
func migration(cmd *commands.Command, args []string, currpath string) {
if len(args) < 2 {
beeLogger.Log.Fatal("Wrong number of arguments. Run: bee help generate")
}
cmd.Flag.Parse(args[2:])
mname := args[1]
beeLogger.Log.Infof("Using '%s' as migration name", mname)
upsql := ""
downsql := ""
if generate.Fields != "" {
dbMigrator := generate.NewDBDriver()
upsql = dbMigrator.GenerateCreateUp(mname)
downsql = dbMigrator.GenerateCreateDown(mname)
}
generate.GenerateMigration(mname, upsql, downsql, currpath)
}
func controller(args []string, currpath string) {
if len(args) == 2 {
cname := args[1]
generate.GenerateController(cname, currpath)
} else {
beeLogger.Log.Fatal("Wrong number of arguments. Run: bee help generate")
}
}
func model(cmd *commands.Command, args []string, currpath string) {
if len(args) < 2 {
beeLogger.Log.Fatal("Wrong number of arguments. Run: bee help generate")
}
cmd.Flag.Parse(args[2:])
if generate.Fields == "" {
beeLogger.Log.Hint("Fields option should not be empty, i.e. -Fields=\"title:string,body:text\"")
beeLogger.Log.Fatal("Wrong number of arguments. Run: bee help generate")
}
sname := args[1]
generate.GenerateModel(sname, generate.Fields.String(), currpath)
}
func view(args []string, currpath string) {
if len(args) == 2 {
cname := args[1]
generate.GenerateView(cname, currpath)
} else {
beeLogger.Log.Fatal("Wrong number of arguments. Run: bee help generate")
}
}
|
import { QUIT_ERROR } from "../types";
// here it gores the actions
// here it goes the function events
|
//#include<bhaai.h>
#include<bits/stdc++.h>
using namespace std;
#define to int64_t
#define mo 1000000007
#define fr(a,e) for(int64_t i=a;i<=e;i++)
#define yah_faster_baby ios_base::sync_with_stdio(0);cin.tie(0);
to n,ans,dp[103][2],x;
//float dp[103][103];
//vector <int> v[200005];
//char s[100005];
int main()
{ yah_faster_baby
cin>>n;
to sum=0;
for(int i=1;i<=n;i++)
sum+=pow(2,i);
cout<<sum<<endl;
return 0;
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef COLUMNSORTPROXYMODEL_H
#define COLUMNSORTPROXYMODEL_H
#if !defined(Q_MOC_RUN)
#include <QAbstractProxyModel>
#include <QVector>
#endif
class ColumnGroupProxyModel;
/*!
\brief Proxy model used to sort on multiple columns
It's using a stable sort to sort on multiple columns.
Every time a value is changed (on one of the sorted columns), it will resort everything.
THis model does not work with tree models!
*/
class ColumnSortProxyModel
: public QAbstractProxyModel
{
Q_OBJECT
public:
ColumnSortProxyModel(QObject* parent = nullptr);
~ColumnSortProxyModel();
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
int rowCount(const QModelIndex& index = QModelIndex()) const override;
int columnCount(const QModelIndex& index = QModelIndex()) const override;
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex& index) const override;
QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override;
QModelIndex mapToSource(const QModelIndex& proxyIndex) const override;
void setSourceModel(QAbstractItemModel* sourceModel) override;
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override;
void AddColumn(int column, Qt::SortOrder order = Qt::AscendingOrder);
void RemoveColumn(int column);
void SetColumns(const QVector<int>& columns);
void ClearColumns();
bool IsColumnSorted(int col) const;
Qt::SortOrder SortOrder(int col) const;
signals:
void SortChanged();
private:
friend class ColumnGroupProxyModel;
void AddColumnWithoutSorting(int column, Qt::SortOrder order = Qt::AscendingOrder);
void RemoveColumnWithoutSorting(int column);
private slots:
void SortModel();
void SourceDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight);
private:
struct Column
{
int column;
Qt::SortOrder sortOrder;
};
int ColumnContains(int col) const;
QVector<Column> m_columns;
QVector<int> m_mappingToSource;
};
#endif //COLUMNSORTPROXYMODEL_H
|
<filename>src/a_star.go
/*
* Copyright (c) 2021 <NAME>.
* All rights reserved.
* See LICENSE.txt in project root for license information.
* Authors:
* <NAME> <<EMAIL>>
*/
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
type MazeAStarVisit struct {
gScore int
fScore int
previous *MazeAStarVisit
cell *MazeCell
}
/* Taxi cab distance because only cardinal directions for now :-) */
func (maze *MazeGrid) heuristic(node *MazeCell, target *MazeCell) int {
d := math.Abs(float64(node.Y-target.Y)) + math.Abs(float64(node.X-target.X))
return int(d)
}
func do_path(ch *Character, arguments string) {
if ch.Room == nil || !ch.Room.Virtual || ch.Room.Cell == nil {
ch.Send("You cannot pathfind from here.\r\n")
return
}
args := strings.Split(arguments, " ")
if len(args) < 2 {
ch.Send(fmt.Sprintf("Usage: path <x> <y>\r\nYour current position is (%d, %d).\r\n", ch.Room.Cell.X, ch.Room.Cell.Y))
return
}
x, err := strconv.Atoi(args[0])
if err != nil {
ch.Send(fmt.Sprintf("Usage: path <x> <y>\r\nYour current position is (%d, %d).\r\n", ch.Room.Cell.X, ch.Room.Cell.Y))
return
}
y, err := strconv.Atoi(args[1])
if err != nil {
ch.Send(fmt.Sprintf("Usage: path <x> <y>\r\nYour current position is (%d, %d).\r\n", ch.Room.Cell.X, ch.Room.Cell.Y))
return
}
if !ch.Room.Cell.Grid.isValidPosition(x, y) {
ch.Send(fmt.Sprintf("Target (%d, %d) out of bounds.\r\n", x, y))
return
}
target := ch.Room.Cell.Grid.Grid[x][y]
if target == nil || target.Wall {
ch.Send(fmt.Sprintf("Bad cell or obstacle at (%d, %d).\r\n", target.X, target.Y))
return
}
var output strings.Builder
pathNodes := ch.Room.Cell.Grid.findPathAStar(ch.Room.Cell, target)
output.WriteString(fmt.Sprintf("{YPath from (%d, %d) to (%d, %d) in %d moves.{x\r\n", ch.Room.Cell.X, ch.Room.Cell.Y, target.X, target.Y, int(math.Max(0, float64(len(pathNodes)-1)))))
for r := len(pathNodes) - 1; r >= 0; r-- {
output.WriteString(fmt.Sprintf("{G(%d, %d){x\r\n", pathNodes[r].cell.X, pathNodes[r].cell.Y))
}
ch.Send(output.String())
}
func (maze *MazeGrid) findPathAStar(start *MazeCell, end *MazeCell) []*MazeAStarVisit {
visited := NewLinkedList()
unvisited := make(map[*MazeCell]*MazeAStarVisit)
for y := 0; y < maze.Height; y++ {
for x := 0; x < maze.Width; x++ {
unvisited[maze.Grid[x][y]] = &MazeAStarVisit{gScore: 1000000, fScore: 1000000, previous: nil, cell: maze.Grid[x][y]}
}
}
var hScore int = maze.heuristic(start, end)
unvisited[start] = &MazeAStarVisit{
gScore: 0,
fScore: hScore,
previous: nil,
cell: start,
}
visits := make([]*MazeAStarVisit, 0)
if start == end {
return visits
}
for {
if len(unvisited) == 0 {
return visits
} else {
var currentNode *MazeAStarVisit = nil
for _, visit := range unvisited {
if currentNode == nil || visit.fScore < currentNode.fScore {
currentNode = visit
}
}
if currentNode.cell == end {
visited.Insert(unvisited[currentNode.cell])
visits = append(visits, currentNode)
current := currentNode.previous
for {
if current == nil {
break
}
visits = append(visits, current)
if current.cell == start {
return visits
}
current = current.previous
}
} else {
neighbours := currentNode.cell.getAdjacentCells(false, 1, false)
for iter := neighbours.Head; iter != nil; iter = iter.Next {
neighbour := iter.Value.(*MazeCell)
if !visited.Contains(neighbour) {
var gScore int = unvisited[currentNode.cell].gScore + 1
_, ok := unvisited[neighbour]
if ok {
if gScore < unvisited[neighbour].gScore {
unvisited[neighbour].gScore = gScore + 1 /* movement cost */
unvisited[neighbour].fScore = gScore + maze.heuristic(currentNode.cell, end)
unvisited[neighbour].previous = currentNode
}
}
}
}
visited.Insert(unvisited[currentNode.cell])
delete(unvisited, currentNode.cell)
}
}
}
}
|
<filename>testsuite/test_0146/data/test.cpp
#include <gtest/gtest.h>
#include <pxr/base/tf/token.h>
#include <pxr/base/vt/value.h>
#include <pxr/usd/sdf/assetPath.h>
#include "render_delegate/utils.h"
#include <cinttypes>
#include <vector>
PXR_NAMESPACE_USING_DIRECTIVE
std::vector<AtString> _GetStringArray(const AtNode* node, const char* paramName)
{
auto* arr = AiNodeGetArray(node, paramName);
if (arr == nullptr) {
return {};
}
const auto numElements = AiArrayGetNumElements(arr);
if (numElements == 0) {
return {};
}
auto* str = static_cast<AtString*>(AiArrayMap(arr));
std::vector<AtString> ret(str, str + numElements);
AiArrayUnmap(arr);
return ret;
}
TEST(HdArnoldSetConstantPrimvar, SingleString)
{
auto* node = AiNode("polymesh");
HdArnoldSetConstantPrimvar(node, TfToken{"primvar1"}, HdPrimvarRoleTokens->none, VtValue{std::string{"hello"}});
EXPECT_EQ(AiNodeGetStr(node, "primvar1"), AtString{"hello"});
HdArnoldSetConstantPrimvar(node, TfToken{"primvar2"}, HdPrimvarRoleTokens->none, VtValue{TfToken{"world"}});
EXPECT_EQ(AiNodeGetStr(node, "primvar2"), AtString{"world"});
HdArnoldSetConstantPrimvar(node, TfToken{"primvar3"}, HdPrimvarRoleTokens->none, VtValue{SdfAssetPath{"mypath"}});
EXPECT_EQ(AiNodeGetStr(node, "primvar3"), AtString{"mypath"});
}
#define TEST_SET_PRIMVAR_ARRAY_FUNCTIONS(FUNCNAME) \
TEST(FUNCNAME, StringsArray) \
{ \
auto* node = AiNode("polymesh"); \
FUNCNAME( \
node, TfToken{"primvar1"}, HdPrimvarRoleTokens->none, \
VtValue{VtArray<std::string>{std::string{"hello"}, std::string{"world"}}}); \
EXPECT_EQ(_GetStringArray(node, "primvar1"), std::vector<AtString>({AtString{"hello"}, AtString{"world"}})); \
FUNCNAME( \
node, TfToken{"primvar2"}, HdPrimvarRoleTokens->none, \
VtValue{VtArray<TfToken>{TfToken{"hello"}, TfToken{"world"}}}); \
EXPECT_EQ(_GetStringArray(node, "primvar2"), std::vector<AtString>({AtString{"hello"}, AtString{"world"}})); \
FUNCNAME( \
node, TfToken{"primvar3"}, HdPrimvarRoleTokens->none, \
VtValue{VtArray<SdfAssetPath>{SdfAssetPath{"hello"}, SdfAssetPath{"world"}}}); \
EXPECT_EQ(_GetStringArray(node, "primvar3"), std::vector<AtString>({AtString{"hello"}, AtString{"world"}})); \
}
TEST_SET_PRIMVAR_ARRAY_FUNCTIONS(HdArnoldSetConstantPrimvar)
TEST_SET_PRIMVAR_ARRAY_FUNCTIONS(HdArnoldSetUniformPrimvar)
TEST_SET_PRIMVAR_ARRAY_FUNCTIONS(HdArnoldSetVertexPrimvar)
TEST(HdArnoldSetInstancePrimvar, StringArray)
{
auto* node = AiNode("polymesh");
HdArnoldSetInstancePrimvar(
node, TfToken{"primvar1"}, HdPrimvarRoleTokens->none, VtIntArray{0, 1, 0},
VtValue{VtArray<std::string>{std::string{"hello"}, std::string{"world"}}});
EXPECT_EQ(
_GetStringArray(node, "instance_primvar1"),
std::vector<AtString>({AtString{"hello"}, AtString{"world"}, AtString{"hello"}}));
HdArnoldSetInstancePrimvar(
node, TfToken{"primvar2"}, HdPrimvarRoleTokens->none, VtIntArray{0, 1, 0},
VtValue{VtArray<TfToken>{TfToken{"hello"}, TfToken{"world"}}});
EXPECT_EQ(
_GetStringArray(node, "instance_primvar2"),
std::vector<AtString>({AtString{"hello"}, AtString{"world"}, AtString{"hello"}}));
HdArnoldSetInstancePrimvar(
node, TfToken{"primvar3"}, HdPrimvarRoleTokens->none, VtIntArray{0, 1, 0},
VtValue{VtArray<SdfAssetPath>{SdfAssetPath{"hello"}, SdfAssetPath{"world"}}});
EXPECT_EQ(
_GetStringArray(node, "instance_primvar3"),
std::vector<AtString>({AtString{"hello"}, AtString{"world"}, AtString{"hello"}}));
}
TEST(HdArnoldSetInstancePrimvar, InvalidIndex)
{
auto* node = AiNode("polymesh");
HdArnoldSetInstancePrimvar(
node, TfToken{"primvar1"}, HdPrimvarRoleTokens->none, VtIntArray{0, 42, 0},
VtValue{VtArray<std::string>{std::string{"hello"}, std::string{"world"}}});
EXPECT_EQ(
_GetStringArray(node, "instance_primvar1"),
std::vector<AtString>({AtString{"hello"}, AtString{}, AtString{"hello"}}));
HdArnoldSetInstancePrimvar(
node, TfToken{"primvar2"}, HdPrimvarRoleTokens->none, VtIntArray{0, 42, -1337},
VtValue{VtArray<std::string>{std::string{"hello"}, std::string{"world"}}});
EXPECT_EQ(
_GetStringArray(node, "instance_primvar2"),
std::vector<AtString>({AtString{"hello"}, AtString{}, AtString{}}));
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
AiBegin();
AiMsgSetConsoleFlags(AI_LOG_NONE);
auto result = RUN_ALL_TESTS();
AiEnd();
return result;
}
|
/**
* Shorthand for the following <p>
* <code>it.intervalInsert(new Node(new Interval(low, high)));</code>
*
* @param it an interval treap
* @param low the low value of the interval to insert in to the treap
* @param high the high value of the interval to insert in to the treap
* @return the node
*/
Node insertInterval(IntervalTreap it, int low, int high) {
Node node = new Node(new Interval(low, high));
it.intervalInsert(node);
return node;
} |
/**
* Messages de l'application
* @return
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
List<String> filesToLoad=new LinkedList<String>();
ClassPathResource res = new ClassPathResource("i18n/messages.properties");
if(res.exists()){
filesToLoad.add("i18n/messages");
}
filesToLoad.add("i18n/messages-default");
ClassPathResource resv = new ClassPathResource("i18n/vaadin-messages.properties");
if(resv.exists()){
filesToLoad.add("i18n/vaadin-messages");
}
filesToLoad.add("i18n/vaadin-messages-default");
resourceBundleMessageSource.setBasenames(filesToLoad.toArray(new String[filesToLoad.size()]));
return resourceBundleMessageSource;
} |
// Error can be either of the following types:
//
// - ApiException
/*
Retrieves the list of service links for the authorized customer.
See {@link ServiceType} for information on the various linking types supported.
@param selector describing which links to retrieve
@throws ApiException
*/
func (service *CustomerServiceInterface) GetServiceLinks(request *GetServiceLinks) (*GetServiceLinksResponse, error) {
response := new(GetServiceLinksResponse)
err := service.client.Call("", request, response)
if err != nil {
return nil, err
}
return response, nil
} |
"""
Functions for geometrical image transformation and warping.
"""
import sys
import time
import numbers
from functools import wraps
from collections import namedtuple
import numpy as np
import scipy.ndimage
from scipy.signal import convolve2d
from sunpy import log
from sunpy.util.exceptions import warn_user
__all__ = ['add_rotation_function', 'affine_transform']
def affine_transform(image, rmatrix, order=3, scale=1.0, image_center=None,
recenter=False, missing=np.nan, *, method='scipy', clip=True):
"""
Rotates, shifts and scales an image.
This function supports NaN values in the input image and supports using NaN for
pixels in the output image that are beyond the extent of the input image.
Handling NaN values in the input image requires additional computation time.
Parameters
----------
image : `numpy.ndarray`
2D image to be rotated.
rmatrix : `numpy.ndarray` that is 2x2
Linear transformation rotation matrix.
order : `int` 0-5, optional
Interpolation order to be used, defaults to 3. The precise meaning depends
on the rotation method specified by ``method``.
scale : `float`
A scale factor for the image with the default being no scaling.
image_center : tuple, optional
The point in the image to rotate around (axis of rotation).
Defaults to the center of the array.
recenter : `bool` or array-like, optional
Move the axis of rotation to the center of the array or recenter coords.
Defaults to `False`.
missing : `float`, optional
The value to use for pixels in the output image that are beyond the extent
of the input image.
Defaults to `numpy.nan`.
method : {{{rotation_function_names}}}, optional
Rotation function to use.
Defaults to ``'scipy'``.
clip : `bool`, optional
If `True`, clips the pixel values of the output image to the range of the
input image (including the value of ``missing``, if used).
Defaults to `True`.
Returns
-------
`numpy.ndarray`:
New rotated, scaled and translated image.
Notes
-----
For each NaN pixel in the input image, one or more pixels in the output image
will be set to NaN, with the size of the pixel region affected depending on the
interpolation order. All currently implemented rotation methods require a
convolution step to handle image NaNs. This convolution normally uses
:func:`scipy.signal.convolve2d`, but if `OpenCV <https://opencv.org>`__ is
installed, the faster |cv2_filter2D|_ is used instead.
See :func:`~sunpy.image.transform.add_rotation_function` for how to add a
different rotation function.
"""
rmatrix = rmatrix / scale
array_center = (np.array(image.shape)[::-1] - 1) / 2.0
# Make sure the image center is an array and is where it's supposed to be
if image_center is not None:
image_center = np.asanyarray(image_center)
else:
image_center = array_center
# Determine center of rotation based on use (or not) of the recenter keyword
if recenter:
rot_center = array_center
else:
rot_center = image_center
displacement = np.dot(rmatrix, rot_center)
shift = image_center - displacement
method = _get_transform_method(method)
# Transform the image using the appropriate function
rotated_image = _rotation_registry[method].function(image, rmatrix, shift, order, missing, clip)
return rotated_image
def _get_transform_method(method):
# This is re-used in affine_transform and GenericMap.rotate
if method not in _rotation_registry:
raise ValueError(f'Method {method} not in supported methods: '
f'{_rotation_registry.keys()}')
return method
def add_rotation_function(name, *, allowed_orders,
handles_clipping, handles_image_nans, handles_nan_missing):
"""
Decorator to add a rotation function to the registry of selectable
implementations.
Each registered rotation function becomes a selectable option for
:func:`sunpy.image.transform.affine_transform` and
:meth:`sunpy.map.GenericMap.rotate`. Those two routines are required to handle
clipping the output image, NaNs in the input image, and NaN as the value to use
for pixels in the output image that are beyond the extent of the input image.
If the supplied rotation function cannot provide one or more of these capabilities,
the decorator is able to provide them instead.
The decorator requires the parameters listed under ``Parameters``. The decorated
rotation function must accept the parameters listed under ``Other Parameters``
in that order and return the rotated image.
Parameters
----------
name : `str`
The name that will be used to select the rotation function
allowed_orders : `set`
The allowed values for the ``order`` parameter.
handles_clipping : `bool`
Specifies whether the rotation function will internally perform clipping.
If ``False``, the rotation function will always receive ``False`` for the
``clip`` input parameter.
handles_image_nans : `bool`
Specifies whether the rotation function will internally handle NaNs in the
input image. If ``False``, the rotation function is guaranteed to be
provided an image without any NaNs.
handles_nan_missing : `bool`
Specifies whether the rotation function will internally handle NaN as the
``missing`` value. If ``False``, the rotation function will never receive
NaN, but instead receive a value in the input range of the image.
Other Parameters
----------------
image : `numpy.ndarray`
The image, which could be integers or floats
matrix : `numpy.ndarray` that is 2x2
The linear transformation matrix (e.g., rotation+scale+skew)
shift : 2-element `numpy.ndarray`
The translational shift to apply to the image in each axis
order : `int`
The numerical parameter that controls the degree of interpolation
missing : `float`
The value to use for outside the bounds of the original image
clip : `bool`
Whether to clip the output image to the range of the input image
Notes
-----
The docstring of the rotation function should be a bulleted list of notes
specific to the rotation function. It will be appended to ``Notes`` section of
the docstring for :func:`~sunpy.image.transform.affine_transform`.
The rotation function is supplied the input image directly, so the function
should not modify the image in place.
Setting any of the ``handles_*`` parameters to ``False`` means that computation
will be performed to modify the image returned by the rotation function before
it is returned to :func:`~sunpy.image.transform.affine_transform`.
If the decorator is handling image NaNs on behalf of the rotation function
(i.e., ``handles_image_nans=False``), pixels in the output image will be set to
NaN if they are within a certain neighborhood size that depends on the ``order``
parameter. This step requires an additional image convolution, which might be
avoidable if the rotation function were able to internally handle image NaNs.
This convolution normally uses :func:`scipy.signal.convolve2d`, but if
`OpenCV <https://opencv.org>`__ is installed, the faster |cv2_filter2D|_ is
used instead.
"""
def decorator(rotation_function):
@wraps(rotation_function)
def wrapper(image, matrix, shift, order, missing, clip):
if order not in allowed_orders:
raise ValueError(f"{order} is one of the allowed orders for method '{name}': "
f"{set(allowed_orders)}")
clip_to_use = clip if handles_clipping else False
# Check if missing is NaN and needs to be externally handled
needs_missing_handling = not handles_nan_missing and np.isnan(missing)
# Check if there are any NaNs in the image that need to be externally handled
if not handles_image_nans:
isnan = np.isnan(image)
needs_nan_handling = np.any(isnan)
else:
needs_nan_handling = False
# If either is needed, change the NaNs to the median of the input image
if needs_missing_handling or needs_nan_handling:
substitute = np.nanmedian(image)
missing_to_use = substitute if needs_missing_handling else missing
image_to_use = np.nan_to_num(image, nan=substitute) if needs_nan_handling else image
t = time.perf_counter()
rotated_image = rotation_function(image_to_use, matrix, shift, order,
missing_to_use, clip_to_use)
log.debug(f"{name} rotating image: {time.perf_counter() - t:.3f} s")
# If needed, restore the NaNs
if needs_nan_handling:
# Use a convolution to find all pixels that are appreciably affected by NaNs
# The kernel size depends on the interpolation order, but are empirically defined
# because a given pixel can affect every other pixel under spline interpolation
sizes = [1, 1, 5, 5, 7, 7]
t = time.perf_counter()
try:
# If OpenCV is installed, its convolution function is much faster
import cv2
expanded_nans = cv2.filter2D(isnan.astype(float), -1,
np.ones((sizes[order], sizes[order])),
borderType=cv2.BORDER_CONSTANT)
except ImportError:
expanded_nans = convolve2d(isnan.astype(float),
np.ones((sizes[order], sizes[order])),
mode='same')
log.debug(f"{name} expanding image NaNs: {time.perf_counter() - t:.3f} s")
t = time.perf_counter()
rotated_nans = rotation_function(expanded_nans, matrix, shift, order=min(order, 1),
missing=0, clip=False)
rotated_image[rotated_nans > 0] = np.nan
log.debug(f"{name} rotating image NaNs: {time.perf_counter() - t:.3f} s")
if needs_missing_handling:
t = time.perf_counter()
# Rotate a constant image to determine where to apply the NaNs for `missing`
constant = rotation_function(np.ones_like(image), matrix, shift, order=1,
missing=0, clip=False)
rotated_image[constant < 1] = np.nan
log.debug(f"{name} applying NaN missing: {time.perf_counter() - t:.3f} s")
if not handles_clipping and clip and not np.all(np.isnan(rotated_image)):
t = time.perf_counter()
# Clip the image to the input range
if np.isnan(missing):
# If `missing` is NaN, clipping to the input range is straightforward
rotated_image.clip(np.nanmin(image), np.nanmax(image), out=rotated_image)
else:
# Otherwise, check if `missing` should be considered part of the input range
lower = np.nanmin([np.max([missing, np.nanmin(rotated_image)]), np.nanmin(image)])
upper = np.nanmax([np.min([missing, np.nanmax(rotated_image)]), np.nanmax(image)])
rotated_image.clip(lower, upper, out=rotated_image)
log.debug(f"{name} clipping image: {time.perf_counter() - t:.3f} s")
return rotated_image
_rotation_registry[name] = _rotation_method(function=wrapper,
allowed_orders=set(allowed_orders))
# Add the docstring of the rotation function to the docstring of affine_transform
affine_transform.__doc__ += (f"\n **Specific notes for the '{name}' rotation method:**"
f"\n{wrapper.__doc__}")
return wrapper
return decorator
_rotation_method = namedtuple('_rotation_method', ['function', 'allowed_orders'])
_rotation_registry = {}
@add_rotation_function("scipy", allowed_orders=range(6),
handles_clipping=False, handles_image_nans=False, handles_nan_missing=True)
def _rotation_scipy(image, matrix, shift, order, missing, clip):
"""
* Rotates using :func:`scipy.ndimage.affine_transform`
* The ``order`` parameter is the order of the spline interpolation, and ranges
from 0 to 5.
* The ``mode`` parameter for :func:`~scipy.ndimage.affine_transform` is fixed to
be ``'constant'``
"""
rotated_image = scipy.ndimage.affine_transform(image.T, matrix, offset=shift, order=order,
mode='constant', cval=missing).T
return rotated_image
@add_rotation_function("scikit-image", allowed_orders=range(6),
handles_clipping=False, handles_image_nans=False, handles_nan_missing=False)
def _rotation_skimage(image, matrix, shift, order, missing, clip):
"""
* Rotates using :func:`skimage.transform.warp`
* The ``order`` parameter selects from the following interpolation algorithms:
* 0: nearest-neighbor
* 1: bi-linear
* 2: bi-quadratic
* 3: bi-cubic
* 4: bi-quartic
* 5: bi-quintic
* The implementation for higher orders of interpolation means that the pixels
in the output image that are beyond the extent of the input image may not have
exactly the value of the ``missing`` parameter.
* An input image with byte ordering that does not match the native byte order of
the system (e.g., big-endian values on a little-endian system) will be
copied and byte-swapped prior to rotation.
* An input image with integer data is cast to floats prior to passing to
:func:`~skimage.transform.warp`. The output image can be re-cast using
:meth:`numpy.ndarray.astype` if desired.
* Does not let :func:`~skimage.transform.warp` handle clipping due to
inconsistent handling across interpolation orders
* Does not let :func:`~skimage.transform.warp` handle image NaNs because they
are not handled properly for some interpolation orders
* Does not pass NaN as ``missing`` to :func:`~skimage.transform.warp` due to
inconsistent handling across interpolation orders
"""
try:
import skimage.transform
except ImportError:
raise ImportError("The scikit-image package is required to use this rotation method.")
# Make the rotation matrix 3x3 to include translation of the image
skmatrix = np.zeros((3, 3))
skmatrix[:2, :2] = matrix
skmatrix[2, 2] = 1.0
skmatrix[:2, 2] = shift
tform = skimage.transform.AffineTransform(skmatrix)
if issubclass(image.dtype.type, numbers.Integral):
warn_user("Integer input data has been cast to float64.")
adjusted_image = image.astype(np.float64)
else:
adjusted_image = image.copy()
# Scale image to range [0, 1]
im_min = np.nanmin([missing, np.min(adjusted_image)])
adjusted_image -= im_min
adjusted_missing = missing - im_min
im_max = np.nanmax([adjusted_missing, np.max(adjusted_image)])
if im_max > 0:
adjusted_image /= im_max
adjusted_missing /= im_max
# Swap the byte order if it is non-native (e.g., big-endian on a little-endian system)
if adjusted_image.dtype.byteorder == ('>' if sys.byteorder == 'little' else '<'):
adjusted_image = adjusted_image.byteswap().newbyteorder()
# Be aware that even though mode is set to 'constant', when skimage 0.19 calls scipy,
# it specifies the scipy mode to be 'grid-constant' rather than 'constant'
rotated_image = skimage.transform.warp(adjusted_image, tform, order=order,
mode='constant', cval=adjusted_missing, clip=clip)
# Convert the image back to its original range
if im_max > 0:
rotated_image *= im_max
rotated_image += im_min
return rotated_image
@add_rotation_function("opencv", allowed_orders={0, 1, 3},
handles_clipping=False, handles_image_nans=False, handles_nan_missing=False)
def _rotation_cv2(image, matrix, shift, order, missing, clip):
"""
* Rotates using |cv2_warpAffine|_ from `OpenCV <https://opencv.org>`__
* The ``order`` parameter selects from the following interpolation algorithms:
* 0: nearest-neighbor interpolation
* 1: bilinear interpolation
* 3: bicubic interpolation
* An input image with byte ordering that does not match the native byte order of
the system (e.g., big-endian values on a little-endian system) will be
copied and byte-swapped prior to rotation.
* An input image with integer data is cast to floats prior to passing to
|cv2_warpAffine|_. The output image can be re-cast using
:meth:`numpy.ndarray.astype` if desired.
"""
try:
import cv2
except ImportError:
raise ImportError("The opencv-python package is required to use this rotation method.")
_CV_ORDER_FLAGS = {
0: cv2.INTER_NEAREST,
1: cv2.INTER_LINEAR,
3: cv2.INTER_CUBIC,
}
order_to_use = _CV_ORDER_FLAGS[order]
if issubclass(image.dtype.type, numbers.Integral):
warn_user("Integer input data has been cast to float64.")
adjusted_image = image.astype(np.float64)
else:
adjusted_image = image.copy()
trans = np.concatenate([matrix, shift[:, np.newaxis]], axis=1)
# Swap the byte order if it is non-native (e.g., big-endian on a little-endian system)
if adjusted_image.dtype.byteorder == ('>' if sys.byteorder == 'little' else '<'):
adjusted_image = adjusted_image.byteswap().newbyteorder()
# missing must be a Python float, not a NumPy float
missing = float(missing)
return cv2.warpAffine(adjusted_image, trans, np.flip(adjusted_image.shape),
flags=order_to_use | cv2.WARP_INVERSE_MAP,
borderMode=cv2.BORDER_CONSTANT, borderValue=missing)
# Generate the string with allowable rotation-function names for use in docstrings
_rotation_function_names = ", ".join([f"``'{name}'``" for name in _rotation_registry])
# Insert into the docstring for affine_transform. We cannot use the add_common_docstring decorator
# due to what would be a circular loop in definitions.
affine_transform.__doc__ = affine_transform.__doc__.format(rotation_function_names=_rotation_function_names)
|
<reponame>DavidMChan/ChineseCheckers<gh_stars>1-10
#ifndef ENDGAME_DB_ELEMENT_H
#define ENDGAME_DB_ELEMENT_H
struct DBElement{
unsigned char a : 6, b : 6, c : 6, d : 6;
};
#endif
|
import java.util.Scanner;
public class Main {
private static int[] first = new int[6];
private static int[] second = new int[6];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 6; i++){
first[i] = scan.nextInt();
}
for(int i = 0; i < 6; i++){
second[i] = scan.nextInt();
}
for(int i = 0; i < 6; i++){
if(first[0] == second[i]){
action0(i);
/*System.out.println("-----------action0-----------");
System.out.println(first[0] + " " + first[1] + " " + first[2]
+ " " + first[3] + " " + first[4] + " " + first[5]);
System.out.println(second[0] + " " + second[1] + " " + second[2] + " "
+ second[3] + " " + second[4] + " " + second[5]);*/
if(first[5] == second[5]){
for(int j = 1; j <= 4; j++){
if(first[1] == second[j]){
action1(j);
/*System.out.println("-----------action1-----------");
System.out.println(first[0] + " " + first[1] + " " + first[2]
+ " " + first[3] + " " + first[4] + " " + first[5]);
System.out.println(second[0] + " " + second[1] + " " + second[2] + " "
+ second[3] + " " + second[4] + " " + second[5]);*/
if(first[3] == second[4]){
int intTemp = second[4];
second[4] = second[3];
second[3] = intTemp;
}
}
}
}
}
}
if(check()){
System.out.println("Yes");
}else{
System.out.println("No");
}
scan.close();
}
static void action0(int i){
int intTemp;
switch(i){
case 1:
intTemp = second[0];
second[0] = second[1];
second[1] = second[5];
second[5] = second[4];
second[4] = intTemp;
break;
case 2:
intTemp = second[0];
second[0] = second[2];
second[2] = second[5];
second[5] = second[3];
second[3] = intTemp;
break;
case 3:
intTemp = second[0];
second[0] = second[3];
second[3] = second[5];
second[5] = second[2];
second[2] = intTemp;
break;
case 4:
intTemp = second[0];
second[0] = second[4];
second[4] = second[5];
second[5] = second[1];
second[1] = intTemp;
break;
case 5:
intTemp = second[0];
second[0] = second[5];
second[5] = intTemp;
intTemp = second[1];
second[1] = second[4];
second[4] = intTemp;
break;
default:
break;
}
}
static void action1(int j){
int intTemp;
switch(j){
case 2:
intTemp = second[1];
second[1] = second[2];
second[2] = second[4];
second[4] = second[3];
second[4] = intTemp;
break;
case 3:
intTemp = second[1];
second[1] = second[3];
second[3] = second[4];
second[4] = second[2];
second[2] = intTemp;
break;
case 4:
intTemp = second[1];
second[1] = second[4];
second[4] = intTemp;
intTemp = second[2];
second[2] = second[3];
second[3] = intTemp;
break;
default :
}
}
static boolean check(){
if(first[0] == second[0] && first[1] == second[1] && first[2] == second[2] && first[3] == second[3] && first[4] == second[4] && first[5] == second[5]){
return true;
}else{
return false;
}
}
} |
Network analysis as a method of evaluating enterprise networks in regional development projects
The support of enterprise networks has an important role in the strategies and implementation of the EU’s cohesion policy programmes. Clustering and networking has become an instrument to increase the competitiveness of enterprises and consequently to create output and employment growth in less advantaged regions. However, so far, there is only weak evidence of the effects of networking projects on the competitiveness and business success of participating enterprises and on regional development. The article is based on a pilot study that tests network analysis as a method for evaluating networking projects, supported by the European Regional Development Fund. The study applied network analysis to identify a firm’s position in the project network and statistical methods to test the significance of identified network features that might explain business development. Preliminary results indicate that network characteristics can predict firm-level business indicators and firms’ assessments of the benefits of participating in the projects. |
Improving the Security of SMS-based Services using Electronic Signatures - Towards SMS-based Processing of Transactional m-Government Services
SMS is still one of the most popular mobile communication technologies. Simplicity, cost efficiency, and low bandwidth requirements account for the SMS technology’s continuing success. Besides the private sector, also public sector organisations aim to take advantage of SMS technology’s current popularity. In numerous countries all over the world, governments and public administrations already offer citizens SMS based m-Government services. However, most of these services are rather simple and do not include security enhancing mechanisms such as cryptographic methods. This renders the use of SMS based approaches for complex transactional m-Government services with higher security requirements difficult. We tackle this issue by proposing the use of electronic signatures in SMS based services. The technical feasibility of our approach is demonstrated by means of a prototypical application. This application allows citizens to generate, electronically sign, and deliver electronic documents by sending well-defined SMS messages. The proposed method’s capability to meet given security requirements of transactional m-Government services is assessed in the course of a detailed security discussion. |
original = list(input())
modified = original[::]
s = []
index = 0
for j in range(len(original)):
if(original[j]=='a'):
index = j
else:
s.append(original[j])
if(original.count('a')==len(original)):
print(''.join(original))
else:
last = original[index+1:]
s = s[:len(s)-len(last)]
if(len(s)>len(last)):
print(':(')
else:
diff = len(last)-len(s)
if(diff%2==0):
s.extend(last[0:diff//2])
last=last[diff//2:]
if(s==last):
print(''.join(original[:index+1+diff//2]))
else:
print(":(")
else:
print(':(')
|
def store_user(request, response, project_key, user_id):
projects = {}
json_str = request.cookies.get('projects')
if json_str is not None:
try:
projects = json.loads(json_str)
except (ValueError, KeyError, TypeError):
print "JSON format error"
logging.exception("Cookie json could not be decoded")
projects[project_key] = user_id
cookie_json = json.dumps(projects)
response.set_cookie('projects', cookie_json, max_age=10 * 365 * 24 * 60 * 60) |
<reponame>openshift-cherrypick-robot/sdn
package main
import (
"context"
"github.com/Microsoft/hcsshim/internal/log"
"github.com/Microsoft/hcsshim/internal/oc"
"github.com/containerd/containerd/namespaces"
shim "github.com/containerd/containerd/runtime/v2/shim"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
type publisher interface {
publishEvent(ctx context.Context, topic string, event interface{}) (err error)
}
type eventPublisher struct {
remotePublisher *shim.RemoteEventsPublisher
}
var _ = (publisher)(&eventPublisher{})
func newEventPublisher(address string) (*eventPublisher, error) {
p, err := shim.NewPublisher(address)
if err != nil {
return nil, err
}
return &eventPublisher{
remotePublisher: p,
}, nil
}
func (e *eventPublisher) close() error {
return e.remotePublisher.Close()
}
func (e *eventPublisher) publishEvent(ctx context.Context, topic string, event interface{}) (err error) {
ctx, span := trace.StartSpan(ctx, "publishEvent")
defer span.End()
defer func() { oc.SetSpanStatus(span, err) }()
span.AddAttributes(trace.StringAttribute("topic", topic))
log.G(ctx).WithFields(logrus.Fields{
"topic": topic,
"event": event,
}).Debug("Publishing event")
if e == nil {
return nil
}
return e.remotePublisher.Publish(namespaces.WithNamespace(ctx, namespaceFlag), topic, event)
}
|
Role model: Cameron Smith says players should accept the responsibility that comes with playing NRL footy. Credit:Matt King On Thursday, as the Kangaroos side came together at Coogee ahead of the Four Nations, the captain was asked if he was angry that little had changed. "Absolutely," he told this column. "I don't see why it's so hard to be a good person and do the right thing. I understand there are going to be issues that arise all the time. That's life. That's not just sportsmen. We all go through ups and downs. But the ones I get really annoyed and upset about are the avoidable situations that footy players get themselves into. I don't understand why they have to be there at that time to get in that strife. "I hear all these things about, 'I'm not a role model, I'm just here to play footy'. Unfortunately, when you get the opportunity to play in the NRL, that's what it is. Somewhere, out there, there's someone who aspires to be like you. You need to accept that responsibility. You should know what the wrong or right decision is. Make the right one. That's what I am asking players to do." Smith said this without mentioning Sharks prop Andrew Fifita or Eels winger Semi Radradra, who were overlooked for the Four Nations tour because of their off-field issues.
Captain and coach: Cameron Smith and Mal Meninga. Credit:Louie Douvis Radradra is facing domestic violence charges and faces court in Sydney on November 28 – eight days after the final is held at Anfield in Liverpool. The integrity unit is still looking into Fifita and his use of armbands supporting one-punch killer Kieran Loveridge. According to a Fairfax Media report, he is considering walking away from the game. As more than a few point out, Fifita needs rugby league more than rugby league needs him. Indeed, if you removed a select dozen or so individuals from the 400-or-so players in the NRL, you probably aren't reading this column. The NRL and commission chairman John Grant have decided to draw a line in the sand, not with their big toe but a Caterpillar D4 bulldozer.
"I firmly stand behind Mal [Australian coach Mal Meninga]," Smith said of the decision to ban Fifita and Radradra. "We really need to set standards in our sport." Behind closed doors at League Central, there's a concession that it erred in picking Radradra for the Prime Minister's XIII match, especially when the jumper he was playing in was emblazoned with support for a campaign against domestic violence. It was an embarrassing gaffe from the league – policy on the run at its worst – but that doesn't mean banning Fifita and Radradra was the wrong call. Like many fans, Smith doesn't buy into the argument that the responsibility of ensuring a player does the right thing rests with the club or game or manager or anyone else. It rests with the player.
"They're young men playing our game – but they are men," he says. "They're not boys. I'd like to think everyone playing in our competition knows the difference between wrong and right. It's not up to welfare officers to call you up and see what you're doing 24 hours a day." As for his memorable speech in defeat after the Storm's grand final loss to Cronulla last Sunday, Smith doubts he has won over the Sydney crowd. He was booed as he took the stage but applauded as he left the stage. "Fans are passionate about their teams and there wouldn't be many times when they have seen their side beat the Melbourne Storm," Smith says. "So I understand that it's easy to dislike a guy like myself. I totally get that. That's sport. They don't have access to NRL players like you do, you don't get to see the person. I think they saw a small part of what we're about the other night." Then a laugh.
"But they'll go back to hating me next year!" 'ET' pic one for the ages It will never surpass the iconic image of Norm Provan and Arthur Summons, but the picture of Sharks captain Paul Gallen and club legend Andrew Ettingshausen embracing each other, in tears, after the grand final is one for the ages. For many, though, the sight of Ettingshausen front and centre on grand final night raised a few eyebrows. According to some of his former teammates, "ET" has been aloof and distant from the club for many years – although he's willing to help out when asked.
There's also lingering distaste about his much-publicised affair with the wife of former teammate Paul Mellor, an episode he blamed on depression caused by bad financial decisions. For the record, the NRL decided to use Ettingshausen – and retired Storm legend Matt Geyer – as on-field talent on grand final day. That's why he was so visible in celebrations. In the eyes of many, it was great to see a club legend of his stature welcomed back into the fold. He had every right to be celebrating with a club he helped – in no small part – to build. Holt's stepson not a Sharkie
The surviving stepson of the late Harold Holt is hardly doing backflips over the Sharks' win. Jack Gibson's immortal line – "Waiting for Cronulla to win the premiership is like leaving the porch light on for Harold Holt" – was finally put to rest with grand final victory. The reference is to the former Prime Minister who disappeared while swimming near Portsea in 1967 – Cronulla's first season in the competition. So said Sam Holt when we contacted him this week: "It's quite a witty line – but I didn't know about it until a week ago. I have no interest in sport. As long as they think of him [Harold] fondly, I have no problem with it." Bias complaints miss the point
There's nothing more amusing than complaints about biased footy commentary. Channel Nine has copped it in the neck this week for their "biased" coverage of the NRL grand final, with an unlikely protagonist in Channel Ten newsreader Sandra Sully who took to Twitter to condemn the "bias" towards the Sharks. We love you, Sandra, as you know … but really? You can surely understand the callers being enthusiastic about the Sharks edging closer and closer to their maiden premiership 50 years after joining the competition. As Nine sports boss Tom Malone pointed out when we contacted him, Phil Gould, Peter Sterling, Andrew Johns, Brad Fittler, Darren Lockyer and Wally Lewis are paid to have a say.
"They're our rugby league experts," he said. "They're paid for their opinions. The only person who gets paid for neutral commentary is Rabs [play-by-play caller Ray Warren]." On the road again: Kate Peck, Todd Kelly, Matt Campbell and Rick Kelly on their road trip. Q&A: Rick Kelly We speak to the two-time Bathurst winner as he prepares for another assault on the Mountain for Nissan this Sunday. Your road trip from Melbourne to Bathurst each year is becoming almost as iconic as the race itself.
We've done it for 15 years. We always wonder if we'll have any trouble along the way, given the cars are so old. We drove a 1963 Datsun Bluebird station wagon this year. It's hard to be in a rush when you're in something like that. About 95km/h is where she is happy. We dress up in the vintage clothes from the same era as the car. I was wearing some nice flashy pants. What do you learn about Bathurst with each year you race in it? The first thing you learn about this place is that it demands respect. You see it every year. Someone comes unstuck significantly. You need to treat the place with a lot of respect, you can't go out flat-stick straight away. You work up to it. You need a car that's nice and comfortable, not too edgy at the top of the hill, and as the weekend progresses you build that confidence in yourself and the car. How spent are you physically after the race? It depends on how the race is run. You have to keep your nutrition and hydration up all week. By the time Sunday comes, it's already been a big week. Depending on how the race pans out, you might need to do a triple stint at the end of it, which has happened to me the last few years. If your car is misbehaving, you really have to hold on tight.
And what do you remember when you did win alongside Greg Murphy in 2003 and 2004? It's an incredible moment because I grew up watching it. I've been coming to the track for 20 years. You walk out onto the podium and there's thousands of people screaming at you. It's insane. The week THE QUOTE "FIFA dropping in to check on the FFA is like Elvis popping round to make sure you're eating properly". – Great one-liner from MC Adam Peacock while interviewing Steve Lowy at the season launch for Sydney FC.
THUMBS UP DeSean Jackson, the Washington Redskins wide receiver, wore custom-designed boots featuring police caution tape to protest the shootings of unarmed African Americans. "I felt like I've been silent long enough," he said. THUMBS DOWN It's the best run club of any code in the country … but how did the Sydney Swans get it so wrong in failing to have an open fan day after the AFL grand final? The Swannies say it was only going ahead if they won, which doesn't make it right. It's a big weekend for … the Wanderers, who haven't beaten Sydney FC in over a thousand days. The pair clash in the Sydney derby at ANZ Stadium on Saturday night.
It's an even bigger weekend for … the Wallabies. Again. They meet the Pumas at Twickenham before flying back to Auckland to play New Zealand before heading to Wales for the start of the Spring Tour. Wheeeeeeee! |
/* Autogenerated file. Do not edit manually. */
/* tslint:disable */
/* eslint-disable */
export * as interfaces from "./interfaces";
export { PrivateVault__factory } from "./PrivateVault__factory";
export { VaultHub__factory } from "./VaultHub__factory";
|
Most parents will tell you they love their children equally. Mothers and fathers will try to convince you they distribute their love evenly — they’ll say they love their babies the same. Not only is this impossible, it doesn’t even work.
When it comes to multiple offspring, the key is to love them differently. Individually. As they are, for who they are. Every relationship you have is unique; this doesn’t change when it comes to your kids.
“I don’t love one more — I love them differently,” says Anita DeVille, mother of two and president of Imagine That Family Care Services, “I love them separately.”
DeVille first became a mother to Madison, 18, in 1997 and reproduced again and gave birth to Sean, 15, a few years later. When her daughter was born, she had a certain personality — different parts about her — DeVille loved every part of her and her experiences.
“Then we had Sean three years later — he didn’t come out exactly like Madison. He came out completely different, with his own personalities,” DeVille says, “He wasn’t a clone of Madison. He was his own person.”
Of course, she loved everything about Sean’s personality. The two children each brought different experiences — it was never a matter of who she loved more. Throughout their childhood, DeVille supported each in their ventures: for Madison it was art and for Sean, it was sports.
DeVille thinks the ‘who do you love more’ question is horrible. She doesn’t think parents should have to explain this to anyone. The only time this type of question came up at home was when the kids heard it from friends or the media. As a parent, she handled it with openness and honesty. She shared a list of traits she loved about each child and emphasized that she loved everything about them individually.
No two people are the same. How can you compare apples to oranges?
“The only thing you can say is equal is if I were to express my love through material items: they each get a scooter, backpacks, movie tickets or the same toy,” DeVille explains, “I can’t give time equally — three hours for each?”
Instead, she follows her intuition and accommodates each child as she sees fit — as they need it. Whatever they need. DeVille is always there to give them both lifts to where they need to go.
It’s about language. The only thing parents might need to change is what they say to children and to other people. Instead of ‘I love my children equally’ consider saying, I love them independently, I love them differently because they’re different people — better yet, you can stop at I love them.
Ultimately, it comes down to communication with people — talk it out. It’s, in fact, pretty simple. Parents shouldn’t feel guilty for giving something to one child and not the other. You’ve customized your care for each individual child.
“That’s exactly what my care providers do,” DeVille explains. Her company Imagine That provides family care services from well trained educators that offer children learning experiences. “We know the basic age and stage of a child, but it isn’t until we get a profile from the parents that we actually start to know their interests.”
As we know, not all five year olds are the same nor do they all have the same interests.
“For teachers and any care providers — there are basics, but it’s not about equality,” explains DeVille with over 26 years of experience working with children in the industry, “It’s about knowing each individual and accommodating their needs — working to develop their skills at their level.”
At the end of the day, it’s about celebrating differences, understanding them and working with who you are developing. Humans, from the get-go are complex beings.
You can distribute gifts equally, split things down the middle and do your best to offer the same amount of affection. But when it comes to loving humans — it’s not about busting out the measuring cups.
Sponsored post by Imagine That Family Care Services |
<reponame>moxley/chat
package chat
// Message a message
type Message struct {
Body string
From *Client
To *Client
ToStr string
}
|
A few weeks before The Paris Review’s Spring Revel, the Transom asked Courtney Love if she would be in attendance to watch her grandmother, the novelist Paula Fox, accept the Hadada Award.
No, she would not.
“Paula’s absolute dislike of me is shocking and inexplicable,” Ms. Love told us.
The strained relationship is perhaps not that inexplicable. Ms. Love found out about her literary lineage late in life, when her mother, Linda Carroll, tracked down Ms. Fox, who had put her daughter up for adoption. Ms. Fox had herself been abandoned by her mother, a Hollywood gadabout who party-hopped with her husband’s cousin, Douglas Fairbanks, out-drank F. Scott Fitzgerald and once got thrown into a lake by Humphrey Bogart.
Ms. Love and Ms. Fox have met only once, during a brief sit-down at the Mercer Hotel. And Ms. Fox has no relationship with her great-granddaughter, Frances Bean Cobain.
Much of Ms. Love’s animosity toward Ms. Fox, she told us, stems from the fact that she doesn’t know the identity of her grandfather. She’s wondered, given some evidence from the past, if it could be Marlon Brando.
This speculative genealogy lingered when the day of the Spring Revel arrived last week. Paris Review editor Lorin Stein had corralled Gay Talese, Jeffrey Eugenides, Zadie Smith, Sam Lipsyte, Mona Simpson and many brilliant others into Cipriani on 42nd Street, and they all mingled beneath the marble buttresses, exuding literary genius and ordering drink after drink at the bar.
The novelist Lynne Tillman asked if we wanted to meet Ms. Fox and then steered us to a tiny table. There sat Ms. Fox, the writer whom Jonathan Franzen called superior to John Updike and Philip Roth and Saul Bellow, diminutive and raspy but still vigorously alive.
“These chandeliers,” Ms. Fox said, staring up. “They look like tangerines.”
Or blood oranges, we countered.
“Blood tangerines,” she decided.
The subject of Courtney Love came up.
“She’s awful, she’s awful. She’s terrible!” Ms. Fox told us. “I met with her for an hour, and the hour was like an hour in the devil’s pocket, for both of us. Things last such a short time in this country. People have their moments. Courtney had her moment, and was very strong, and she had enormous vitality, but that moment is gone.”
She launched into a coughing fit.
“I don’t want to be mean,” she said after composing herself. Her eyes almost watered, and maybe she was on the brink of forgiveness. “Poor everybody,” she sighed.
A few days later, the Transom rode out to New London, Conn., where the Lyman Allyn Art Museum was hosting a reception for Mentoring Courtney Love, an exhibition displaying watercolors by Ms. Love and photographs by David LaChapelle. It is her first museum show.
“Over here, over here,” Ms. Love beckoned from the middle of a mob as we entered the lobby, squeezing by a cluster of local teenage girls clutching Hole records and posters, pens at the ready. “It’s like a record signing,” she said.
Later that evening, Nancy Stula, the director of the museum, had arranged for an intimate dinner at her home in Old Lyme, and we found ourselves near the head of the table, where Ms. Love sat.
“You know, Nate met my grandmother the other night,” Ms. Love told the muted Connecticut gentry seated around her. That topic hung like a ghost in the room, and after a few moments, the discussion turned to Paula Fox’s onetime companion, the unknown man who begat Courtney’s mother.
“It could be a sailor, for all I care,” said Ms. Love, though she admitted that she would at least like to know who granddad is—and pursuing that theory is a fun parlor game. “Paula was living with Ellen Adler when she became pregnant, and Marlon Brando was basically a member of the Adler household then,” she said.
We rattled off the evidence to skeptical guests: Ms. Love had become intrigued by comments Brando made to her while hanging out at Carrie Fisher’s house, and then she discovered the connection between Brando, Stella Adler—the actor’s influential mentor who housed him before he became a star—Ms. Adler’s daughter, Ellen Adler, and Ms. Fox. They were all very close—Ms. Fox would dedicate her 1990 novel, The God of Nightmares, to Ellen, and Brando spoke with Ellen daily until his death. What’s more, during the period that Ms. Fox was pregnant, Brando claims to have fathered dozens of kids he’d never know.
But there is no proof. Ms. Love explained that she had a chance to steal Brando’s toothbrush and test the DNA, but decided against it.
Then she rose, though we were still on our salad course. She had to fly to Las Vegas to film a commercial for an electronic cigarette. But before leaving, she had time to offer one more clue as to her bloodline.
“If you look at me before my first nose job,” Ms. Love said, smiling, “I kind of look like Marlon Brando.” |
Of course there's a lot of overlap when it comes to porn and copyright infringement. The entire business model of many porn aggregation sites seems to be to steal videos from subscription services and offer them for free, although the relationship between such sites is more complicated than you might think.
The ACL can't simply point out that YouPorn has lifted videos from other sites and therefore convince a judge that YouPorn should be blocked. The complaint has to come from the copyright holder, or from an Australian company that has licensed the content – although just one infringement is enough to lodge a request to have a site blocked.
To have YouPorn blocked, the ACL would need to either own or license something that's on the site – which is perhaps a bridge too far in their fight against porn. Depending on how it was done, such tactics might be viewed by the courts as an abuse of process and knocked back – one of the advantages of having this process overseen by a judge rather than backroom bureaucrats.
There's another more practical loophole for anti-porn crusaders to target; music. You can be sure if you trawled through any porn aggregation site that you'd find clips using copyrighted music without permission. If you found an artist or music label happy to play ball, you might be able to have porn sites blocked that way – assuming the judge signed off on it. Alternatively the ACL could license the Australian rights to "bow chicka wow wow" and hope to wipe out 1970s porn overnight.
You can be sure that every lobby group in Australia which wants something banned is sitting around brainstorming ideas on how to turn the new anti-piracy rules to their advantage. Rather than looking for loopholes, the ACL will more likely just bide its time and wait for the government to declare the anti-piracy laws a success. |
package com.brainacad.module_1.LabWork_1_4;
/**
* Created by a.zemlyanskiy on 01.09.2016.
* Write a console program that prints result of Bitwise operators for two integer variables.
*/
public class Lab_Work_1_4_6 {
public static void main(String[] args) {
int a = 0x000F;
int b = 0x2222;
System.out.println(Integer.toBinaryString(b & a));
System.out.println(Integer.toBinaryString(b ^ a));
System.out.println(Integer.toBinaryString(b | a));
System.out.println(Integer.toBinaryString(~a));
}
}
|
Getty Images
The encore for Ted Wells officially has run longer than his debut.
As noted by NFL Media’s Albert Breer, the Wells-led investigation into the #DeflateGate scandal has now consumed more time than the investigation conducted by Wells regarding the Dolphins bullying scandal. In Miami, Wells’ work was done in 100 days; his latest project is at 103 days and counting.
While the two situations have many differences, the Dolphins scandal required interviews of many people and a review of thousands of text messages, followed by an effort to harmonize conflicts in the information provided by witnesses and to explore and explain other incidents that emerged as Wells examined the allegations that resulted in former Dolphins tackle Jonathan Martin leaving the team abruptly in late October 2013. The question of whether the Patriots deliberately deflated footballs used during the AFC championship game against the Colts would seem on the surface to entail a far less complex set of facts and a far more narrow universe of potential witnesses and evidence.
In fairness to Wells, the NFL emphasized upon hiring him that there would be no timetable on his work. But did anyone expect that his work would last into May?
Commissioner Roger Goodell has repeatedly said that the report from Wells is coming soon. It’s unclear whether the NFL will release the report publicly before Goodell determines the penalties, if any, that will be imposed as a result of the findings.
Regardless, the ultimate bad-news dump comes in 16 days: The Friday of Memorial Day Weekend. The only thing keeping the report from being released then could be the league’s sensitivity to the perception that it tries to bury bad news into the final hours of the work week. |
// ListOwners retrieves a list of the group's owners. The owners are a set of users who are allowed to
// modify the group object. Owners are currently not available in Microsoft Graph for groups that were created in
// Exchange or groups that are synchronized from an on-premises environment.
//
// GET /groups/{id}/owners
//
// MS Graph API doc:
// https://docs.microsoft.com/en-us/graph/api/group-list-owners?view=graph-rest-beta&tabs=http
func (s *GroupsService) ListOwners(ctx context.Context, groupID string, opts *ListOptions) (*UsersResponse, error) {
u := msgraph.URL(Groups, groupID).Append(Owners).Options(opts).Build()
req, err := s.client.NewRequest(http.MethodGet, u, nil)
if err != nil {
return nil, err
}
usersResp := new(UsersResponse)
_, err = s.client.Do(ctx, req, usersResp)
if err != nil {
return nil, err
}
return usersResp, nil
} |
Profound bradycardia following release of cardiac tamponade. Hypothesis for reflex control.
A 58-year-old patient with chronic renal failure presented for routine hemodialysis, and was noted to have severe hypotension and findings on examination compatible with cardiac tamponade. The patient had emergency construction of a pericardial window. At the time of surgery, rapid evacuation of the pericardial space resulted in rebound hypertension associated with marked bradycardia. The features of the patient's case were analogous to the cardiovascular and reflex adjustments that normally occur during the Valsalva maneuver. These findings suggest that the cardiovascular changes occurring during the rapid decompression of cardiac tamponade may be reflexly-mediated, and gradually decompression of the pericardial space is therefore recommended to avoid reflex hypertension and bradycardia. |
// NewIngressCollector creates a new collector for the Kubernetes Ingress
// resource.
func NewIngressCollector() *IngressCollector {
return &IngressCollector{
metadata: &collectors.CollectorMetadata{
IsStable: false,
Name: "ingresses",
NodeType: orchestrator.K8sIngress,
},
processor: processors.NewProcessor(new(k8sProcessors.IngressHandlers)),
}
} |
/**
* Created by luying on 17/2/7.
*/
public class ChaseCmd extends UserBaseCmd{
int targetId;
public ChaseCmd(byte[] bytes){
parse(bytes);
}
public int getTargetId() {
return targetId;
}
public void setTargetId(int targetId) {
this.targetId = targetId;
}
public ChaseCmd(int userId ,int targetId){
this.userId =userId;
this.targetId= targetId;
}
@Override
public byte[] toBytes(){
return ByteUtil.createBuffer().put(cmdType.getType())
.put(userId)
.put(targetId)
.array();
}
public void parse(byte[] bytes){
ByteBufferWrap byteBufferWrap = ByteUtil.createBuffer(bytes);
byteBufferWrap.getInt();
this.userId= byteBufferWrap.getInt();
this.targetId =byteBufferWrap.getInt();
}
private CmdType cmdType =CmdType.CHASE;
@Override
public CmdType getCmdType() {
return cmdType;
}
} |
//-----------------------------------------------------------------------------
// Compute vertex buffer for terrain that is a 2D grid.
// The computed terrain spans [0,1] in texture coordinates (inclusive on edges).
// The array pointed to by pResult is assumed to have m_numVertices elements, which are filled in by valid data by this function.
//-----------------------------------------------------------------------------
void TerrainGenerator::GenerateVertices()
{
float minDimension = -100.0f;
float maxDimension = 100.0f;
const float frac = 1.0f / static_cast<float>(m_args.m_terrainSideSize - 1);
concurrency::parallel_for(UINT(0), m_args.m_terrainSideSize, [&](UINT y)
{
for (UINT x = 0; x < m_args.m_terrainSideSize; x++)
{
Vertex& vtx = m_vertices[y * m_args.m_terrainSideSize + x];
vtx.pos.x = Lerp(minDimension, maxDimension, (float)x / (m_args.m_terrainSideSize - 1));
vtx.pos.z = Lerp(minDimension, maxDimension, (float)y / (m_args.m_terrainSideSize - 1));
float height = 0.0f;
for (UINT i = 0; i < m_args.m_numOctaves; i++)
{
float coordModulate = float(1 << i);
float heightModulate = 1.0f / (coordModulate * coordModulate);
XMFLOAT2 noiseCoordinates = XMFLOAT2(
vtx.pos.x * coordModulate / m_args.m_noiseScale,
vtx.pos.z * coordModulate / m_args.m_noiseScale);
height += Noise(noiseCoordinates) * heightModulate;
}
Modulate height by a Gaussian to create a central mountain
float distanceFromCenter = sqrtf(vtx.pos.x * vtx.pos.x + vtx.pos.z * vtx.pos.z);
vtx.pos.y = m_args.m_heightScale * height * Gaussian(distanceFromCenter, m_args.m_mountainSize);
vtx.tex.x = x * frac; u,v = 0.0..1.0 evenly distributed
vtx.tex.y = y * frac;
FIXME? the terrain is shown upside down!
vtx.tex.x = 1.f - vtx.tex.x;
}
});
Compute normals
Each vertex is surrounded by six triangles (except at edges).
Compute smooth normal as the average of these connected triangle's face normals.
We do this by looping over quads, and for each of its two triangles,
compute face normal and accumulate to each of the triangle's three vertices.
std::vector<XMVECTOR> normals(
m_args.m_terrainSideSize * m_args.m_terrainSideSize,
XMVectorSet(0.f, 0.f, 0.f, 0.f));
concurrency::parallel_for(UINT(0), m_args.m_terrainSideSize - 1, [&](UINT y)
{
for (UINT x = 0; x < m_args.m_terrainSideSize - 1; x++)
{
UINT vtx0 = (y * m_args.m_terrainSideSize) + x;
Upper triangle (CCW)
{
UINT vtx2 = vtx0 + 1;
UINT vtx1 = vtx0 + 1 + m_args.m_terrainSideSize;
XMVECTOR n = ComputeNormal(vtx0, vtx2, vtx1);
normals[vtx0] += n;
normals[vtx1] += n;
normals[vtx2] += n;
}
Lower triangle (CCW)
{
UINT vtx2 = vtx0 + 1 + m_args.m_terrainSideSize;
UINT vtx1 = vtx0 + m_args.m_terrainSideSize;
XMVECTOR n = ComputeNormal(vtx0, vtx2, vtx1);
normals[vtx0] += n;
normals[vtx1] += n;
normals[vtx2] += n;
}
}
});
for (size_t i = 0; i < normals.size(); i++)
{
XMVECTOR n = XMVector3Normalize(normals[i]);
XMStoreFloat3(&m_vertices[i].normal, n);
}
} |
/**
* Adds condition to root node
* @param condition
* @return
*/
public boolean addCondition(AdvancedConditionsNode condition)
{
whereCondition.add(new DefaultMutableTreeNode(condition));
return false;
} |
Ethnicity and Health Care in Cervical Cancer Survival: Comparisons between a Filipino Resident Population, Filipino-Americans, and Caucasians
Few studies have assessed and compared cervical cancer survival between developed and developing countries, or between ethnic groups within a country. Fewer still have addressed how much of the international or interracial survival differences can be attributed to ethnicity or health care. To determine the role of ethnicity and health care, 5-year survival of patients with cervical cancer was compared between patients in the Philippines and Filipino-Americans, who have the same ethnicity, and between Filipino-Americans and Caucasians, who have the same health care system. Cervical cancer databases from the Manila and Rizal Cancer Registries and Surveillance, Epidemiology, and End Results 13 were used. Age-adjusted 5-year survival estimates were computed and compared between the three patient groups. Using Cox proportional hazards modeling, potential determinants of survival differences were examined. Overall 5-year relative survival was similar in Filipino-Americans (68.8%) and Caucasians (66.6%), but was lower for Philippine residents (42.9%). Although late stage at diagnosis explained a large proportion of the survival differences between Philippine residents and Filipino-Americans, excess mortality prevailed after adjustment for stage, age, and morphology in multivariate analysis . Excess mortality decreased, but persisted, when treatments were included in the multivariate models (RR, 1.78; 95% CI, 1.41-2.23). A moderate, marginally significant excess mortality was found among Caucasians compared with Filipino-Americans (adjusted RR, 1.22; 95% CI, 1.01-1.47). The differences in cervical cancer survival between patients in the Philippines and in the United States highlight the importance of enhanced health care and access to diagnostic and treatment facilities in the Philippines. (Cancer Epidemiol Biomarkers Prev 2009;18(8):2228–34) |
// simple test to make sure the C bindings to offsetof() are valid.
func TestLmapOffsets(t *testing.T) {
if lname_offset() >= lnext_offset() {
t.Fatalf("lname offset (%d) should be l.t. lnext offset (%d)",
lname_offset(), lnext_offset())
}
} |
//==========================================================================
//
// Bismillahir-Rahmanir-Rahim
//
// ==========================================================================
#include <bits/stdc++.h>
#define ll long long int
#define f(x,y,z) for(int x=y;x<z;x++)
#define pii pair<int,int>
#define pll pair<ll,ll>
#define CLR(a) memset(a,0,sizeof(a))
#define SET(a) memset(a,-1,sizeof(a))
#define N 100010
#define M 1000000007
#define pi acos(-1.0)
#define ff first
#define ss second
#define pb push_back
#define inf (int)1e9
using namespace std;
int dx[]={0,0,1,-1,-1,-1,1,1};
int dy[]={1,-1,0,0,-1,1,1,-1};
template < class T> inline T biton(T n,T pos){return n |((T)1<<pos);}
template < class T> inline T bitoff(T n,T pos){return n & ~((T)1<<pos);}
template < class T> inline T on(T n,T pos){return (bool)(n & ((T)1<<pos));}
template < class T> inline T gcd(T a, T b){while(b){a%=b;swap(a,b);}return a;}
template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); }
inline int nxt(){int aaa;scanf("%d",&aaa);return aaa;}
inline ll lxt(){ll aaa;scanf("%I64d",&aaa);return aaa;}
template <class T> inline T bigmod(T p,T e,T m){T ret = 1;
for(; e > 0; e >>= 1){
if(e & 1) ret = (ret * p) % m;p = (p * p) % m;
} return (T)ret;}
#define sayed
#ifdef sayed
#define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;}
#else
#define debug(args...) // Just strip off all debug tokens
#endif
struct debugger{
template<typename T> debugger& operator , (const T& v){
cerr<<v<<" ";
return *this;
}
}dbg;
///******************************************START******************************************
int ar[N];
int tree[3*N];
void segment_tree(int node,int low,int high){
if(low==high){
tree[node]=ar[low]; return;
}
int left=2*node;
int right=2*node+1;
int mid=(low+high)/2;
segment_tree(left,low,mid);
segment_tree(right,mid+1,high);
tree[node]=gcd(tree[left],tree[right]);
}
int query(int node,int low,int hi,int i,int j){
if(i>hi||j<low) return 0;
if(low>=i&&hi<=j)
return tree[node];
int mid=(low+hi)/2;
int left=2*node;
int right=left+1;
int x= query(left,low,mid,i,j);
int y= query(right,mid+1,hi,i,j);
return gcd(x,y);
}
map<int,vector<int> > mp;
map<int,vector<int> > :: iterator it;
int main(){
// freopen("out.txt","w",stdout);
//ios_base::sync_with_stdio(false);
// cin.tie(0);
int n=nxt();
f(i,1,n+1){ ar[i]=nxt();
mp[ar[i]].pb(i);
}
segment_tree(1,1,n);
int m=nxt();
while(m--){
int a=nxt(),b=nxt();
int gc=query(1,1,n,a,b);
int l=lower_bound(mp[gc].begin(),mp[gc].end(),a)-mp[gc].begin();
int r=upper_bound(mp[gc].begin(),mp[gc].end(),b)-mp[gc].begin();
int cut=r-l;
printf("%d\n",b-a+1-cut);
}
return 0;
}
|
<filename>src/intercept/nextError.ts
/* eslint-disable */
// @ts-nocheck
import i18n from '@/i18n/index.ts'
import { Message } from 'element-ui'
export default function (to, from, next: Function, path = '/404') {
console.log('错误路由处理')
const error = process.env.VUE_APP_ROUTER_ERROR_PAGE_JUMP
// next(new Error()) // 进行跳转到要跳转的路由
if (error === 'true' || path !== '/404') {
next({ path, replace: true })
} else {
Message({ message: i18n.tc('tip.error.page'), type: 'error' })
next({ path: from.path, replace: true })
}
}
|
Emerging Diagnostic and Therapeutic Potentials of Human Hair Proteomics
The use of noninvasive human substrates to interrogate pathophysiological conditions has become essential in the post‐ Human Genome Project era. Due to its high turnover rate, and its long term capability to incorporate exogenous and endogenous substances from the circulation, hair testing is emerging as a key player in monitoring long term drug compliance, chronic alcohol abuse, forensic toxicology, and biomarker discovery, among other things. Novel high‐throughput ‘omics based approaches like proteomics have been underutilized globally in comprehending human hair morphology and its evolving use as a diagnostic testing substrate in the era of precision medicine. There is paucity of scientific evidence that evaluates the difference in drug incorporation into hair based on lipid content, and very few studies have addressed hair growth rates, hair forms, and the biological consequences of hair grooming or bleaching. It is apparent that protein‐based identification using the human hair proteome would play a major role in understanding these parameters akin to DNA single nucleotide polymorphism profiling, up to single amino acid polymorphism resolution. Hence, this work seeks to identify and discuss the progress made thus far in the field of molecular hair testing using proteomic approaches, and identify ways in which proteomics would improve the field of hair research, considering that the human hair is mostly composed of proteins. Gaps in hair proteomics research are identified and the potential of hair proteomics in establishing a historic medical repository of normal and disease‐specific proteome is also discussed. |
Figure 1. Schematics (not to scale) of the fabrication process steps (top) and the corresponding optical microscope images (bottom) of a representative all-2D FET. (i) Transfer of large-area CVD grown bilayer graphene onto a Si/SiO 2 substrate. (ii) Bilayer graphene patterning by O 2 plasma to define S/D contacts. (iii) Transfer of a few-layer MoS 2 flake on top of the patterned grahene S/D contacts. (iv) Transfer of a few-layer h-BN gate dielectric, overlapping the MoS 2 channel. (v) Transfer of a multilayer graphene top gate electrode. (vi) Optical microscope image of a fully fabricated all-2D transistor. Scale bar is 5 μm for all images.
Two-dimensional (2-D) material systems have aroused immense interest in research due to the possibility of obtaining thickness uniformity down to a monolayer without surface dangling bonds. Graphene (Gr), as a two-dimensional semimetal has been studied extensively for the purpose of analog and digital applications. However, the absence of an intrinsic bandgap in Gr overshadows its attractive properties of small quantum capacitance and extremely high mobilities in scaled transistors. (1-3) Transition metal dichalcogenides (TMDC), with an inherent bandgap, tunable by composition and the number of layers, have ignited significant interest and promise over the past few years for both electronic and optoelectronic applications. (4-7) For instance, MoSand WSehave been used to obtain excellent switching current ratios (up to 10), and ideal subthreshold slope (60 mV/decade). (8-12) One of the primary advantages of layered materials is, in principle, the absence of dangling bonds, which rules out performance degradation due to interface states. (13) Uniquely, heterostructures using two-dimensional materials would not suffer from constraints of lattice mismatch. A layered material can be seamlessly transferred onto another, and bond by van der Waal’s (vdW) forces, leaving the interface pristine. An ideal transistor structure would, therefore, be composed of a TMDC material as the channel, with a layered insulator as the gate dielectric, and layered metallic source/drain and gate contacts. Atomically thin p-n diodes have been reported, using MoSand WSemonolayers as the electron and hole conducting layers, respectively. (14-16) These vdW heterostructure diodes have exhibited excellent rectification behavior owing to the abruptness of the 2D–2D interface, with ideality factor of 1.2. MoStransistors with graphene source/drain contacts have been used to fabricate flexible, transparent transistors. (17) Also, flexible and transparent MoStransistors with graphene source/drain contacts were fabricated with h-BN as back gate dielectric, demonstrating negligible hysteresis in transport characteristics. (18) Heterostructures with 2D materials have been used for memory applications and tunnel transistors. Gr/MoSheterostructures have been used for nonvolatile memory cells. (19) Tunnel transistors fabricated with Gr/hexagonal-BN (h-BN)/Gr and Gr/MoS/Gr open the prospect of obtaining steep transistors with such an architecture. (20) Vertical Gr/h-BN/Gr heterostacks have also exhibited negative differential resistance, allowing the prospect of vdW heterostructures in analog electronics. (21) Gr/WS/Gr heterostructures have demonstrated strong light-matter interactions, leading to enhanced photon absorption and electron–hole creation. (22) This has opened the possibility of flexible photovoltaic devices with layered 2D materials. Heterobilayers of WSeand MoShave shown strong interlayer coupling with spatially direct absorption and spatially indirect emission, exhibiting yet another unique property of TMDC heterostructures. TMDC heterojunctions with III–V, Si, and carbon nanotubes have also been explored previously, demonstrating electrically active vdW interfaces built from highly dissimilar semiconductors. (23-26) However, a transistor made completely from two-dimensional materials to leverage the absence of interface states with digitally controlled and atomically uniform thickness has not been reported so far. In this work, we use large area chemical vapor deposited (CVD) Gr to contact few-layer MoScrystals. We use exfoliated hexagonal boron nitride as the layered gate dielectric and exfoliated Gr as the top-gate contact. The resulting field-effect transistor (FET) made completely of layered materials exhibits a high ON/OFF current ratio of >10, with a MoSelectron mobility of 33 cm/V·s. We also demonstrate the rectification behavior of an all-2D diode, using MoS–WSeheterojunction contacted with Gr as the source/drain electrodes.
Results and Discussion
2 back-gated FETs (I D -V G and I D –V D characteristics of a representative MoS 2 transistor with Gr S/D contacts. Here the p+Si/SiO 2 (260 nm) substrate is used as the back gate. The channel length, L, and width, W, are ∼7 μm and ∼25 μm, respectively. This MoS 2 transistor with vdW Gr contacts exhibits clear n-type characteristic with ON/OFF current ratio of ∼106. Notably, the low V DS regime of the output characteristics ( 2 for electron injection. This observation is similar to those previously reported for MoS 2 devices with elemental metal contacts, where the FETs exhibited n-type characteristics. We have also characterized Gr contacted WSe 2 multilayer devices. In contrast to MoS 2 devices, Gr contacted WSe 2 FETs exhibit a p-type characteristic with nonlinear I D –V D curves arising from a large Schottky barrier (SB) height to the valence band of WSe 2 at the Gr interface ( 2 , but not high enough to form an ohmic contact to holes in WSe 2 . Given the ability to chemically dope Gr, 2 and WSe 2 . This presents potentially a unique feature of Gr contacts over elemental metals. We first examine the properties of Gr contacted MoSback-gated FETs ( Figure 2 a). Figure 2 b,c shows theandcharacteristics of a representative MoStransistor with Gr S/D contacts. Here the pSi/SiO(260 nm) substrate is used as the back gate. The channel length,, and width,, are ∼7 μm and ∼25 μm, respectively. This MoStransistor with vdW Gr contacts exhibits clear n-type characteristic with ON/OFF current ratio of ∼10. Notably, the lowregime of the output characteristics ( Figure 2 b) is linear without an inflection point. This result suggests that Gr provides efficient contacts to the conduction band of MoSfor electron injection. This observation is similar to those previously reported for MoSdevices with elemental metal contacts, where the FETs exhibited n-type characteristics. We have also characterized Gr contacted WSemultilayer devices. In contrast to MoSdevices, Gr contacted WSeFETs exhibit a p-type characteristic with nonlinearcurves arising from a large Schottky barrier (SB) height to the valence band of WSeat the Gr interface ( Supporting Information , Figure S1). The results suggest that the workfunction of Gr, which is ∼4.5 eV based on literature, (29) is low enough for contacting electrons in MoS, but not high enough to form an ohmic contact to holes in WSe. Given the ability to chemically dope Gr, (30) in the future, it should be possible to explore Gr with tuned work function to further improve the contact resistances to both MoSand WSe. This presents potentially a unique feature of Gr contacts over elemental metals.
Figure 2. Back-gated few-layer MoS 2 FET with monolayer graphene contacts. The p+ Si substrate is used as the back-gate. (a) Device schematic (not to scale). (b) I D –V G curves at different V D . (c) I D –V D characteristics.
2 flake (thickness, ∼10 nm) is contacted by bilayer Gr S/D, with h-BN (thickness, ∼55 nm) as the top-gate dielectric and multilayer Gr (thickness, ∼10 nm) as the top-gate electrode (6 (the OFF current being limited by the noise level of the system). Next we fabricated an all-2D transistor, where a MoSflake (thickness, ∼10 nm) is contacted by bilayer Gr S/D, with h-BN (thickness, ∼55 nm) as the top-gate dielectric and multilayer Gr (thickness, ∼10 nm) as the top-gate electrode ( Figure 3 a). In this system, all interfaces are based on vdW bonding, presenting a unique device architecture where crystalline, layered materials are stacked on demand, without the lattice parameter constraints. The device has a channel length and width of ∼3 and 2.7 μm, respectively. Panels b and c of Figure 3 depict the transfer and output characteristics of this all 2-D FET, respectively. The device demonstrates clear n-type switching behavior, with ON/OFF current ratio of >10(the OFF current being limited by the noise level of the system).
Figure 3. All-2D MoS 2 FET with few-layer h-BN gate dielectric, and bilayer graphene source/drain and multilayer graphene top-gate electrodes. (a) Device schematic (not to scale). (b) I D –V G characteristics at different V D . (c) I D –V D characteristics. (d) Extracted mobility as a function of gate voltage, V G – V t . The inset shows the circuit model of the device used for mobility extraction. The substrate is grounded during all measurements.
R c , and the active channel, R CH . The drain current, I D can be expressed as I D = μC ox (W/L)(V G–i – V t )(V D–i ), where μ is the mobility, C ox is the capacitance of the gate oxide, W and L are the channel width and length, respectively, V t is the threshold voltage, and V G–i and V D–i are the intrinsic gate and drain voltages after subtracting the potential drops across the source and drain contact resistances. The channel resistance R CH can be then defined as R CH = V D–i /I D = L/(μC ox W(V G–i – V t )). The total resistance between the source and the drain is given by R total = R CH + 2R c = V D /I D = L/(μC ox W(V G–i – V t )) + 2R c . At high V G–i – V t , the channel resistance becomes negligible with the total resistance being dominated by the contacts. That is R total ≈ 2R c . From the measured transfer curves at high V G and V D = 0.05 V, we extract R c ∼ 15 kΩ (see I D can be expressed as μC ox (W/L)(V G – V t – I D R c )(V D – 2I D R c ). Assuming h-BN has a dielectric constant of 4, C ox is calculated to be ∼6.4 × 10–8 F/cm2. The extracted electron mobility for our all-2D device is subsequently calculated as a function of V G –V t as shown in 2/V·s which is consistent with the range of electron mobility values reported in the literature for MoS 2 FETs. FE using the expression μ FE = dI D /dV G (L/WC ox V DS ), at V DS = 0.05 V. In this method, the contact resistance is not corrected for, and the mobility is extracted to be 26 cm2/V·s, which is slightly lower than the value obtained when the contact resistance is corrected for. The contact resistance of TMDC devices is generally significant as compared to the channel resistance. Thus, in order to properly extract the device mobility, the contact resistances must be carefully taken into account. To extract the mobility of the all-2D FET, we used a model described as follows. The potential from the source to the drain is assumed to drop across three resistors in series, as shown in the inset of Figure 3 d: the source and drain contacts,, and the active channel,. The drain current,can be expressed as= μ)()(), where μ is the mobility,is the capacitance of the gate oxide,andare the channel width and length, respectively,is the threshold voltage, andandare the intrinsic gate and drain voltages after subtracting the potential drops across the source and drain contact resistances. The channel resistancecan be then defined as/(μ)). The total resistance between the source and the drain is given by+ 2/(μ)) + 2. At high, the channel resistance becomes negligible with the total resistance being dominated by the contacts. That is≈ 2. From the measured transfer curves at highand= 0.05 V, we extract∼ 15 kΩ (see Supporting Information for details).can be expressed as μ)()(– 2). Assuming h-BN has a dielectric constant of 4,is calculated to be ∼6.4 × 10F/cm. The extracted electron mobility for our all-2D device is subsequently calculated as a function ofas shown in Figure 3 d. The peak mobility is ∼33 cm/V·s which is consistent with the range of electron mobility values reported in the literature for MoSFETs. (8, 31) We also calculate the field-effect mobility μusing the expression μ= d/d), at= 0.05 V. In this method, the contact resistance is not corrected for, and the mobility is extracted to be 26 cm/V·s, which is slightly lower than the value obtained when the contact resistance is corrected for.
V G dependence of the ON-state device performance (e.g., speed), thus making the eventual circuit design based on the demonstrated device architecture more robust. In conventional Si MOSFETs, the mobility drastically decays at high gate fields as the carriers are moved closer to the device surface, thereby making them more susceptible to surface roughness scattering. 2 layers used, the charge centroid of carriers is expected to be near the middle of the MoS 2 thickness with minimal dependence on the gate fields. This was previously observed in ultrathin InAs and WSe 2 FETs. Notably, in distinct contrast to conventional Si MOSFETs, the mobility of the all-2D FET does not decrease at high gate fields, and remains rather constant ( Figure 3 d). This observation is highly desirable for FET operation since it reduces thedependence of the ON-state device performance (, speed), thus making the eventual circuit design based on the demonstrated device architecture more robust. In conventional Si MOSFETs, the mobility drastically decays at high gate fields as the carriers are moved closer to the device surface, thereby making them more susceptible to surface roughness scattering. (32) In contrast, in the all-2D FET, the impact of surface roughness scattering of carriers is expected to be less severe given the vdW nature of the bonds with atomically uniform thicknesses of the semiconductor channel and the gate dielectric. In addition, given the 2D nature of the thin MoSlayers used, the charge centroid of carriers is expected to be near the middle of the MoSthickness with minimal dependence on the gate fields. This was previously observed in ultrathin InAs and WSeFETs. (33, 9) These two effects contribute to the lack of gate dependence in mobility at high gate fields, and demonstrate an important advantage of the all-2D FET.
2 as the hole conducting layer, MoS 2 as the electron conducting layer, and Gr as the contacts ( 2 for electron injection, but a Schottky contact to the WSe 2 valence band for hole injection. Thus, a Gr/WSe 2 /MoS 2 /Gr heterostructure is composed of a Schottky diode between Gr and WSe 2 , and a heterojunction diode between WSe 2 and MoS 2 . The band alignment for a WSe 2 /MoS 2 heterobilayer was previously explored, showing a ∼100 meV offset in the conduction band edge of the two materials. 2 can cross the low barrier into WSe 2 and recombine with the holes that are injected from Gr into WSe 2 . I–V is determined by the MoS 2 /WSe 2 junction, and the parasitic resistances of the Schottky contacts and the MoS 2 and WSe 2 films. Under reverse bias, the applied voltage is dropped at the MoS 2 /WSe 2 junction and the current is limited by the thermally generated electrons and holes. The measured diode characteristic is shown in 5 times larger than the reverse bias current. The diode ideality factor is extracted to be 1.4. The low reverse bias current and the ideality factor suggest high interface quality between MoS 2 and WSe 2 with minimal interface recombination/generation of carriers. This diode presents yet another example of configuring different layered material components into a functional device through the multistep transfer process. Finally, we demonstrate an all-2D diode using WSeas the hole conducting layer, MoSas the electron conducting layer, and Gr as the contacts ( Figure 4 a). As noted before, Gr forms a low resistance contact to the conduction band of MoSfor electron injection, but a Schottky contact to the WSevalence band for hole injection. Thus, a Gr/WSe/MoS/Gr heterostructure is composed of a Schottky diode between Gr and WSe, and a heterojunction diode between WSeand MoS. The band alignment for a WSe/MoSheterobilayer was previously explored, showing a ∼100 meV offset in the conduction band edge of the two materials. (15) Assuming a similar band offset for the multilayer heterojunction explored here, a qualitative band diagram can be drawn as shown in Figure 4 b. Under forward bias, electrons from MoScan cross the low barrier into WSeand recombine with the holes that are injected from Gr into WSeis determined by the MoS/WSejunction, and the parasitic resistances of the Schottky contacts and the MoSand WSefilms. Under reverse bias, the applied voltage is dropped at the MoS/WSejunction and the current is limited by the thermally generated electrons and holes. The measured diode characteristic is shown in Figure 4 c. The device exhibits clear rectification behavior, with the forward bias current at 3 V being ∼10times larger than the reverse bias current. The diode ideality factor is extracted to be 1.4. The low reverse bias current and the ideality factor suggest high interface quality between MoSand WSewith minimal interface recombination/generation of carriers. This diode presents yet another example of configuring different layered material components into a functional device through the multistep transfer process. |
/*
* Wrap the REST call.
* TODO: Add logic later to handle HDFS HA related exception
* to failover with a retry for the HA HDFS scenario.
*/
static void
RestRequest(PxfOptions *options, ClientContext * client_context, char *rest_msg)
{
Assert(options->pxf_host != NULL && options->pxf_port > 0);
CallRest(options, client_context, rest_msg);
} |
<gh_stars>0
import os
import tempfile
import json
import pathlib
import pytest
import pandas
import eco
class TestPackager:
@pytest.fixture
def packager(self):
from eco.packager import Packager
return Packager()
def test_packager(self, packager):
assert packager._version == eco.__version__
@pytest.fixture
def empty_data(self):
return {'test_data': pandas.DataFrame()}
def test_build_package(self, packager, empty_data):
with tempfile.TemporaryDirectory() as pkg_dir:
packager.build_package(empty_data, pkg_dir=pkg_dir)
files = os.listdir(pkg_dir)
assert 'datapackage.json' in files
@staticmethod
def check_vals(vals, val_name, load_fn, pkg_dir):
with open(os.path.join(pkg_dir, 'datapackage.json')) as j:
data = json.load(j)
uuid = data['eco']['uuid']
read_vals = data['eco']['nodes'][uuid][val_name]
all_good = True
if val_name in ('metadata',):
vals, read_vals = [vals], [read_vals]
for val, read_val in zip(vals, read_vals):
if isinstance(val, pathlib.Path):
with open(val) as i:
read_valf = load_fn(i)
if not read_val == read_valf:
all_good = False
elif not val == read_val:
all_good = False
assert all_good, "Read view does not match original content"
@pytest.mark.parametrize("annotations",
[
['annotation 1'],
['annotation 1', 'annotation 2'],
[pathlib.Path('annot/fetch_data/overview.md')]
])
def test_build_package_annotations(self, packager, empty_data, annotations):
with tempfile.TemporaryDirectory() as pkg_dir:
packager.build_package(empty_data, annotations=annotations, pkg_dir=pkg_dir)
self.check_vals(annotations, 'annot', lambda i: i.read(), pkg_dir)
@pytest.mark.parametrize("views",
[
[{'test': 'view'}],
[pathlib.Path('views/fetch_data/scatterplot.json')],
])
def test_build_package_views(self, packager, empty_data, views):
with tempfile.TemporaryDirectory() as pkg_dir:
packager.build_package(empty_data, views=views, pkg_dir=pkg_dir)
self.check_vals(views, 'views', json.load, pkg_dir)
@pytest.mark.parametrize("metadata",
[
{'test': [1,2,3]},
pathlib.Path('metadata/test_metadata.json'),
])
def test_build_package_nodemetadata(self, packager, empty_data, metadata):
with tempfile.TemporaryDirectory() as pkg_dir:
packager.build_package(empty_data, metadata=metadata, pkg_dir=pkg_dir)
self.check_vals(metadata, 'metadata', json.load, pkg_dir)
@pytest.mark.parametrize("metadata",
[
{'test': [1,2,3]},
])
def test_build_package_pkgmetadata(self, packager, empty_data, metadata):
with tempfile.TemporaryDirectory() as pkg_dir:
packager.build_package(empty_data, pkg_dir=pkg_dir, **metadata)
with open(os.path.join(pkg_dir, 'datapackage.json')) as j:
data = json.load(j)
read_metadata = {key: data['eco'][key] for key in metadata.keys()}
assert read_metadata == metadata
|
May the Blessed Virgin Mary, through her intercession, inspire fraternity in all those who venerate her, so that they may be reunited, in God’s own time, in the peace and harmony of the one people of God, for the glory of the Most Holy and indivisible Trinity!
Joint Declaration
of Pope Francis
and Patriarch Kirill of Moscow and All Russia
“The grace of the Lord Jesus Christ and the love of God the Father and the fellowship of the holy Spirit be with all of you” (2 Cor 13:13).
1. By God the Father’s will, from which all gifts come, in the name of our Lord Jesus Christ, and with the help of the Holy Spirit Consolator, we, Pope Francis and Kirill, Patriarch of Moscow and All Russia, have met today in Havana. We give thanks to God, glorified in the Trinity, for this meeting, the first in history.
It is with joy that we have met like brothers in the Christian faith who encounter one another “to speak face to face” (2Jn12), from heart to heart, to discuss the mutual relations between the Churches, the crucial problems of our faithful, and the outlook for the progress of human civilization.
2. Our fraternal meeting has taken place in Cuba, at the crossroads of North and South, East and West. It is from this island, the symbol of the hopes of the “New World” and the dramatic events of the history of the twentieth century, that we address our words to all the peoples of Latin America and of the other continents.
It is a source of joy that the Christian faith is growing here in a dynamic way. The powerful religious potential of Latin America, its centuries–old Christian tradition, grounded in the personal experience of millions of people, are the pledge of a great future for this region.
3. By meeting far from the longstanding disputes of the “Old World”, we experience with a particular sense of urgency the need for the shared labour of Catholics and Orthodox, who are called, with gentleness and respect, to give an explanation to the world of the hope in us (cf.1Pet3:15).
4. We thank God for the gifts received from the coming into the world of His only Son. We share the same spiritual Tradition of the first millennium of Christianity. The witnesses of this Tradition are the Most Holy Mother of God, the Virgin Mary, and the saints we venerate. Among them are innumerable martyrs who have given witness to their faithfulness to Christ and have become the “seed of Christians”.
5. Notwithstanding this shared Tradition of the first ten centuries, for nearly one thousand years Catholics and Orthodox have been deprived of communion in the Eucharist. We have been divided by wounds caused by old and recent conflicts, by differences inherited from our ancestors, in the understanding and expression of our faith in God, one in three Persons – Father, Son and Holy Spirit. We are pained by the loss of unity, the outcome of human weakness and of sin, which has occurred despite the priestly prayer of Christ the Saviour: “So that they may all be one, as you, Father, are in me and I in you … so that they may be one, as we are one” (Jn17:21).
6. Mindful of the permanence of many obstacles, it is our hope that our meeting may contribute to the re–establishment of this unity willed by God, for which Christ prayed. May our meeting inspire Christians throughout the world to pray to the Lord with renewed fervour for the full unity of all His disciples. In a world which yearns not only for our words but also for tangible gestures, may this meeting be a sign of hope for all people of goodwill!
7. In our determination to undertake all that is necessary to overcome the historical divergences we have inherited, we wish to combine our efforts to give witness to the Gospel of Christ and to the shared heritage of the Church of the first millennium, responding together to the challenges of the contemporary world. Orthodox and Catholics must learn to give unanimously witness in those spheres in which this is possible and necessary. Human civilization has entered into a period of epochal change. Our Christian conscience and our pastoral responsibility compel us not to remain passive in the face of challenges requiring a shared response.
8. Our gaze must firstly turn to those regions of the world where Christians are victims of persecution. In many countries of the Middle East and North Africa whole families, villages and cities of our brothers and sisters in Christ are being completely exterminated. Their churches are being barbarously ravaged and looted, their sacred objects profaned, their monuments destroyed. It is with pain that we call to mind the situation in Syria, Iraq and other countries of the Middle East, and the massive exodus of Christians from the land in which our faith was first disseminated and in which they have lived since the time of the Apostles, together with other religious communities.
9. We call upon the international community to act urgently in order to prevent the further expulsion of Christians from the Middle East. In raising our voice in defence of persecuted Christians, we wish to express our compassion for the suffering experienced by the faithful of other religious traditions who have also become victims of civil war, chaos and terrorist violence.
10. Thousands of victims have already been claimed in the violence in Syria and Iraq, which has left many other millions without a home or means of sustenance. We urge the international community to seek an end to the violence and terrorism and, at the same time, to contribute through dialogue to a swift return to civil peace. Large–scale humanitarian aid must be assured to the afflicted populations and to the many refugees seeking safety in neighbouring lands.
We call upon all those whose influence can be brought to bear upon the destiny of those kidnapped, including the Metropolitans of Aleppo, Paul and John Ibrahim, who were taken in April 2013, to make every effort to ensure their prompt liberation.
11. We lift our prayers to Christ, the Saviour of the world, asking for the return of peace in the Middle East, “the fruit of justice” (Is32:17), so that fraternal co–existence among the various populations, Churches and religions may be strengthened, enabling refugees to return to their homes, wounds to be healed, and the souls of the slain innocent to rest in peace.
We address, in a fervent appeal, all the parts that may be involved in the conflicts to demonstrate good will and to take part in the negotiating table. At the same time, the international community must undertake every possible effort to end terrorism through common, joint and coordinated action. We call on all the countries involved in the struggle against terrorism to responsible and prudent action. We exhort all Christians and all believers of God to pray fervently to the providential Creator of the world to protect His creation from destruction and not permit a new world war. In order to ensure a solid and enduring peace, specific efforts must be undertaken to rediscover the common values uniting us, based on the Gospel of our Lord Jesus Christ.
12. We bow before the martyrdom of those who, at the cost of their own lives, have given witness to the truth of the Gospel, preferring death to the denial of Christ. We believe that these martyrs of our times, who belong to various Churches but who are united by their shared suffering, are a pledge of the unity of Christians. It is to you who suffer for Christ’s sake that the word of the Apostle is directed: “Beloved … rejoice to the extent that you share in the sufferings of Christ, so that when his glory is revealed you may also rejoice exultantly” (1Pet4:12–13).
13. Interreligious dialogue is indispensable in our disturbing times. Differences in the understanding of religious truths must not impede people of different faiths to live in peace and harmony. In our current context, religious leaders have the particular responsibility to educate their faithful in a spirit which is respectful of the convictions of those belonging to other religious traditions. Attempts to justify criminal acts with religious slogans are altogether unacceptable. No crime may be committed in God’s name, “since God is not the God of disorder but of peace” (1Cor14:33).
14. In affirming the foremost value of religious freedom, we give thanks to God for the current unprecedented renewal of the Christian faith in Russia, as well as in many other countries of Eastern Europe, formerly dominated for decades by atheist regimes. Today, the chains of militant atheism have been broken and in many places Christians can now freely confess their faith. Thousands of new churches have been built over the last quarter of a century, as well as hundreds of monasteries and theological institutions. Christian communities undertake notable works in the fields of charitable aid and social development, providing diversified forms of assistance to the needy. Orthodox and Catholics often work side by side. Giving witness to the values of the Gospel they attest to the existence of the shared spiritual foundations of human co–existence.
15. At the same time, we are concerned about the situation in many countries in which Christians are increasingly confronted by restrictions to religious freedom, to the right to witness to one’s convictions and to live in conformity with them. In particular, we observe that the transformation of some countries into secularized societies, estranged from all reference to God and to His truth, constitutes a grave threat to religious freedom. It is a source of concern for us that there is a current curtailment of the rights of Christians, if not their outright discrimination, when certain political forces, guided by an often very aggressive secularist ideology, seek to relegate them to the margins of public life.
16. The process of European integration, which began after centuries of blood–soaked conflicts, was welcomed by many with hope, as a guarantee of peace and security. Nonetheless, we invite vigilance against an integration that is devoid of respect for religious identities. While remaining open to the contribution of other religions to our civilization, it is our conviction that Europe must remain faithful to its Christian roots. We call upon Christians of Eastern and Western Europe to unite in their shared witness to Christ and the Gospel, so that Europe may preserve its soul, shaped by two thousand years of Christian tradition.
17. Our gaze is also directed to those facing serious difficulties, who live in extreme need and poverty while the material wealth of humanity increases. We cannot remain indifferent to the destinies of millions of migrants and refugees knocking on the doors of wealthy nations. The unrelenting consumerism of some more developed countries is gradually depleting the resources of our planet. The growing inequality in the distribution of material goods increases the feeling of the injustice of the international order that has emerged.
18. The Christian churches are called to defend the demands of justice, the respect for peoples’ traditions, and an authentic solidarity towards all those who suffer. We Christians cannot forget that “God chose the foolish of the world to shame the wise, and God chose the lowly and despised of the world, those who count for nothing, to reduce to nothing those who are something, that no human being might boast before God” (1Cor1:27–29).
19. The family is the natural centre of human life and society. We are concerned about the crisis in the family in many countries. Orthodox and Catholics share the same conception of the family, and are called to witness that it is a path of holiness, testifying to the faithfulness of the spouses in their mutual interaction, to their openness to the procreation and rearing of their children, to solidarity between the generations and to respect for the weakest.
20. The family is based on marriage, an act of freely given and faithful love between a man and a woman. It is love that seals their union and teaches them to accept one another as a gift. Marriage is a school of love and faithfulness. We regret that other forms of cohabitation have been placed on the same level as this union, while the concept, consecrated in the biblical tradition, of paternity and maternity as the distinct vocation of man and woman in marriage is being banished from the public conscience.
21. We call on all to respect the inalienable right to life. Millions are denied the very right to be born into the world. The blood of the unborn cries out to God (cf.Gen4:10).
The emergence of so-called euthanasia leads elderly people and the disabled begin to feel that they are a burden on their families and on society in general.
We are also concerned about the development of biomedical reproduction technology, as the manipulation of human life represents an attack on the foundations of human existence, created in the image of God. We believe that it is our duty to recall the immutability of Christian moral principles, based on respect for the dignity of the individual called into being according to the Creator’s plan.
22. Today, in a particular way, we address young Christians. You, young people, have the task of not hiding your talent in the ground (cf. Mt25:25), but of using all the abilities God has given you to confirm Christ’s truth in the world, incarnating in your own lives the evangelical commandments of the love of God and of one’s neighbour. Do not be afraid of going against the current, defending God’s truth, to which contemporary secular norms are often far from conforming.
23. God loves each of you and expects you to be His disciples and apostles. Be the light of the world so that those around you may see your good deeds and glorify your heavenly Father (cf. Mt5:14,16). Raise your children in the Christian faith, transmitting to them the pearl of great price that is the faith (cf. Mt13:46) you have received from your parents and forbears. Remember that “you have been purchased at a great price” (1Cor6:20), at the cost of the death on the cross of the Man–God Jesus Christ.
24. Orthodox and Catholics are united not only by the shared Tradition of the Church of the first millennium, but also by the mission to preach the Gospel of Christ in the world today. This mission entails mutual respect for members of the Christian communities and excludes any form of proselytism.
We are not competitors but brothers, and this concept must guide all our mutual actions as well as those directed to the outside world. We urge Catholics and Orthodox in all countries to learn to live together in peace and love, and to be “in harmony with one another” (Rm15:5). Consequently, it cannot be accepted that disloyal means be used to incite believers to pass from one Church to another, denying them their religious freedom and their traditions. We are called upon to put into practice the precept of the apostle Paul: “Thus I aspire to proclaim the gospel not where Christ has already been named, so that I do not build on another’s foundation” (Rm15:20).
25. It is our hope that our meeting may also contribute to reconciliation wherever tensions exist between Greek Catholics and Orthodox. It is today clear that the past method of “uniatism”, understood as the union of one community to the other, separating it from its Church, is not the way to re–establish unity. Nonetheless, the ecclesial communities which emerged in these historical circumstances have the right to exist and to undertake all that is necessary to meet the spiritual needs of their faithful, while seeking to live in peace with their neighbours. Orthodox and Greek Catholics are in need of reconciliation and of mutually acceptable forms of co–existence.
26. We deplore the hostility in Ukraine that has already caused many victims, inflicted innumerable wounds on peaceful inhabitants and thrown society into a deep economic and humanitarian crisis. We invite all the parts involved in the conflict to prudence, to social solidarity and to action aimed at constructing peace. We invite our Churches in Ukraine to work towards social harmony, to refrain from taking part in the confrontation, and to not support any further development of the conflict.
27. It is our hope that the schism between the Orthodox faithful in Ukraine may be overcome through existing canonical norms, that all the Orthodox Christians of Ukraine may live in peace and harmony, and that the Catholic communities in the country may contribute to this, in such a way that our Christian brotherhood may become increasingly evident.
28. In the contemporary world, which is both multiform yet united by a shared destiny, Catholics and Orthodox are called to work together fraternally in proclaiming the Good News of salvation, to testify together to the moral dignity and authentic freedom of the person, “so that the world may believe” (Jn17:21). This world, in which the spiritual pillars of human existence are progressively disappearing, awaits from us a compelling Christian witness in all spheres of personal and social life. Much of the future of humanity will depend on our capacity to give shared witness to the Spirit of truth in these difficult times.
29. May our bold witness to God’s truth and to the Good News of salvation be sustained by the Man–God Jesus Christ, our Lord and Saviour, who strengthens us with the unfailing promise: “Do not be afraid any longer, little flock, for your Father is pleased to give you the kingdom” (Lk12:32)!
Christ is the well–spring of joy and hope. Faith in Him transfigures human life, fills it with meaning. This is the conviction borne of the experience of all those to whom Peter refers in his words: “Once you were ‘no people’ but now you are God’s people; you ‘had not received mercy’ but now you have received mercy” (1Pet2:10).
30. With grace–filled gratitude for the gift of mutual understanding manifested during our meeting, let us with hope turn to the Most Holy Mother of God, invoking her with the words of this ancient prayer: “We seek refuge under the protection of your mercy, Holy Mother of God”. May the Blessed Virgin Mary, through her intercession, inspire fraternity in all those who venerate her, so that they may be reunited, in God’s own time, in the peace and harmony of the one people of God, for the glory of the Most Holy and indivisible Trinity!
Francis
Bishop of Rome
Pope of the Catholic Church Kirill
Patriarch of Moscow
and all Russia
12 February 2016, Havana (Cuba)
[Original text: Italian – Russian]
© Copyright – Libreria Editrice Vaticana |
def dots2mm( self, point ):
return Point( self.dots2mm_X(point.x), self.dots2mm_Y(point.y) ) |
// LikePhoto takes in a context and photo id, returns abbreviated versions of the picture and user.
// Likes a photo on behalf of the logged-in user. This requires the `write_likes` scope.
// https://unsplash.com/documentation#like-a-photo
func (c *Client) LikePhoto(ctx context.Context, photoID string) (*LikeResponse, error) {
if !isClientPrivate(c) {
return nil, ErrClientNotPrivate
}
if ok := c.AuthScopes.Contains(WriteLikesScope); !ok {
return nil, ErrRequiredScopeAbsent(WriteLikesScope)
}
endPoint := AllPhotosEndpoint + photoID + "/like"
resp, err := c.postHTTP(ctx, endPoint, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var lr LikeResponse
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = parseJSON(data, &lr)
if err != nil {
return nil, err
}
return &lr, nil
} |
<reponame>ostdotcom/ost-wallet-sdk-android<filename>ostsdk/src/main/java/com/ost/walletsdk/ui/util/CommonUtils.java<gh_stars>10-100
/*
* Copyright 2019 OST.com Inc
*
* 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
*/
package com.ost.walletsdk.ui.util;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.provider.Settings;
import com.ost.walletsdk.annotations.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.ost.walletsdk.OstConstants;
import com.ost.walletsdk.OstSdk;
import com.ost.walletsdk.models.entities.OstToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.web3j.crypto.Keys;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static com.ost.walletsdk.OstSdk.getContext;
public class CommonUtils {
private static final String LOG_TAG = "OstCommonUtils";
private static final String DATA = "data";
public CommonUtils() {
}
public JSONArray listToJSONArray(List<String> list) {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < list.size(); i++) {
jsonArray.put(list.get(i));
}
return jsonArray;
}
public List<String> jsonArrayToList(JSONArray jsonArray) {
List<String> list = new ArrayList<>();
try {
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getString(i));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "jsonArray to list exception", e);
}
return list;
}
public List<String> toCheckSumAddresses(List<String> addressList) {
for (int i = 0; i < addressList.size(); i++) {
String address = Keys.toChecksumAddress(addressList.get(i));
addressList.set(i, address);
}
return addressList;
}
private static final byte[] nonSecret = ("LETS_CLEAR_BYTES" + String.valueOf((int) (System.currentTimeMillis()))).getBytes();
public static void clearBytes(byte[] secret) {
if (null == secret) {
return;
}
for (int i = 0; i < secret.length; i++) {
secret[i] = nonSecret[i % nonSecret.length];
}
}
public String parseStringResponseForKey(JSONObject jsonObject, String key) {
try {
JSONObject resultType = (JSONObject) parseResponseForResultType(jsonObject);
return resultType.getString(key);
} catch (JSONException e) {
Log.e(LOG_TAG, "JSON Exception");
}
return null;
}
public boolean isValidResponse(JSONObject jsonObject) {
try {
if (jsonObject.getBoolean(OstConstants.RESPONSE_SUCCESS)) {
return true;
}
} catch (JSONException e) {
Log.e(LOG_TAG, "JSON Exception");
}
return false;
}
public Object parseResponseForResultType(JSONObject jsonObject) throws JSONException {
if (!isValidResponse(jsonObject)) {
Log.e(LOG_TAG, "JSON response false");
return null;
}
JSONObject jsonData = jsonObject.getJSONObject(OstConstants.RESPONSE_DATA);
return jsonData.get(jsonData.getString(OstConstants.RESULT_TYPE));
}
public Object parseObjectResponseForKey(JSONObject jsonObject, String key) {
try {
JSONObject resultType = (JSONObject) parseResponseForResultType(jsonObject);
return resultType.get(key);
} catch (JSONException e) {
Log.e(LOG_TAG, "JSON Exception");
}
return null;
}
public JSONObject parseJSONData(JSONObject jsonObject) {
try {
return jsonObject.getJSONObject(DATA);
} catch (JSONException e) {
return null;
}
}
public JSONObject deepMergeJSONObject(JSONObject firstObject, JSONObject secondObject) {
JSONObject mergedObj = null;
try {
mergedObj = new JSONObject(firstObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Iterator secondIterator = secondObject.keys();
String tmp_key;
try {
while (secondIterator.hasNext()) {
tmp_key = (String) secondIterator.next();
if (secondObject.get(tmp_key) instanceof JSONObject) {
if (mergedObj.has(tmp_key)) {
mergedObj.put(tmp_key, deepMergeJSONObject(mergedObj.getJSONObject(tmp_key), secondObject.getJSONObject(tmp_key)));
} else {
mergedObj.put(tmp_key, deepMergeJSONObject(new JSONObject(), secondObject.getJSONObject(tmp_key)));
}
} else {
mergedObj.put(tmp_key, secondObject.get(tmp_key));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return mergedObj;
}
public Map<String, Object> convertJsonToMap(JSONObject jsonObject) throws JSONException {
Map<String, Object> map = new HashMap<>();
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
map.put(key, convertJsonToMap((JSONObject) value));
} else if (value instanceof JSONArray) {
map.put(key, convertJsonToArray((JSONArray) value));
} else if (value instanceof Boolean) {
map.put(key, (Boolean) value);
} else if (value instanceof Integer) {
map.put(key, (Integer) value);
} else if (value instanceof Double) {
map.put(key, (Double) value);
} else if (value instanceof String) {
map.put(key, (String) value);
} else {
map.put(key, value.toString());
}
}
return map;
}
public List<Object> convertJsonToArray(JSONArray jsonArray) throws JSONException {
List<Object> array = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JSONObject) {
array.add(convertJsonToMap((JSONObject) value));
} else if (value instanceof JSONArray) {
array.add(convertJsonToArray((JSONArray) value));
} else if (value instanceof Boolean) {
array.add((Boolean) value);
} else if (value instanceof Integer) {
array.add((Integer) value);
} else if (value instanceof Double) {
array.add((Double) value);
} else if (value instanceof String) {
array.add((String) value);
} else {
array.add(value.toString());
}
}
return array;
}
public boolean isBioMetricEnrolled() {
return isBioMetric(false);
}
public boolean isBioMetricHardwareAvailable() {
return isBioMetric(true);
}
private boolean isBioMetric(boolean checkForHardware) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//Fingerprint API only available on from Android 6.0 (M)
FingerprintManager fingerprintManager = (FingerprintManager) getContext()
.getSystemService(Context.FINGERPRINT_SERVICE);
if (null != fingerprintManager) {
if (checkForHardware) {
return fingerprintManager.isHardwareDetected();
} else {
return fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints();
}
}
}
return false;
}
public void showEnableBiometricDialog(Activity currentActivity, DialogInterface.OnClickListener onCancelListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
builder.setCancelable(true);
builder.setMessage("No biometrics available on this device. Please enable via your device settings.");
builder.setTitle("Enable Biometric");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
currentActivity.startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
}
});
builder.setNegativeButton("Cancel", onCancelListener);
builder.create().show();
}
public String convertWeiToTokenCurrency(String userId, String balance) {
if (null == balance) return "0";
OstToken token = OstSdk.getToken(OstSdk.getUser(userId).getTokenId());
Integer decimals = Integer.parseInt(token.getBtDecimals());
BigDecimal btWeiMultiplier = new BigDecimal(10).pow(decimals);
BigDecimal bal = new BigDecimal(balance).divide(btWeiMultiplier, 10 , RoundingMode.HALF_UP);
return new DecimalFormat("#.#####").format(bal);
}
public String convertFiatWeiToFiat(String amount) {
if (null == amount) return "";
BigDecimal btWeiMultiplier = new BigDecimal(10).pow(18);
BigDecimal bal = new BigDecimal(amount).divide(btWeiMultiplier, 10, RoundingMode.HALF_UP);
return new DecimalFormat("#.##").format(bal);
}
public String convertFiatWeiToBt(String userId, String fiatInWei, JSONObject pricePointObject,@NonNull String currencySymbol) {
try{
OstToken token = OstSdk.getToken(OstSdk.getUser(userId).getTokenId());
Double pricePointOSTtoUSD = pricePointObject.getJSONObject(token.getBaseToken()).getDouble(currencySymbol);
BigDecimal weiMultiplier = new BigDecimal(10).pow(18);
BigDecimal usdWei = new BigDecimal(fiatInWei);
BigDecimal pricePointOSTtoUSDWei = new BigDecimal(String.valueOf(pricePointOSTtoUSD)).multiply(weiMultiplier);
BigDecimal baseCurrency = usdWei.divide(pricePointOSTtoUSDWei, 10, RoundingMode.HALF_UP);
BigDecimal bt = baseCurrency.multiply(new BigDecimal(token.getConversionFactor()));
return new DecimalFormat("#.#####").format(bt);
} catch (Exception e){
return null;
}
}
public String convertBTWeiToFiat(String userId, String balance, JSONObject pricePointObject, @NonNull String currencySymbol) {
if (null == balance || null == pricePointObject) return null;
try{
OstToken token = OstSdk.getToken(OstSdk.getUser(userId).getTokenId());
double pricePointOSTtoUSD = pricePointObject.getJSONObject(token.getBaseToken()).getDouble(currencySymbol);
int fiatDecimalExponent = pricePointObject.getJSONObject(token.getBaseToken()).getInt("decimals");
BigDecimal fiatToEthConversionFactor = new BigDecimal("10").pow(fiatDecimalExponent);
BigDecimal tokenToFiatMultiplier = calTokenToFiatMultiplier(pricePointOSTtoUSD, fiatDecimalExponent, token.getConversionFactor(), Integer.parseInt(token.getBtDecimals()));
BigDecimal fiatBalance = new BigDecimal(balance).multiply(tokenToFiatMultiplier);
BigDecimal fiatBalanceInEth = fiatBalance.divide(fiatToEthConversionFactor, 10, RoundingMode.HALF_UP);
return new DecimalFormat("#.##").format(fiatBalanceInEth);
} catch (Exception e){
return "0";
}
}
private BigDecimal calTokenToFiatMultiplier(
double oneOstToUsd,
int usdDecimalExponent,
String oneOstToBT,
int btDecimalExponent) {
// weiDecimal = OstToUsd * 10^decimalExponent
BigDecimal bigDecimal = new BigDecimal(String.valueOf(oneOstToUsd));
BigDecimal toWeiMultiplier = new BigDecimal(10).pow(usdDecimalExponent);
BigDecimal usdWeiDecimalNumerator = bigDecimal.multiply(toWeiMultiplier);
// toBtWeiMultiplier = 10^btDecimal
BigDecimal toBtWeiMultiplier = new BigDecimal(10).pow(btDecimalExponent);
// btInWeiNumerator = conversionFactorOstToPin * toBtWeiMultiplier
BigDecimal conversionFactorOstToBT = new BigDecimal(String.valueOf(oneOstToBT));
BigDecimal btInWeiDenominator = conversionFactorOstToBT.multiply(toBtWeiMultiplier);
int precision = btDecimalExponent - usdDecimalExponent;
if (precision < 1) precision = 2;
// multiplierForFiat = btInWeiNumerator / usdWeiDecimalDenominator
return usdWeiDecimalNumerator.divide(btInWeiDenominator, precision, RoundingMode.HALF_UP);
}
} |
<gh_stars>0
import CountryMaster from './country';
import StateMaster from './state';
import CityMaster from './city';
export { CountryMaster, StateMaster, CityMaster };
|
def _get_many(self, ids, _record_builder, chunk_size):
chunks = [ids[x:x+chunk_size] for x in range(0, len(ids), chunk_size)]
for chunk in chunks:
ids_found = 0
results = (self.session.query(schema.Record)
.filter(schema.Record.id.in_(chunk)))
for result in results:
ids_found += 1
yield _record_builder(json_input=_json_loads(result.raw))
if ids_found != len(chunk):
raise ValueError("No Record found with id in chunk %s" % chunk) |
/// Returns a unit vector in x direction.
///
/// ```
/// assert_eq!(lina::Vec2f::unit_x(), lina::vec2(1.0, 0.0));
/// ```
pub fn unit_x() -> Self
where
Self: HasX<Scalar = T>,
{
let mut out = Self::zero();
*out.x_mut() = T::one();
out
} |
<gh_stars>0
pub mod dmc;
pub mod noise_channel;
pub mod square_channel;
pub mod triangle_channel;
|
Like most offices, we are coffee-fueled here at DataHero. Thus, when I came across some data on coffee production, I had to look into it a little more. Contributing so far only to the demand on coffee production, researching coffee distribution yielded many new perspectives and considerations. Factors like weather (Brazil’s drought could drive up coffee prices in 2014), different regions, different types of beans, etc. all play important roles in driving supply, and thus price, in coffee. Read on to find some of the interesting trends we found in coffee production.
Thanks to coffee crops favoring rich soil, steady temperatures, and moderate sunshine and rain, it grows only between the Tropic of Cancer and the Tropic of Capricorn. You can see this quite clearly in the map below, which represents overall coffee production in bags by country between 1990 and 2012.
Notice that Brazil is the most significant coffee producer, and the growing region for coffee is relatively small, compared to its expansive reach in consumption.
To see trends in coffee growing by country, take a look at the percentage area graph of coffee production by country between 1990-2012.
Brazil is the major player here, accounting for roughly a third of all coffee production. Vietnam is working hard to carve out a piece of this market, which as the graph above indicates, has been quite successful so far. Vietnam aims to capitalize specifically on the new market in sustainability. There are strict guidelines each farm must follow to be certified as “sustainable”. Once the farms meet these guidelines, they can demand a higher price for their beans, and yield better harvests with more streamlined practices.
Among the sustainably-sourced coffee trend is the impetus for the new popularity in specialty roasts and high-quality brews. Not all coffee production is created equal. Arabica beans are the most highly sought after, as these are considered better quality than Robusta beans. Arabica beans are grown at higher altitudes and generally yield a smaller harvest than Robusta beans, but are said to have a softer, sweeter and less harsh taste. Below is a chart of coffee production in Arabica vs. Robusta beans. Many countries produce both, marked in grey below.
Specialty roasts and high-end coffee is a luxury that many Westerners treat themselves to. This is the foundation on which Starbucks has built its empire; luxury for the common man. You can very clearly see that Robusta production peaked in 1999, then saw a significant drop in 2000 and has remained fairly steady since then. Robusta coffee beans are largely used for instant coffees, and as specialty roasts become more desired in Western consumers’ minds, it’s easy to see why Robusta hovers quite low on the production chart.
If we look at coffee production prices by country, we see that the countries that produce the most coffee aren’t necessarily the ones charging the most per pound. You’ll see in the following chart average coffee price in US cents per pound, broken down by country.
Jamaica, Cuba and Mexico hold the top three slots for most expensive exporting countries. Whether this is due to one specific blend/producer (Jamaicain Blue Mountain, anyone?) or due to a special growing region, or some combination thereof is difficult to say.
Take a look at the change average price of one pound of coffee in US cents (2014 dollars) by coffee type.
Robustas, interestingly enough, seem to be gaining in popularity according to this chart (except for 2009), though they were not gaining in production according to the first chart. Non-Colombian milds also appear to be the most expensive type of coffee, which is what Jamaica, Cuba and Mexico, the most expensive production countries, all grow.
1994 was a particularly rough year for coffee prices, given that a Colombian drought and unrest in Rwanda led to significantly decreased production. 1997 was another year of high prices in coffee, though there is some debate about whether low coffee reserves or El Nino is more to blame for this price spike. There was also quite a dip in coffee prices in 1998; this could be more a result of the market coming back to normal after 1997. However, this dip in prices continued from 1998 all the way to 2002. We can see from the second chart in this post that coffee production increased quite a bit in 1998 and even more dramatically in 1999, driving the cost of coffee down. Vietnam also started to become a larger player in the international coffee market around this time, upsetting the market. The coffee industry appears to be back on track though, with an upward trend in prices since 2004.
Next we’ll be taking a look at the other side of the coffee industry; consumer demand. Subscribe to our blog to stay up to date on data stories like this one, plus data analysis tips. Create a free DataHero account and import the coffee production datasets to find your own insights.
Download the datasets |
package com.xw.exception;
import com.xw.ErrorCode;
public class CheckException extends BaseException {
private final int code;
public CheckException(ErrorCode apiErrorCode) {
super(apiErrorCode.getMessage());
this.code = apiErrorCode.getCode();
}
/**
* 用于一种code对英语多种语义的情况,需要加remark,最后的msg为apiErrorCodeEnum.getMessage()+":"+remark
*
* @param errorCode 错误码
* @param remark 补充remark
*/
public CheckException(ErrorCode errorCode, String remark) {
super(errorCode.getMessage() + ":" + remark);
this.code = errorCode.getCode();
}
/**
* 用于异常转译
*
* @param errorCode 错误码
* @param cause 下层异常栈
*/
public CheckException(ErrorCode errorCode, Throwable cause) {
super(errorCode.getMessage(), cause);
this.code = errorCode.getCode();
}
/**
* 用于异常转译切code对英语多种语义的情况,需要加remark,最后的msg为{@link #getMessage()}
* +":"+message
*
* @param errorCode 错误码
* @param cause 下层异常栈
* @param message 异常信息
*/
public CheckException(ErrorCode errorCode, Throwable cause, String message) {
super(errorCode.getMessage() + ":" + message, cause);
this.code = errorCode.getCode();
}
public int getCode() {
return code;
}
}
|
package site.wanjiahao.gulimall.order.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import site.wanjiahao.common.constant.OrderRabbitConstant;
import site.wanjiahao.common.constant.SeckillConstant;
import java.util.HashMap;
@Configuration
@Slf4j
public class MyRabbitMQConfig {
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
// 库存服务交换机
@Bean
public Exchange wareEventExchange() {
// topic交换机 String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
return new TopicExchange(OrderRabbitConstant.ORDER_EXCHANGE, true, false, null);
}
// 监听超时队列
@Bean
public Queue queue() {
return new Queue(OrderRabbitConstant.ORDER_RELEASE_ORDER_QUEUE, false, false, false);
}
// 库存服务延迟队列
@Bean
public Queue wareDelayORDERQueue() {
// String name, boolean durable, boolean exclusive, boolean autoDelete,
// @Nullable Map<String, Object> arguments
// map.put("x-message-ttl", 10000);//message在该队列queue的存活时间最大为10秒
// map.put("x-dead-letter-exchange", DELAY_EXCHANGE); //x-dead-letter-exchange参数是设置该队列的死信交换器(DLX)
// map.put("x-dead-letter-routing-key", DELAY_ROUTING_KEY);//x-dead-letter-routing-key参数是给这个DLX指定路由键
HashMap<String, Object> args = new HashMap<>();
args.put("x-message-ttl", OrderRabbitConstant.X_MESSAGE_TTL);
args.put("x-dead-letter-exchange", OrderRabbitConstant.X_DEAD_LETTER_EXCHANGE);
args.put("x-dead-letter-routing-key", OrderRabbitConstant.X_DEAD_LETTER_ROUTING_KEY);
return new Queue(OrderRabbitConstant.ORDER_DELAY_QUEUE, false, false, false, args);
}
// 创建绑定关系
@Bean
public Binding delayQueueBinding() {
// String destination, DestinationType destinationType, String exchange, String routingKey,
// @Nullable Map<String, Object> arguments
return new Binding(OrderRabbitConstant.ORDER_DELAY_QUEUE,
Binding.DestinationType.QUEUE,
OrderRabbitConstant.ORDER_EXCHANGE,
OrderRabbitConstant.ORDER_DELAY_QUEUE,
null);
}
@Bean
public Binding releaseQueueBinding() {
return new Binding(OrderRabbitConstant.ORDER_RELEASE_ORDER_QUEUE,
Binding.DestinationType.QUEUE,
OrderRabbitConstant.ORDER_EXCHANGE,
"order.release.#",
null);
}
// 秒杀服务 队列消锋
@Bean
public Queue seckillQueue() {
/*
* String name, boolean durable, boolean exclusive, boolean autoDelete,
@Nullable Map<String, Object> arguments
* */
return new Queue(SeckillConstant.SECKILL_QUEUE, true, false, false);
}
// 绑定关系
@Bean
public Binding seckillBinding() {
/*
* String destination, DestinationType destinationType, String exchange, String routingKey,
@Nullable Map<String, Object> arguments
* */
return new Binding(SeckillConstant.SECKILL_QUEUE,
Binding.DestinationType.QUEUE,
OrderRabbitConstant.ORDER_EXCHANGE,
SeckillConstant.SECKILL_QUEUE,
null);
}
}
|
// RemoveEdge removes the connection from this node to the destination node.
// Returns the cost of the edge that is removed. If the edge did not exist,
// RemoveEdge returns nil.
func (v *Vertex) RemoveEdge(dst *Vertex) Cost {
e := v.out[dst]
if e == nil {
return nil
}
delete(e.src.out, e.dst)
delete(e.dst.in, e.src)
return e.cost
} |
import AWS from "aws-sdk";
import * as firebaseAdmin from "firebase-admin";
import {
QuerySnapshot,
DocumentChange,
DocumentData
} from "@google-cloud/firestore";
import { singular as singularize } from "pluralize";
import "isomorphic-fetch";
import AWSAppSyncClient from "aws-appsync";
import { AUTH_TYPE } from "aws-appsync/lib/client";
import gql from "graphql-tag";
import * as mutations from "./graphql/mutations";
AWS.config.update({ region: process.env.AWS_REGION });
const ddb = new AWS.DynamoDB.DocumentClient();
const ssm = new AWS.SSM();
const cfn = new AWS.CloudFormation();
let appSync: any;
const capitalize = (x: string): string => x[0].toUpperCase() + x.substring(1);
const getStackOutput = async (StackName: string, key: string) => JSON.parse(
((await cfn.describeStacks({ StackName }).promise()).Stacks ?? [])
.map((stack) => (stack.Outputs ?? [])
.find((output) => output.OutputKey === key))
.filter((it) => it)
.shift()!
.OutputValue!);
const getAmplifyConfig = async () => getStackOutput(
`${process.env.FIREBASE_PROJECT_ID}-ApiStack`,
"AmplifyConfigOutput"
);
const initialize = async () => {
const { FIREBASE_PROJECT_ID } = process.env;
const params = {
Name: `/FirebaseMigrator/${FIREBASE_PROJECT_ID}/FirebaseServiceAccount`,
WithDecryption: true
};
const res = await ssm.getParameter(params).promise();
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(JSON.parse(res.Parameter!.Value!))
});
const amplifyConfig = await getAmplifyConfig();
appSync = await new AWSAppSyncClient({
disableOffline: true,
url: amplifyConfig.aws_appsync_graphqlEndpoint,
region: amplifyConfig.aws_appsync_region,
auth: {
type: AUTH_TYPE.AWS_IAM,
credentials: new AWS.ECSCredentials()
}
}).hydrated();
};
const triggerUpdateMutation = async (typename: string, docId: string) => {
const mutationName = `update${typename}`;
const mutation = (mutations as {[k: string]: string})[mutationName];
await appSync.mutate({
mutation: gql(mutation),
variables: {
input: {
key: docId
}
}
});
};
const itemByFirestoreDocumentId = async (docId: string) => {
const qParams = {
TableName: process.env.TABLE_NAME!,
IndexName: "firestoreDocumentId-firestoreUpdatedAt-index",
ExpressionAttributeNames: {"#docId": "__firestoreDocumentId"},
ExpressionAttributeValues: {":pk": docId},
KeyConditionExpression: "#docId = :pk",
Limit: 1
};
const res = await ddb.query(qParams).promise();
return res.Count === 0 ? {} : res.Items!.shift()!;
};
const onModified = async (
collection: string,
it: DocumentChange<DocumentData>
) => {
try {
const item = await itemByFirestoreDocumentId(it.doc.id);
const pParams = {
TableName: process.env.TABLE_NAME!,
Item: {
...item,
...it.doc.data(),
__firestoreUpdatedAt: it.doc.updateTime.toDate().toISOString()
}
};
await ddb.put(pParams).promise();
await triggerUpdateMutation(capitalize(singularize(collection)), it.doc.id);
console.log(`[${it.type}] ${collection}: ${it.doc.id}`);
} catch (err) {
console.error(err);
}
};
const listenToCollection = async (collection: string) => firebaseAdmin
.firestore()
.collection(collection)
.onSnapshot((snapshot: QuerySnapshot<DocumentData>) => snapshot
.docChanges()
.forEach(async (it: DocumentChange<DocumentData>) => {
switch (it.type) {
case "modified":
onModified(collection, it);
break;
}
}),
(err: Error) => console.error(err)
);
async function main() {
console.log("Firebase Listener Proxy");
process.on("SIGINT", () => process.exit());
await initialize();
const firestore = firebaseAdmin.firestore();
const collections = (await firestore.listCollections()).map((it) => it.id);
await Promise.all(collections.map(listenToCollection));
}
main().catch(console.error);
|
Correlation of (18F) FDG PET/CT Parameters with Haematological Parameters in Esophageal Cancers and the Effect of These Parameters on Survival
Objective: In the present study, we aimed to investigate the relationship between metabolic (SUVmax) and volume-based (18F)FDG PET/CT parameters (metabolic tumour volume (MTV) and total lesion glycolysis (TLG)) and haematological parameters (neutrophil, lymphocyte, platelet,mean platelet volume(MPV) , neutrophil-lymphocyte ratio (NLR) and platelet-lymphocyte ratio (TLR)) with survival, and whether haematological parameters are correlated with metabolic and volume-based PET parameters. Method: We included a total of 55 patients who underwent (18F)FDG PET/CT in our nuclear medicine clinic between January 2017 and December 2018 with a diagnosis of esophageal squamous cell carcinoma, had no distant metastasis, either had or did not have regional lymph node metastasis, whose imaging and laboratory data could be retrospectively accessed, who did not undergo an operation before imaging, did not receive chemo-radiotherapy. Results: In multivariate regression analysis, we found esophageal MTV (OR 2.6; 95% CI 1.04–6.57, p: 0.041) and esophageal TLG (OR 2.7; 95% CI 1.2–6.2, p: 0.022) values to be independent variables in terms of survival. While we observed a negative correlation between PLR and esophageal MTV and TLG (p values were respectively p: 0.021, p: 0.03), we observed a positive correlation between lymphocyte counts and esophageal MTV and TLG (p values were p: 0.004, p: 0.001, respectively). We detected a positive correlation between the size and SUVmax of lymph node metastasis, on the one hand, and both neutrophil counts and NLR on the other. Conclusion: We determined MTV and TLG values, which are volume-based metabolic PET parameters, to be independent prognostic factors for survival. MTV and TLG had a negative correlation with PLR and a positive correlation with lymphocyte counts.
INTRODUCTION
Esophageal cancer is the sixth-most prevalent cancer type, which is responsible for 5.8% of cancer deaths worldwide, and it is the thirdmost common malignancy in the gastrointestinal tract worldwide; it is more frequently fatal in males 1 .
Squamous cell carcinoma (SCC) and adenocarcinoma, which are the two most common histological types that make up more than 95% of all esophageal cancers, have quite different aetiologies. Alcohol use, smoking and their synergistic effects are the primary risk factors for SCC. SCC has been the dominant histological type in Asian countries, especially in the twentieth century 2,3 .
Patients with esophageal cancer often present with a locally advanced disease characterised by invasion into the surrounding structures or lymph node involvement 4 . Neo-adjuvant chemo-radiotherapy (CRT) and definitive CRT or radiotherapy treatment are among the important treatment strategies for locally advanced esophageal SCC. Despite recent advances in treatment methods, the prognosis for esophageal cancer is poor. Overall survival and local control rates are inadequate; the 2year survival rate may reach 30%-40% and the local recurrence rate may reach 50%. Identifying the pre-treatment prognostic factors for esophageal cancer can improve treatment strategies and aid in the classification of risk 5,6 . C-reactive proteins and cytokines, a systemic inflammatory response that plays a key role in tumour growth and shows an inflammatory response, and leukocytes, their subtypes and platelets, which are easy to apply in daily practice, have been identified as promising prognostic factors 7,8 .
Several markers in the blood-such as platelets, neutrophils, lymphocytes, neutrophil-tolymphocyte ratio (NLR), platelet-to-lymphocyte ratio (PLR) and mean platelet volume (MPV)can serve as prognostic factors for esophageal cancer, especially for the squamous type 9,10 .
Whole-body 18F-fluorodeoxyglucose ((18F) FDG) positron emission tomography/computed tomography (PET/CT) is used for pre-treatment staging of esophageal cancers, the evaluation of treatment response and both post-treatment regional recurrence and distant metastasis. In addition to the maximum standard uptake value (SUVmax), the most frequently used parameters in PET/CT, metabolic tumour volume (MTV) and total lesion glycolysis (TLG), which are volume-based metabolic PET parameters, reflect tumour load more accurately and are reportedly prognostic factors for many tumours, including esophageal cancer .
The present study aimed to investigate the relationship between volume-based PET/CT parameters (MTV, TLG, SUVmax) and haematological parameters (neutrophil, lymphocyte, platelet, MPV, NLR, and PLR) with survival and the correlation between haematological parameters and volumebased PET parameters.
METHODS
We included in our study a total of 55 patients who underwent PET/CT in our Nuclear Medicine Clinic between January 2017 and December 2018 with the diagnosis of esophagus SCC, had no distant metastasis, did or did not have regional lymph node metastasis in PET/CT, whose imaging and laboratory data could be accessed retrospectively, who were not operated on before imaging, did not receive chemoradiotherapy and had no history of steroid use, and whose simultaneous complete blood parameters could be accessed with (18F)FDG PET/CT. We calculated times from the PET/CT scan to death dates. We carried out the study under local good clinical practice guidelines and current laws and obtained approval from the ethics committee of our hospital for the use of patient data (approval no: 401/2019).
(18F) FDG PET/CT protocol
We asked all patients not to eat for at least 6 hours before undergoing scans and to stop intravenous (IV) glucose intake. We confirmed blood glucose values to be ≤140 mg/dl by the finger-stick method before FDG injection. One hour after the (18F)FDG injection of 3.5 MBq/kg-5.5 MBq/kg, we obtained the CT images (120 kV, 80 mAs/slice, 700 mm transaxial FOV, no gap, 64xo. 625 mm collimation, pitch 1.4, 0.5 s rotation time, 3.3 mm slice thickness, 512x512 matrix) from the vertex to the middle of the thigh in the supine position with the Discovery IQ 4 ring 20-cm axial FOV PET/CT device (GE Healthcare, Milwaukee, WI, USA); we then obtained the bedside PET (3D FOV 20 cm, ordered subset expectation-maximisation algorithm (OSEM) 5 iterations/12 subset, full width at half maximum (FWHM) 3 mm) images 2.5 minutes thereafter.
Evaluation of the images
All (18F)FDG PET/CT images were evaluated by two specialist in nuclear medicine with 10 years of experience, using the PET Volume Computerised Assisted Reporting (PET-VCAR, GE, USA) (GE Advantage Workstation software version AW 4.7) program.
We drew volumetric regions of interests manually from the esophageal primary lesion to include the lesion in all three planes and obtained automatic MTV, TLG (MTV X SUVmean) and SUVmax values by the device for each lesion using a 40% SUV threshold value ( Figure 1, Figure 2).
Statistical Analysis
We used the SPSS 25.0 (IBM Corporation, Armonk, New York, United States) program to analyse the variables, and evaluated the conformity of univariate data to normal distribution by the Shapiro-Wilk and Francia tests, and variance homogeneity, by the Levene test. We used the independent samples T-test with the bootstrap results, and the Mann-Whitney U test with the Monte Carlo simulation technique in the comparison of two independent groups according to quantitative data. We used the Pearson Chisquare test with exact results in the comparison of categorical variables and compared column ratios with each other and expressed them according to the Benjamini-Hochberg corrected p value results. We analysed and expressed the sensitivity and specificity ratios by the ROC (receiver operating curve) curve analysis for the relationship between the classification by the cut-off value calculated for the independent variables according to mortality and the actual classification. We used the odds ratio with a 95% confidence interval to show how many times those with a risk factor were compared with those without. We used the Kaplan-Meier (product-limit method)-Log Rank (Mantel-Cox) analysis to examine the effects of factors on mortality and lifespan. We used the Cox regression analysis to measure the effects of prognostic variables on life span according to the main factor, and the Pearson correlation and Kendall's tau-b tests to examine the correlations of variables with each other. While we expressed quantitative variables as mean ± SD (standard deviation) and median (minimum/maximum), we showed categorical variables as n (%) in the tables. We analysed variables at a confidence level of 95% and considered them to be significant when the p value was less than 0.05.
RESULTS
Of the patients we included in the study, 29 (52.7%) were male and 26 (47.3%) were female. The mean age of the patients was 58.0+12.2 (57-91). The median survival of the patients was 365 (49-981) days (Table 1). In the ROC curve analysis, we determined the sensitivity and the specificity to be 73% and 88.9%, respectively, for MTV (cut-off > 30.29 cm3) and 54% and 100%, respectively, for TLG (cut-off > 372, 7 g/ml.cm3) in predicting survivors and non-survivors; the area under the curve was found to be statistically significant in determining mortality (p values were p: 0.001, p < 0.001, respectively) ( Table 2). (Figure 3, Figure 4). When we compared parameters obtained from PET/CT and haematologic parameters, we detected a negative correlation between PLR and esophagus MTV and TLG (p values were p: 0.021, p: 0.003, respectively), while there was a positive correlation between lymphocyte and esophagus MTV and TLG (p values were p: 0.004, p: 0.001, respectively). We found a positive correlation between the size of lymph node metastasis and SUVmax value and both neutrophils and NLR (Table 5). We detected no statistically significant correlation between the haematologic parameters among those with and those without lymph node metastasis in PET/CT (Table 6).
DISCUSSION
The most important finding in our retrospective cohort is that esophageal MTV and TLG values are independent prognostic values for survival.
In the present study, we found no statistically significant difference between survivors and non-survivors in terms of age and gender, and neither were found as significant prognostic factors for survival.
Studies of prognosis in patients with esophageal cancer using (18F)FDG PET/CT frequently emphasised the SUVmax value and reported the SUVmax of the primary tumour to be significantly correlated with overall survival (OS), progression-free survival (PFS), local control and response to simultaneous CRT 15,16 . However, many studies reported that the SUVmax value was not a prognostic factor for OS and PFS 14, . In their study with simultaneous CRT in esophageal cancer, Song et al. reported that the SUVmax difference before and after treatment might show a pathological response, but the SUVmax value before treatment was not a prognostic value in showing the treatment response 20 . In the present study, we found that SUVmax median values of both the primary tumour and the lymph nodes not only did not show a statistically significant difference between survivors and non-survivors but also had no prognostic value for survival (p values were p: 0.223, p: 0.895, respectively). In addition, in this study, no statistically significant relationship was found between the SUVmax of the primary tumor and lymph node and the survival time in univariate analysis (p values were p: 0.391, p: 0,098, respectively).
Because it is a measurement based on a single pixel in the most active part of the tumour and does not fully reflect tumour heterogeneity except for solid tumours, the SUVmax value causes excessive simplification. Since MTV and TLG-which are volume-based PET parameters-reflect the total tumour volume, metabolic activity and heterogeneity in the tumour in three dimensions, they may potentially be more sensitive than the singlepixel approach 21,22 .
In their 151-patient study involving 146 squamous cancer cases, Hyun et al. found age, TNM stage, MTV and SUVmax as prognostic factors for survival in a univariant analysis (p < 0.001, p: 0.001 for MTV and SUVmax, respectively), whereas MTV and SUVmax values were not found as independent prognostic factors in the multivariant analysis, and the effect of MTV on survival was seen to be of greater prognostic power than the SUVmax value 14 .
In a recent study of 38 patients with locally advanced esophageal cancer, TLG was found to be a prognostic value for OS, while MTV and SUVmax values were not prognostic factors. OS was significantly shorter in patients with TLG values higher than 232.98 g/ml.cm3 (p: 0.003) 23 .
In their study investigating the prognostic values of MTV, TLG and SUVmax in patients with esophageal cancer who received definitive chemo-radiotherapy, Yıldırım et al. showed that for DFS and OS, MTV and TLG, regional lymph node metastasis and concomitant chemotherapy were major prognostic factors in patients with esophageal carcinoma. In addition, they reported that MTV and TLG were important in predicting nodal metastasis 24 .
In the study by Hyun et all., the N phase was found to be a significant prognostic factor for survival in univariate analyses, but not in multivariate analyses (p < 0.001, p: 0.1, respectively) 14 . Other studies report lymph node positivity as the strongest prognostic factor in cases undergoing an operation 25,26 . In a study in which Ogino et all. Compared the localization of lymph node metastases to disease-free survival and mean survival in patients with esophageal cancers; While they found regional abdominal and left gastric lymph node metastases related to OS and PFS, they could not find a relationship between cervical and thoracic lymph nodes and OS and PFS 27 . In the present study, lymph node positivity in PET/CT was significantly higher in nonsurvivors than in survivors. However, we established in univariate and multivariate analyses that the presence of lymph node metastasis was not a significant variable for survival. The reason for this may be that the lymph nodes are evaluated only positively and negatively and due to the low number of cases, the evaluation could not be made according to the lymph node localizations.
It is widely accepted that the inflammation response plays a critical role in tumour progression and can affect the survival results in cancer patients. Among inflammatory markers, high neutrophil, platelet and macrophage counts, low lymphocyte counts and high NLR, PLR and low lymphocyte-tomonocyte ratio were considered to be associated with an adverse prognosis in solid tumours 28 .
In a meta-analysis including 1540 patients, which evaluated the relationship between NLR and OS, a significantly worse OS (HR 1.40, 95% CI 1.08-1.81, P = 0.01) was found in patients with a high NLR before treatment than that in those with a low NLR. High NLR and PLR were both found to be significant markers for a deeper tumour invasion and lymph node metastasis. However, neither high NLR nor high PLR was significantly associated with tumour differentiation or vascular invasion 29 .
A recent meta-analysis demonstrated that a high NLR predicts negative survival in esophageal cancer, both in SCC and adenocarcinoma, and could, therefore, be a promising predictive factor 30 . In the present study, however, we found no statistical significance in the median and mean values of haematological parameters in survivors and non-survivors.
We also found that haematological parameters were not a prognostic factor for survival. In addition, we did not find any statistically significant relationship between haematological parameters and survival time in univariate analysis.
There are very few studies comparing volumebased PET parameters and haematological parameters in patients with esophageal cancer. In a study comparing PET parameters and haematological parameters in 52 patients with esophageal cancer, Sürücü et al. found a positive correlation between MTV and NLR, while they did not find any correlation between MTV and MPV and NLR, nor between SUVmax and NLR, MPV and PLR. In addition, they found no correlation in haematological parameters in patients with or without lymph node positivity. However, they did not use the TLG value in their study 31 . In the present study, we observed a negative correlation between PLR and esophagus MTV and TLG (p values were p: 0.021 and p: 0.03, respectively), and a positive correlation between lymphocyte and esophagus MTV and TLG (p values were p: 0.004 and p: 0.001, respectively). We found a positive correlation between the size and SUVmax value of lymph node metastasis and both neutrophils and NLR. We also found a low, negative and statistically significant correlation between the lymph node size and MPV.
Our study had some limitations. First, this study is retrospective, but most studies in the literature have also been designed retrospectively. Since patients did not have post-treatment PET/CT evaluations, PET parameters were evaluated as pre-therapeutic metabolic index in all patients, and PET parameters and haematological parameters were associated with OS.
CONCLUSION
We found MTV and TLG values-the volumebased metabolic PET parameters-to be independent prognostic factors for survival. Both esophagus and lymph node SUVmax values and haematological parameters had no effect on survival. While we observed a negative correlation between both MTV and TLG and PLR, there was a positive correlation between MTV and lymphocyte counts We found a positive correlation between lymph node size and SUVmax value and both neutrophils and NLR. We established volume-based PET parameters as the most valuable parameters in terms of survival.
Ethics Committee Approval:
We carried out the study under local good clinical practice guidelines and current laws and obtained approval from the ethics committee of our hospital for the use of patient data (approval no: 401/2019).
Declaration of Conflicting Interests:
The authors declare that they have no conflict of interest.
Financial Disclosure: No financial support was received. |
package issues.i1580;
import io.jooby.annotations.PUT;
import io.jooby.annotations.Path;
import io.jooby.annotations.PathParam;
@Path("/pets")
public class Controller1580 {
@PUT
@Path("/{id}")
public Data1580 updatePet(Data1580 body, @PathParam String id) { // -> leads to NPE
return body;
}
}
|
# -*- encoding: utf-8 -*-
try:
from django.core.urlresolvers import reverse
except ImportError:
from django.urls import reverse
from django.test import TestCase
from django.test.client import Client
class Test(TestCase):
def setUp(self):
pass
def test_raport_autorow(self):
c = Client()
res = c.get(reverse("bpp:raport_autorow_formularz"))
self.assertEquals(res.status_code, 200)
|
pub struct HttpResponse {
pub content_type: String,
pub content_length: usize,
pub body: String,
}
impl HttpResponse {
pub fn write_response(&self) -> String {
format!(
"HTTP/1.1 200 OK\r\n\
Content-Type: {}\r\n\
Content-Length: {}\r\n\
\r\n\
{}",
self.content_type,
self.content_length,
self.body,
)
}
}
|
def FindSuspects(dep_to_file_to_changelogs,
dep_to_file_to_stack_infos,
stack_deps, get_repository,
ignore_cls=None):
suspects = SuspectMap(ignore_cls)
for dep, file_to_stack_infos in dep_to_file_to_stack_infos.iteritems():
file_to_changelogs = dep_to_file_to_changelogs[dep]
for crashed_file_path, stack_infos in file_to_stack_infos.iteritems():
for touched_file_path, changelogs in file_to_changelogs.iteritems():
if not crash_util.IsSameFilePath(crashed_file_path, touched_file_path):
continue
repository = get_repository(stack_deps[dep].repo_url)
blame = repository.GetBlame(touched_file_path,
stack_deps[dep].revision)
suspects.GenerateSuspects(
touched_file_path, dep, stack_infos, changelogs, blame)
return suspects.values() |
name = 'automake'
version = '1.15'
authors = [
'GNU'
]
description = \
'''
Automake
'''
build_requires = [
'autoconf-2.69'
]
variants = [
['platform-osx', 'arch-x86_64']
]
tools = [
]
def commands():
env.PATH.append('{root}/bin')
if building:
env.ACLOCAL_PATH = '{root}/share'
uuid = 'repository.automake'
|
<reponame>macfire10/hospitalrun-frontend<gh_stars>0
import sortBy from 'lodash-es/sortBy'
import React, { useState } from 'react'
import { resources } from '@shared/config/i18n'
import useTranslator from '@shared/hooks/useTranslator'
import SelectWithLabelFormGroup, { Option } from './SelectWithLabelFormGroup'
import { useAppContext } from '@shared/wrappers/RemoteAppWrapper'
const LanguageSelector = () => {
const { i18n } = useAppContext();
const { t } = useTranslator()
const [selected, setSelected] = useState(i18n.language)
let languageOptions: Option[] = Object.keys(resources).map((abbr) => ({
label: resources[abbr].name,
value: abbr,
}))
languageOptions = sortBy(languageOptions, (o: any) => o.label)
const onChange = (value: string) => {
i18n.changeLanguage(value)
setSelected(value)
}
return (
<SelectWithLabelFormGroup
name="language"
label={t('settings.language.label')}
options={languageOptions}
defaultSelected={languageOptions.filter(({ value }) => value === selected)}
onChange={(values: any) => onChange(values[0])}
isEditable
/>
)
}
export default LanguageSelector
|
<filename>pkg/crypto/algorithm/rc4md5/rc4md5.go
package rc4md5
import (
"crypto/cipher"
"crypto/md5"
"crypto/rc4"
"github.com/golang/glog"
)
const (
rc4MD5KeyLen = 16
rc4MD5IVLen = 16
)
//AES implementation aes encrypt and decrypt
type RC4MD5 struct {
Name string
}
//NewAES is return a AES handler
func NewRC4MD5(typ string) (*RC4MD5, error) {
alg := &RC4MD5{
Name: typ,
}
return alg, nil
}
//NewStream create a new stream by key and iv
func (a *RC4MD5) NewStream(key, iv []byte, _ bool) (cipher.Stream, error) {
glog.V(5).Infoln("New Aes Stream")
h := md5.New()
h.Write(key)
h.Write(iv)
rc4key := h.Sum(nil)
return rc4.NewCipher(rc4key)
}
//GetIVLen return the iv len of this method
func (a *RC4MD5) GetIVLen() int {
return rc4MD5IVLen
}
func (a *RC4MD5) GetKeyLen() int {
return rc4MD5KeyLen
}
|
/**
* Utility methods used by the test class(es).
*
*/
public abstract class AbstractTest {
void waitForPass(long timeToWaitInSeconds, Runnable r) {
waitForPass(timeToWaitInSeconds, false, r);
}
void waitForPass(long timeToWaitInSeconds, boolean showExceptions, Runnable r) {
long expireTimeInNanos = System.nanoTime()
+ TimeUnit.NANOSECONDS.convert(timeToWaitInSeconds, TimeUnit.SECONDS);
Throwable lastThrowable = null;
int delay = 50;
while (System.nanoTime() < expireTimeInNanos) {
try {
r.run();
return;
} catch (Throwable t) {
if (showExceptions) {
t.printStackTrace();
}
lastThrowable = t;
GHApiUtil.sleep(delay);
delay *= 1.5;
if (delay >= 1000) {
delay = 1000;
}
}
}
if (lastThrowable instanceof RuntimeException) {
throw (RuntimeException) lastThrowable;
} else {
throw (Error) lastThrowable;
}
}
protected static ServerInstanceBuilder getClientBuilder() {
File f = new File(new File(System.getProperty("user.home"), ".githubapitests"), "test.properties");
Properties props = new Properties();
if (f.exists()) {
try {
props.load(new FileInputStream(f));
} catch (IOException e) {
e.printStackTrace();
}
}
String ghUsername = getProperty("github.username", props);
String ghPassword = getProperty("github.password", props);
ServerInstanceBuilder build = ServerInstance.builder();
build = build.credentials(ghUsername, ghPassword);
return build;
}
private static String getProperty(String property, Properties props) {
String apiKey = (String) props.getOrDefault(property, null);
if (apiKey == null) {
apiKey = System.getProperty(property);
}
if (apiKey == null) {
fail("Unable to find property '" + property + "'. Specify with -D" + property
+ "=(...value..), see com.githubapimirror.tests.AbstractTest for details.");
}
return apiKey;
}
} |
Obama has commuted the sentences of 348 federal inmates since he took office. (Pablo Martinez Monsivais/AP)
President Obama granted clemency to 42 inmates Friday as part of an ongoing effort to release federal prisoners who are serving prison terms resulting from sentencing laws that the White House said were “outdated and unduly harsh.”
To date, Obama has commuted the sentences of 348 federal inmates. The White House said in a statement that the president will continue commuting the sentences of inmates through his seven remaining months in office.
Half of the inmates on Friday’s list had been sentenced to life for nonviolent drug offenses, according to the White House.
Obama has granted more commutations than the previous seven presidents combined, according to White House officials.
“Despite these important efforts, only legislation can bring about lasting change to the federal system,” wrote Neil Eggleston, the White House counsel. “There remain thousands of men and women in federal prison serving sentences longer than necessary, often due to overly harsh mandatory minimum sentences.”
One federal inmate who was released — but not under Obama’s clemency initiative — is Weldon Angelos, 36, a father of three from Utah who was sentenced in 2004 to a 55-year mandatory minimum prison term in connection with selling marijuana.
The specific circumstances of Angelos’s release are unclear because court records in his case are sealed. But after a long campaign from his supporters, including Sen. Mike Lee (R-Utah), Angelos was quietly released Tuesday after a federal court granted him an immediate reduction in sentence. He was able to immediately go home to his family without serving three months in a halfway house, as those who receive clemency are required to do.
The release allowed Angelos to see the son he left at age 7 graduate from high school Thursday.
Angelos is one of the nation’s most famous nonviolent drug offenders and became a symbol of what advocates said was the severity and unfairness of mandatory sentences. His case was championed by the group Families Against Mandatory Minimums, former FBI director Bill Sessions, conservative billionaire Charles Koch and others. Three years ago, more than 100 former judges and prosecutors, former elected and appointed government officials, and prominent authors, scholars, activists and business leaders signed a letter urging Obama to grant Angelos commutation.
In February, former federal judge Paul G. Cassell, who sentenced Angelos, wrote a letter asking Obama to swiftly grant him clemency. Cassell said that the sentence he was forced to impose was “one of the most troubling that I ever faced in my five years on the federal bench” and that it was one of the chief reasons he stepped down as a judge.
But Obama never granted clemency to Angelos. The granting of mercy instead came from the Salt Lake City prosecutor who charged him in the case, according to his lawyer.
“After three and half years of inaction on Weldon’s clemency petition, he is free because of the fair and good action of a prosecutor,” attorney Mark W. Osler said. “He returns to citizenship because of the actions of one individual — just not the individual I was expecting. Weldon’s freedom is a wonderful thing but remains just one bright spot among many continuing tragedies.”
A White House spokeswoman said that the White House cannot respond with details about any individual clemency case.
Julie Stewart, president of Families Against Mandatory Minimums, called the release of Angelos “fantastic news and past due.”
According to the Justice Department, those whose sentences were commuted by Obama on Friday were:
Eric E. Alvarez, New York, N.Y.
Offense: Conspiracy to distribute and possess with the intent to distribute cocaine and cocaine base (crack); conspiracy to commit money laundering. Eastern District of North Carolina
Sentence: 360 months’ imprisonment; five years’ supervised release (April 18, 2000)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Dale Baldwin, Largo, Fla.
Offense: Conspiracy to possess with intent to distribute cocaine base; possession with intent to distribute cocaine base (three counts). Middle District of Florida
Sentence: Life imprisonment; 10 years’ supervised release (June 28, 1995)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Delaine F. Berg, Imboden, Ark.
Offense: Conspiracy to manufacture methamphetamine. Eastern District of Missouri
Sentence: 360 months’ imprisonment; five years’ supervised release (May 26, 1998)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Phillip Blackwood, Ridgewood, N.Y.
Offense: Conspiracy to distribute and possess with intent to distribute cocaine base; distribution and possession with intent to distribute a controlled substance. Eastern District of New York
Sentence: 240 months’ imprisonment; 10 years’ supervised release (Nov. 21, 2008)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Wilhemina Bryan, Orlando
Offense: Conspiracy to import five kilograms or more of cocaine; conspiracy to possess with intent to distribute at least five kilograms of cocaine; possession with intent to distribute cocaine. Middle District of Florida
Sentence: 360 months’ imprisonment; five years’ supervised release (May 21, 2001)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Charrell Franklin Burrage, Davenport, Iowa
Offense: Possession with intent to distribute; possession of firearm in furtherance of drug-trafficking. Southern District of Iowa
Sentence: 300 months’ imprisonment; 10 years’ supervised release (November 29, 2004)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Christopher Shawn Collier, Midland, Tex.
Offense: Conspiracy to possess with intent to distribute more than 50 grams of methamphetamine; possession with intent to distribute more than five grams of methamphetamine. Western District of Texas
Sentence: 360 months’ imprisonment; 10 years’ supervised release (May 10, 2002)
Commutation grant: Prison sentence commuted to expire June 3, 2018.
Richard Eugene Dains, Porter, Tex.
Offense: Did conspire to manufacture methamphetamine; did knowingly and unlawfully possess in and affecting commerce, a firearm and prior thereto the defendant had been convicted in a court of a crime punishable by imprisonment for a term exceeding one year; did knowingly use and carry a firearm during and in relation to a drug-trafficking crime, namely, conspiracy to manufacture methamphetamine. Eastern District of Texas
Sentence: Life imprisonment; 10 years’ supervised release (Oct. 16, 1992)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Douglas Ray Dunkins Jr., Fort Worth.
Offense: Conspiracy. Northern District of Texas
Sentence: Life imprisonment; five years’ supervised release (Jan. 20, 1993)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Ronald Gregory Farah, Boca Raton, Fla.
Offense: Conspiracy to import marijuana into the United States; importation of marijuana into the United States; conspiracy to possess with intent to distribute marijuana; possession with intent to distribute marijuana. Middle District of Florida
Sentence: Life imprisonment; 10 years’ supervised release (April 30, 1997)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Joe Mack Flowers, St. Petersburg, Fla.
Offense: Conspiracy to possess with intent to distribute 50 grams or more of crack cocaine; possession with intent to distribute of 50 grams or more of crack cocaine; possession of a firearm during a drug-trafficking offense; convicted felon in possession of a firearm. Middle District of Florida
Sentence: Life plus 60 months’ imprisonment; 10 years’ supervised release (July 1, 1991)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Ronald Glinton, Boynton Beach, Fla.
Offense: Conspiracy to manufacture and possess with intent to distribute cocaine; conspiracy to possess with intent to distribute cocaine base; possession with intent to distribute cocaine; possession of cocaine with intent to manufacture cocaine base. Southern District of Florida
Sentence: Life imprisonment; 10 years’ supervised release (April 2, 1993)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Gregory E. Graham, Denver
Offense: Distribution of cocaine base. District of Wyoming
Sentence: 300 months’ imprisonment; eight years’ supervised release; $1,000 fine (Nov. 1, 2005)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Teresa Mechell Griffin, Orlando
Offense: Conspiracy to possess cocaine powder and/or cocaine base with intent to distribute; unlawful travel in interstate commerce with the intent to promote, manage, establish, carry on or facilitate the promotion, management, establishment and carrying on of unlawful activity; distribution of one kilogram of cocaine (two counts). Western District of Oklahoma
Sentence: Life imprisonment; five years’ supervised release (May 6, 1994)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Larry Roscoe Gunnell Jr., Hightown, N.J.
Offense: Possession with intent to distribute crack and aiding and abetting. Eastern District of Virginia
Sentence: Life imprisonment; 10 years’ supervised release (July 8, 1999)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Marvin Hampton, Orangeburg, S.C.
Offense: Possession with intent to distribute 50 grams or more of cocaine base; knowingly using and carrying a firearm during and in relation to, and possession of a firearm in furtherance of, a drug-trafficking crime. District of South Carolina
Sentence: 180 months’ imprisonment; five years’ supervised release (Nov. 28, 2006)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Cedric Jarreau Hawkins, Chicago
Offense: Distribution of 5.4 grams of cocaine base within 1,000 feet of a protected location after two or more prior felony drug convictions. Northern District of Iowa
Sentence: Life imprisonment; 10 years’ supervised release (Feb. 1, 2008)
Commutation grant: Prison sentence commuted to expire June 3, 2018.
Cleon Jermaine Hawkins, Baker, La.
Offense: Possession with intent to distribute cocaine base and cocaine; possession of a firearm in furtherance of a drug-trafficking crime. Middle District of Louisiana
Sentence: 180 months’ imprisonment; five years’ supervised release (June 5, 2008)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Bennit Hayes, Jonesboro, Ga.
Offense: Conspiracy to possess with intent to distribute five kilograms or more of cocaine and five grams or more of cocaine base; possession with intent to distribute 500 grams or more of a mixture and substance containing cocaine. Northern District of Florida
Sentence: Life imprisonment; 10 years’ supervised release; $800 fine (Feb. 6, 2003)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Patrick Henderson, Beloit, Wis.
Offense: Conspiracy to distribute cocaine base. Western District of Wisconsin
Sentence: 360 months’ imprisonment; five years’ supervised release (April 13, 1998); amended to 292 months’ imprisonment (March 16, 2015)
Commutation grant: Prison sentence commuted to expire June 3, 2018.
Tony Jones, Tallahassee
Offense: Conspiracy to distribute cocaine base; possession with intent to distribute cocaine base (two counts). Northern District of Florida
Sentence: Life imprisonment; 10 years’ supervised release (May 16, 1997)
Commutation grant: Prison sentence commuted to expire June 3, 2018.
Everette Bryant Law, Roanoke
Offense: Conspiracy to possess with intent to distribute crack cocaine, to distribute crack cocaine with intent of carrying on unlawful activity, to distribute cocaine with intent of concealing proceeds of unlawful activity; distributing crack cocaine, aid and abet (three counts); false financial transactions to conceal proceeds of drug-trafficking crime. Western District of Virginia
Sentence: Life imprisonment; 10 years’ supervised release (March 25, 1994)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Gary Allen Lott, Oklahoma City
Offense: Conspiracy to manufacture and distribute methamphetamine (two counts); maintaining a residence to manufacture methamphetamine (three counts); possession of chemicals with intent to manufacture methamphetamine; use of a firearm in relation to a drug-trafficking crime. Western District of Oklahoma
Sentence: Life plus five years’ imprisonment; five years’ supervised release (April 5, 2000)
Commutation grant: Prison sentence commuted to expire June 3, 2018.
Kareem Martin, River Rouge, Mich.
Offense: Possession with intent to distribute cocaine base. Eastern District of Michigan
Sentence: 276 months’ imprisonment; five years’ supervised release (Jan. 18, 2007)
Commutation grant: Prison sentence commuted to expire June 3, 2018.
Nolan McSwain, Altadena, Calif.
Offense: Conspiracy to possess with intent to distribute cocaine; possession with intent to distribute cocaine. Central District of California
Sentence: Life imprisonment (Dec. 6, 1993)
Commutation grant: Prison sentence commuted to expire June 3, 2017.
Sherman Ray Meirovitz, Minneapolis
Offense: Possession with intent to distribute cocaine; conspiracy to distribute and possession with intent to distribute cocaine. District of Minnesota
Sentence: Life imprisonment (Jan. 5, 1990)
Commutation grant: Prison sentence commuted to expire June 3, 2017.
Darran Lamar Moore, Miami
Offense: Conspiracy to possess with intent to distribute five kilograms or more of cocaine and 50 grams or more of cocaine base. Southern District of Florida
Sentence: Life imprisonment; 10 years’ supervised release (March 22, 2005)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Robert Pettway, Pensacola, Fla.
Offense: Conspiracy to possess with intent to distribute five kilograms or more of cocaine and 50 grams or more of a mixture and substance containing a detectable amount of cocaine base. Northern District of Florida
Sentence: Life imprisonment; 10 years’ supervised release; $1,000 fine (Aug. 31, 2004)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Patrick Kit Plumlee, Newport News, Va.
Offense: Continuing criminal enterprise; distribution and possession with intent to distribute cocaine and cocaine base (eight counts); use of a firearm in relation to a drug-trafficking crime; renting, leasing and making premises available for storing and distributing cocaine and cocaine base; money laundering and conspiracy (10 counts). Eastern District of Virginia
Sentence: Life plus 60 months’ imprisonment; five years’ supervised release (July 18, 1994); amended to 420 months’ imprisonment (Jan. 6, 2016)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Shawn Antonio Pressley, Greensboro, N.C.
Offense: Possess with intent to distribute cocaine base (crack); carrying a firearm during a drug-trafficking crime. Middle District of North Carolina
Sentence: 322 months’ imprisonment; 10 years’ supervised release (Jan. 23, 1998)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Anthony Walter Puig, Land O’Lakes, Fla.
Offense: Conspiracy to possess with intent to distribute 500 grams or more of cocaine; possession with intent to distribute 500 grams or more of cocaine. Middle District of Florida
Sentence: 360 months’ imprisonment; eight years’ supervised release (Dec. 18, 2002)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Emlera Quince, Knoxville, Tenn.
Offense: Possession with intent to distribute cocaine base (two counts). Eastern District of Tennessee
Sentence: 300 months’ imprisonment; eight years’ supervised release (June 30, 1997)
Commutation grant: Prison sentence commuted to expire on Oct. 1, 2016.
Jesus Ruiz, Kennedale, Tex.
Offense: 1. Conspiracy to distribute marijuana. Western District of New York
2. Conspiracy to possess with intent to distribute marijuana; conspiracy to export marijuana. Western District of New York
Sentence: 1. 92 months’ imprisonment; eight years’ supervised release (July 12, 1993);
2. 360 months’ imprisonment; eight years’ supervised release (April 17, 1998)
Commutation grant: Prison sentences commuted to expire Oct. 1, 2016.
Garrie Lavert Samuels, Groveport, Ohio
Offense: Conspiracy to possess with intent to distribute a quantity of cocaine base; aiding and abetting distribution of more than 50 grams of cocaine base; aiding and abetting distribution of more than five grams of cocaine base. Western District of Texas
Sentence: Life imprisonment; 10 years’ supervised release (April 8, 2003)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Robert Lewis Sleepers III, South Bend, Ind.
Offense: Conspiracy to distribute cocaine and cocaine base; conspiracy to commit money laundering. Northern District of Indiana
Sentence: 240 months’ imprisonment; 10 years’ supervised release (June 18, 2004)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Almos L. Starks, Jacksonville, Fla.
Offense: Conspiracy to distribute cocaine and cocaine base; possession with intent to distribute cocaine; possession with intent to distribute in excess of 50 grams of cocaine base; possession of firearms by a convicted felon. Southern District of Ohio
Sentence: Life imprisonment; six years’ supervised release; $20,000 fine (Oct. 5, 1995)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016, and unpaid balance of the fine remitted.
Phillip Maurice Thomas, Vero Beach, Fla.
Offense: Possession with intent to distribute at least five grams or more of cocaine base; possession with intent to distribute at least 500 grams or more of cocaine; possession with intent to distribute a mixture and substance containing MDMA or ecstasy; possession with intent to distribute a mixture and substance containing marijuana. Southern District of Florida
Sentence: 292 months’ imprisonment; eight years’ supervised release (April 8, 2005)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Shane William Tuttle, Great Falls, Mont.
Offense: Possession with intent to distribute (three counts); use of a firearm during drug-trafficking offense (two counts); illegal use of communication facility (two counts); possession with intent to distribute cocaine. District of Montana
Sentence: 360 months’ imprisonment; four years’ supervised release (Sept. 14, 1994)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Craig L. Watson, Jacksonville, Ark.
Offense: Conspiracy to distribute more than 50 grams of crack cocaine; distribution of cocaine; attempt to distribute cocaine base; possession with intent to distribute cocaine base. Eastern District of Arkansas
Sentence: 276 months’ imprisonment; 10 years’ supervised release (July 10, 2006); amended to 240 months’ imprisonment (Dec. 15, 2011)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Lawrence McArthur Webb, Salem, Va.
Offense: Conspiracy to possess with intent to distribute more than 50 grams of cocaine base and more than five kilograms of cocaine powder; distribution of cocaine (two counts). Western District of Virginia
Sentence: 240 months’ imprisonment; 10 years’ supervised release (June 4, 2007)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Danny Ray White, Garland, Tex.
Offense: Attempt to manufacture and manufacture of methamphetamine; attempt to manufacture and manufacture of amphetamine; possession of a three-neck round-bottom flask; possession of a listed chemical, ethyl ether. Eastern District of Texas
Sentence: Life imprisonment; 10 years’ supervised release; $11,000 fine (July 19, 1996)
Commutation grant: Prison sentence commuted to expire Oct. 1, 2016.
Julian L. Wyre, Chicago
Offense: Possession with intent to distribute cocaine base. Northern District of Illinois
Sentence: 204 months’ imprisonment; five years’ supervised release; $250 fine (Nov. 6, 2008)
Commutation grant: Prison sentence commuted to expire June 3, 2018. |
import { spawnTemplate } from "."
export const builderSpawnLogic = (room: Room) => {
return spawnTemplate({
role: 'builder',
room
})
}
|
-- Copyright 2017 <NAME> <<EMAIL>>
-- SPDX-License-Identifier: MIT
{-# LANGUAGE FlexibleContexts #-}
module XMonad.MyConfig.Notify
( applyMyUrgencyHook
, popupCurDesktop
, myDefaultPopup, myNotify, myNotifyColored)
where
-- needs `notify-osd` and `libnotify`
-- See: https://pbrisbin.com/posts/using_notify_osd_for_xmonad_notifications/
-- and https://wiki.haskell.org/Xmonad/Config_archive/doitan%27s_xmonad.hs
-- and https://github.com/lierdakil/xmonad-config/blob/master/Local/Popup.hs
import XMonad
import XMonad.Util.Dzen
import XMonad.Util.EZConfig (additionalKeys)
import XMonad.Hooks.UrgencyHook
import XMonad.Util.NamedWindows
import qualified XMonad.StackSet as W
import XMonad.MyConfig.Common
applyMyUrgencyHook :: (LayoutClass a Window) => XConfig a -> XConfig a
applyMyUrgencyHook c = withUrgencyHook myUrgencyHook c
`additionalKeys` mapToWithModM c [((m__, xK_u ), focusUrgent)]
myUrgencyHook = MyUrgencyHook (myNotify 2)
newtype MyUrgencyHook = MyUrgencyHook { muhPopup :: String -> X () }
instance UrgencyHook MyUrgencyHook where
urgencyHook MyUrgencyHook { muhPopup = pop } w =
withWindowSet . (. W.findTag w) . flip whenJust . flash =<< getName w
where
flash name index =
pop (show name ++ " @ " ++ index)
mkFont s = font $ "xft:Hack:pixelsize=" ++ show s ++ ":antialias=true:hinting=true"
myNotifyColored :: String -> Rational -> String -> X ()
myNotifyColored color t = dzenConfig pc
where
pc = onCurr (hCenter 1400) >=> timeout t >=> background >=> mkFont 32
background = addArgs ["-bg", color]
myNotify :: Rational -> String -> X ()
myNotify = myNotifyColored "darkgreen"
myPopup :: Int -> Rational -> String -> X ()
myPopup width t = dzenConfig pc
where
pc = onCurr (hCenter width) >=> timeout t >=> mkFont 80
myDefaultPopup :: String -> X ()
myDefaultPopup = myPopup 400 0.5
popupCurDesktop :: X()
popupCurDesktop = (W.currentTag <$> gets windowset) >>= myDefaultPopup . ("ws: " ++)
-- popupCmdOut :: String -> [String] -> X()
-- popupCmdOut cmd args = do
-- cmdOut <- liftIO (readProcess cmd args [])
-- myPopup 400 0.5 cmdOut
-- popupConfig :: Prime
-- popupConfig = do
-- handleEventHook =+ serverModeEventHookF "XMONAD_POPUP" popup
-- apply $ withUrgencyHook $ MyUrgencyHook popup
|
/**
* Handle a change to the ClearStateRecord parameter
*/
void Pco::onClearStateRecord(TakeLock& takeLock)
{
if(paramClearStateRecord)
{
paramStateRecord = "";
paramClearStateRecord = 0;
}
} |
Brit Dee, Contributor
Activist Post
Having devastated millions of lives as co-conspirator in the illegal and immoral Iraq war – and then having raked in millions of pounds through business contacts made during his time as prime minister – war criminal Tony Blair is apparently trying to edge his way back into British politics.
According to the London Guardian, Blair – supposedly retired from frontline politics – is to act as an adviser to the Labour party and will be “contributing ideas and experience to Ed Miliband’s policy review”.
Miliband, the current Labour leader, revealed that Blair will be giving advice on the ‘Olympic legacy’ – and in a sickening display of sycophancy, praised the warmonger and thanked him for what he had done for the Labour party and Britain.
Unless you’re Ed Miliband, it’s difficult to ignore the fact that one of the main things Blair has done for Britain is to cause the country to become widely reviled in the Muslim world. Figures vary, but the Iraq war – illegally launched on a complete fabrication about supposed weapons of mass destruction – is estimated to have resulted in the deaths of well over 100,000 people.
The terrible violence and massive body count in Iraq has evidently not weighed too heavily on Blair’s conscience, and he has carved a highly lucrative business career since leaving office in 2007. Blair’s earnings for 2011 were estimated at £12million; though due to a complex network of partnerships and companies he is able to avoid publishing a complete account of all his commercial ventures, and his full income remains a secret.
He runs a business consultancy called ‘Tony Blair Associates’, known to have deals with the corrupt regimes of Kazakhstan and Kuwait, and he also acts as adviser to criminal investment bank JP Morgan.
Despite his culpability for war crimes, Blair appears untouchable; and in 2009 he even had the gall to try and become the first President of Europe. Apparently still harbouring such ambitions he last month suggested that he might go for the job again in future.
As the political elite seem unlikely to prosecute Blair for war crimes, we are left to take a small amount of solace in the fact that the former PM is now hounded by activists wherever he goes. He travels with extensive security due to people constantly angrily confronting and heckling him. Last month Tom Grundy tried to perform a citizen’s arrest on Blair; and in May, students in the US shouted “warmonger” and “war criminal” at him during a graduation speech he was giving at a college in Maine.
This article first appeared at ResistRadio.com
You can support this information by voting on Reddit HERE
Brit Dee’s ResistRadio.com is an independent media website approaching global news, politics and conspiracy theory from a radical, but critical and rational perspective. |
<gh_stars>1-10
from pyramid.view import view_config
from pyramid import i18n
from memex import search
from memex import storage
from h import feeds
_ = i18n.TranslationStringFactory(__package__)
def _annotations(request):
"""Return the annotations from the search API."""
result = search.Search(request).run(request.params)
return storage.fetch_ordered_annotations(request.db, result.annotation_ids)
@view_config(route_name='stream_atom')
def stream_atom(request):
"""An Atom feed of the /stream page."""
return feeds.render_atom(
request=request, annotations=_annotations(request),
atom_url=request.route_url("stream_atom"),
html_url=request.route_url("stream"),
title=request.registry.settings.get("h.feed.title"),
subtitle=request.registry.settings.get("h.feed.subtitle"))
@view_config(route_name='stream_rss')
def stream_rss(request):
"""An RSS feed of the /stream page."""
return feeds.render_rss(
request=request, annotations=_annotations(request),
rss_url=request.route_url("stream_rss"),
html_url=request.route_url("stream"),
title=request.registry.settings.get("h.feed.title") or _(
"Hypothesis Stream"),
description=request.registry.settings.get("h.feed.description") or _(
"The Web. Annotated"))
def includeme(config):
config.add_route('stream_atom', '/stream.atom')
config.add_route('stream_rss', '/stream.rss')
config.scan(__name__)
|
//Thread-4: Calculate the number of courses from SOC
public class Thread4 implements Runnable{
public void run(){
try{
ExtractData ex = new ExtractData();
ArrayList<String> course = ex.course();
ArrayList<String> SOC = new ArrayList<String>();
for (int i=0; i<course.size(); i++) {
if(course.get(i).contains("STIW")|| course.get(i).contains("STIA")|| course.get(i).contains("STQM")||
course.get(i).contains("STID")|| course.get(i).contains("STIJ")|| course.get(i).contains("STIX")||
course.get(i).contains("STIN")|| course.get(i).contains("STQS")|| course.get(i).contains("STIK1")||
course.get(i).contains("STIK2")|| course.get(i).contains("STIK3")){
String soc = course.get(i).replaceAll(",", " ");
SOC.add(soc);
}
}
System.out.println(Thread.currentThread().getName() + " Number of Courses from SOC: " + SOC.size());
}catch(Exception e){
e.printStackTrace();
}
}
} |
n = int(input())
won = list(input())
A_won = len([1 for i in won if i=='A'])
print("Anton" if A_won>n-A_won else "Danik" if A_won<n-A_won else "Friendship")
|
a=int(input())
for i in range(a):
s=int(input())
ans=[]
for i in range(s//2):
ans.append(2*(i+1)-1)
ans.append(ans[-1]+1)
if(s%2==1):
ans.append(s)
print(len(ans))
print(*ans)
|
Subsets and Splits