content
stringlengths 10
4.9M
|
---|
Implications of Implant Framework Misfit: An Animal Study on an Ovine Model.
Although clinicians routinely aim to provide prosthesis with accurate fit on implants, a degree of prosthesis misfit is inevitable. This exploratory animal study evaluated the effects of framework vertical misfit and the timing of implant loading on implant position and screw loosening. Four implants were placed in healed ridges of each side of mandibles of 3 sheep. On the right side, 2 immediate frameworks were placed after 2 days. One framework was fitting, and the other one had a vertical gap of 0.5 mm on the distal implant. After 8 weeks (1 st review), the left side received 2 conventional frameworks with similar fit conditions to the right side. All the animals were euthanised after 8 weeks (2 nd review). At the 1 st and 2 nd reviews, implant level impressions were taken to measure the vertical displacement of distal implants, and the retaining screws loosening torque values were measured. The loosening torque values for the immediate fitting frameworks were considerably greater than the immediate misfitting frameworks. This was noticeable at the 1 st review. At the 2 nd review, the loosening torque values were comparable for the immediate fitting and misfitting frameworks. Vertical implant displacement was observed for all the misfitting frameworks. However, much more implant displacement occurred under immediate frameworks. Therefore, implant frameworks with vertical misfit in the present study were associated with less screw stability and more implant displacement. Retightening the retaining screws during the maturation of bone seemed to maintain the torque values.
|
Piously posturing as the savior of Medicare, President Obama lashed out at the House Republicans for embracing the budget proposed by Budget Committee Chairman Paul Ryan Paul Davis RyanBrexit and exit: A transatlantic comparison Five takeaways from McCabe’s allegations against Trump The Hill's 12:30 Report: Sanders set to shake up 2020 race MORE (R-Wis.). But a comparison of the president’s own plans for Medicare with those in the Ryan budget shows that the Democratic cuts are far more immediate and drastic than anything in the GOP proposal.
While the Republican Medicare changes only take effect in 2021, Obama’s cuts will begin hurting seniors right away. The president’s healthcare legislation imposed a hard spending cap on Medicare — the first time it has ever had one — which he has just proposed lowering by another one-half of 1 percent of GDP (a further cut of about $70 billion a year).
ADVERTISEMENT
Obama’s cuts, which will take effect immediately, are to be administered by his newly created Independent Payment Advisory Board (IPAB) of 15 members appointed by the president. Its recommendations for cuts in Medicare services or for reductions in reimbursement will not be subject to congressional approval but will take effect by administrative fiat. Right now.
The IPAB will be, essentially, the rationing board that will decide who gets what care. Its decisions will be guided by a particularly vicious concept of Quality Adjusted Life Years (QUALYS). If you have enough QUALYS ahead of you, you’ll be approved for a hip replacement or a heart transplant. If not, you’re out of luck. Perforce, many of these cuts will fall on those at the end of their lives, reducing their options to accommodate Obama’s mandate to cut costs. If death comes sooner, well, that’s the price of aging in Obama’s America.
Ryan’s approach is totally different. First, he does nothing at all to cut benefits for those now on Medicare or for anyone who turns 65 before 2022 (leaving me in the clear!). Second, the Republicans would leave the elderly in charge of their own medical decisions by letting them spend their Medicare money as they wish. The subsidy they would receive for health insurance would permit them to buy plans tailored to their needs. Just as a myriad of insurance-company plans sprang up to fill the mandates of the new prescription drug benefit, there will likely be quite an array of choices for the elderly of 2021. Finally, the savings from Ryan’s plan will be plowed back into Medicare, prolonging its life, rather than being diverted, as Obama would do, into paying for a new entitlement for younger people.
But the most important difference is that Obama’s cuts are now and Ryan’s are not. Any budget projection is a guess. When the projection is made two to three years in advance, it is conjecture. Ten years away it becomes fantasy. Who can possibly tell how the American economy will be doing a decade hence? What revenues will it generate? And the only thing less certain than guessing about the economy is projecting healthcare costs.
Medicine is on the verge of a revolution akin to that which followed the creation of antibiotics. Genetic medicine and ultimately nanotechnology are about to change everything. No longer will we fight cancer by cutting or burning or poisoning diseased cells. Instead, we will use DNA and RNA to predict cancers and grow healthy cells. Who knows what the costs will be? Possibly, they could be lower than our current range of therapies.
And, between now and 2021, Congress will be able to change the Ryan plan as it chooses. But the early deaths triggered by the rationing decisions of Obama’s IPAB cannot be saved. Their decisions are, for the elderly of today, irreversible.
Democrats are drooling over the prospect of conducting the elections of 2012 over Medicare. They better watch their steps. The truth might come out!
Morris, a former adviser to Sen. Trent Lott (R-Miss.) and President Clinton, is the author of Outrage, Fleeced, Catastrophe and 2010: Take Back America — A Battle Plan. To get all of his and Eileen McGann’s columns for free by e-mail or to order a signed copy of their latest book, Revolt! How To Defeat Obama and Repeal His Socialist Programs — A Patriot’s Guide, go to http://www.dickmorris.com.
|
// Copyright © 2022, Cisco Systems Inc.
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file or at https://opensource.org/licenses/MIT.
package skel
import (
"github.com/iancoleman/strcase"
"path"
"strings"
)
const (
inflectionAppTitle = "App Title"
inflectionProtocolUpperCamel = "ProtocolUpperCamel"
inflectionProtocolLowerCamel = "protocolLowerCamel"
)
func init() {
AddTarget("generate-domain-beats", "Generate beats domain implementation", GenerateBeatsDomain)
AddTarget("generate-kubernetes-beats", "Create production kubernetes manifest templates", GenerateKubernetesForBeats)
}
func GenerateBeatsDomain(args []string) error {
inflections := map[string]string{
inflectionAppTitle: strings.Title(skeletonConfig.AppName),
inflectionProtocolUpperCamel: strcase.ToCamel(skeletonConfig.BeatProtocol),
inflectionProtocolLowerCamel: strcase.ToLowerCamel(skeletonConfig.BeatProtocol),
}
apiPackageSource := path.Join("code", "beats", "api")
apiPackagePath := path.Join("pkg", "api")
apiPackageUrl := path.Join("cto-github.cisco.com/NFV-BU", skeletonConfig.AppName, apiPackagePath)
beaterPackageSource := path.Join("code", "beats", "beater")
beaterPackagePath := path.Join("internal", "beater")
//beaterPackageUrl := path.Join("cto-github.cisco.com/NFV-BU", skeletonConfig.AppName, beaterPackagePath)
metaPackageSource := path.Join("code", "beats", "_meta")
metaPackagePath := path.Join("internal", "_meta")
templates := TemplateSet{
{
Name: inflections[inflectionAppTitle] + " Field Descriptors",
SourceFile: path.Join(metaPackageSource, "fields.yml"),
DestFile: path.Join(metaPackagePath, "fields.yml"),
Format: FileFormatYaml,
},
{
Name: inflections[inflectionAppTitle] + " DTO",
SourceFile: path.Join(apiPackageSource, "device.go"),
DestFile: path.Join(apiPackagePath, "device.go"),
},
{
Name: inflections[inflectionAppTitle] + " Beater Init",
SourceFile: path.Join(beaterPackageSource, "init.go.tpl"),
DestFile: path.Join(beaterPackagePath, "init.go"),
},
{
Name: inflections[inflectionAppTitle] + " Beater Config",
SourceFile: path.Join(beaterPackageSource, "config.go.tpl"),
DestFile: path.Join(beaterPackagePath, "config.go"),
},
{
Name: inflections[inflectionAppTitle] + " Beater State",
SourceFile: path.Join(beaterPackageSource, "state.go.tpl"),
DestFile: path.Join(beaterPackagePath, "state.go"),
},
{
Name: inflections[inflectionAppTitle] + " Beater Implementation",
SourceFile: path.Join(beaterPackageSource, "beater.go.tpl"),
DestFile: path.Join(beaterPackagePath, "beater.go"),
},
}
options := NewRenderOptions()
options.AddStrings(inflections)
options.AddString("cto-github.cisco.com/NFV-BU/go-msx/skel/_templates/code/beats/api", apiPackageUrl)
if err := templates.Render(options); err != nil {
return err
}
return initializePackageFromFile(
path.Join(skeletonConfig.TargetDirectory(), "cmd", "app", "main.go"),
path.Join(skeletonConfig.AppPackageUrl(), "internal", "beater"))
}
|
package org.ggp.base.player.gamer.statemachine.sample;
import org.ggp.base.util.statemachine.MachineState;
import org.ggp.base.util.statemachine.Move;
import org.ggp.base.util.statemachine.Role;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException;
import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException;
import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException;
public class UCT extends MonteCarloTreeSearch {
public final double EXPLORATION_CONSTANT = 1 / Math.sqrt(2);
public final boolean MINIMAX = true;
public Node rootNode;
public UCT(long finishBy, Role role, StateMachine theMachine) {
super(finishBy, role, theMachine);
}
public Move UCTSearch(MachineState state) throws MoveDefinitionException, TransitionDefinitionException, GoalDefinitionException {
// Set the root node parent to null
rootNode = new Node(state, null, null, 0, theMachine, role);
// Until time runs out, run algorithm
while(System.currentTimeMillis() < finishBy) {
Node currentNode = treePolicy(rootNode);
double reward = defaultPolicy(currentNode.state);
backup(currentNode, reward);
}
// Return best child move
// System.out.println(" TOTAL PLAYOUTS: " + playouts);
Node node = bestChild(rootNode, 0.0, MINIMAX);
return node.move;
}
public Node treePolicy(Node node) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
while (!theMachine.isTerminal(node.state)) {
if(node.nextStatesMap.size() != 0) {
return expand(node);
} else {
node = bestChild(node, EXPLORATION_CONSTANT, MINIMAX);
}
}
return node;
}
public Node bestChildMinimax(Node node, double explorationConstant) {
Node bestChild = null;
double bestScore = Double.POSITIVE_INFINITY;
for (Node child : node.children) {
double score;
if(child.turn != node.myRole) {
score = (child.reward / child.visits) + explorationConstant * (Math.sqrt((2*Math.log(node.visits))/child.visits));
} else {
score = (child.reward / child.visits) - explorationConstant * (Math.sqrt((2*Math.log(node.visits))/child.visits));
}
// System.out.println(child.move + " VISITS: " + child.visits + " SCORE: " + score + " LEVEL: " + child.level);
if(bestScore == Double.POSITIVE_INFINITY) {
bestChild = child;
bestScore = score;
} else if (child.turn != node.myRole && score > bestScore || child.turn == node.myRole && score < bestScore) {
bestChild = child;
bestScore = score;
}
}
return bestChild;
}
public Node bestChildGen(Node node, double explorationConstant) {
Node bestChild = null;
double bestScore = 0.0;
for (Node child : node.children) {
double score = (child.reward / child.visits) + explorationConstant * (Math.sqrt((2*Math.log(node.visits))/child.visits));
if(explorationConstant == 0.0)
// System.out.println(child.move + " VISITS: " + child.visits + " SCORE: " + score);
if (score > bestScore) {
bestChild = child;
bestScore = score;
}
}
return bestChild;
}
public Node bestChild(Node node, double explorationConstant, boolean minimax) throws GoalDefinitionException {
if(minimax) {
return bestChildMinimax(node, explorationConstant);
} else {
return bestChildGen(node, explorationConstant);
}
}
public void backup(Node node, double reward) {
while (node != null) {
node.updateUCT(reward);
node = node.parent;
}
}
}
|
<filename>src/pkg/fetch/fetch_test.go
package fetch
import (
"gospec"
// . "gospec"
)
func FetchSpec(c gospec.Context) {
// TODO: Figure out what to put here
}
|
def add_constraint(self, type, column, check_clause=None):
if type == 'CHECK' and check_clause and 'NOT NULL' in check_clause:
sql = self.commands.add_check_not_null(self.name, check_clause.split(' ')[0])
elif type == 'CHECK':
if check_clause and 'VALUE' in check_clause and column:
check_clause.replace('VALUE', column)
sql = self.commands.add_check(self.name, check_clause)
elif type in ['UNIQUE', 'PRIMARY KEY']:
constraint_name = self.new_constraint_name(column, type)
sql = self.commands.add_constraint(self.name, constraint_name, type, column)
else:
raise Exception('Invalid constraint parameters')
try:
self.execute(sql)
except Exception as e:
print('Unable to add constraint: {}'.format(e))
self.commit()
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> PII;
const ll mx = 3e5+10;
map<ll,ll>mp;
void solve()
{
ll n ;
cin>>n;
ll Ans = 0 ;
mp.clear();
ll Ar[n+5],Mn,Mx;
for(int i=0; i<n; i++) cin>>Ar[i];
for(int i=0; i<n; i++)
mp[Ar[i]%3]++;
while(mp[0]< (n/3) && mp[2]>(n/3))
{
mp[0]++;
mp[2]--;
Ans++;
}
while(mp[0]<(n/3) && mp[1]>(n/3))
{
mp[0]++;
mp[1]--;
Ans+=2;
}
while(mp[1]<(n/3)&&mp[0]>(n/3))
{
mp[1]++;
mp[0]--;
Ans++;
}
while(mp[1]<(n/3)&&mp[2]>(n/3))
{
mp[1]++;
mp[2]--;
Ans+=2;
}
while(mp[2]<(n/3) &&mp[1]> (n/3))
{
mp[2]++;
mp[1]--;
Ans++;
}
while(mp[2]< (n/3)&&mp[0]> (n/3))
{
mp[2]++;
mp[0]--;
Ans+=2;
}
cout<<Ans<<"\n";
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
cin>>t;
while(t--)
{
solve();
}
}
|
<filename>packages/engine/src/renderer/materials/constants/VoronoiClouds.mat.ts
import { ShaderMaterial } from 'three'
import { Entity } from '@xrengine/engine/src/ecs/classes/Entity'
import { defineAction } from '@xrengine/hyperflux'
import { MaterialParms } from '../MaterialParms'
export const vertexShader = `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1);
}
`
export const fragmentShader = `
uniform vec3 iResolution;
uniform float iTime;
varying vec2 vUv;
/*
Combustible Voronoi Layers
--------------------------
The effect itself is nothing new or exciting, just some moving 3D Voronoi layering.
However, the fire palette might prove useful to some.
*/
// This is my favorite fire palette. It's trimmed down for shader usage, and is based on an
// article I read at Hugo Elias's site years ago. I'm sure most old people, like me, have
// visited his site at one time or another:
//
// http://freespace.virgin.net/hugo.elias/models/m_ffire.htm
//
vec3 firePalette(float i){
float T = 1400. + 1300.*i; // Temperature range (in Kelvin).
vec3 L = vec3(7.4, 5.6, 4.4); // Red, green, blue wavelengths (in hundreds of nanometers).
L = pow(L,vec3(5)) * (exp(1.43876719683e5/(T*L)) - 1.);
return 1. - exp(-5e8/L); // Exposure level. Set to "50." For "70," change the "5" to a "7," etc.
}
/*
vec3 firePalette(float i){
float T = 1400. + 1300.*i; // Temperature range (in Kelvin).
// Hardcode red, green and blue wavelengths (in hundreds of nanometers).
vec3 L = (exp(vec3(19442.7999572, 25692.271372, 32699.2544734)/T) - 1.);
// Exposure level. Set to "50" For "70," change the ".5" to a ".7," etc.
return 1. - exp(-vec3(22532.6051122, 90788.296915, 303184.239775)*2.*.5/L);
}
*/
vec3 hash33(vec3 p){
float n = sin(dot(p, vec3(7, 157, 113)));
return fract(vec3(2097152, 262144, 32768)*n);
}
// 3D Voronoi: Obviously, this is just a rehash of IQ's original.
//
float voronoi(vec3 p){
vec3 b, r, g = floor(p);
p = fract(p); // "p -= g;" works on some GPUs, but not all, for some annoying reason.
// Maximum value: I think outliers could get as high as "3," the squared diagonal length
// of the unit cube, with the mid point being "0.75." Is that right? Either way, for this
// example, the maximum is set to one, which would cover a good part of the range, whilst
// dispensing with the need to clamp the final result.
float d = 1.;
// I've unrolled one of the loops. GPU architecture is a mystery to me, but I'm aware
// they're not fond of nesting, branching, etc. My laptop GPU seems to hate everything,
// including multiple loops. If it were a person, we wouldn't hang out.
for(int j = -1; j <= 1; j++) {
for(int i = -1; i <= 1; i++) {
b = vec3(i, j, -1);
r = b - p + hash33(g+b);
d = min(d, dot(r,r));
b.z = 0.0;
r = b - p + hash33(g+b);
d = min(d, dot(r,r));
b.z = 1.;
r = b - p + hash33(g+b);
d = min(d, dot(r,r));
}
}
return d; // Range: [0, 1]
}
// Standard fBm function with some time dialation to give a parallax
// kind of effect. In other words, the position and time frequencies
// are changed at different rates from layer to layer.
//
float noiseLayers(in vec3 p) {
// Normally, you'd just add a time vector to "p," and be done with
// it. However, in this instance, time is added seperately so that
// its frequency can be changed at a different rate. "p.z" is thrown
// in there just to distort things a little more.
vec3 t = vec3(0., 0., p.z + iTime*1.5);
const int iter = 5; // Just five layers is enough.
float tot = 0., sum = 0., amp = 1.; // Total, sum, amplitude.
for (int i = 0; i < iter; i++) {
tot += voronoi(p + t) * amp; // Add the layer to the total.
p *= 2.; // Position multiplied by two.
t *= 1.5; // Time multiplied by less than two.
sum += amp; // Sum of amplitudes.
amp *= .5; // Decrease successive layer amplitude, as normal.
}
return tot/sum; // Range: [0, 1].
}
void main()
{
vec2 fragCoord = vUv;
// Screen coordinates.
vec2 uv = (fragCoord - iResolution.xy*.5) / iResolution.y;
// Shifting the central position around, just a little, to simulate a
// moving camera, albeit a pretty lame one.
uv += vec2(sin(iTime*.5)*.25, cos(iTime*.5)*.125);
// Constructing the unit ray.
vec3 rd = normalize(vec3(uv.x, uv.y, 3.1415926535898/8.));
// Rotating the ray about the XY plane, to simulate a rolling camera.
float cs = cos(iTime*.25), si = sin(iTime*.25);
// Apparently "r *= rM" can break in some older browsers.
rd.xy = rd.xy*mat2(cs, -si, si, cs);
// Passing a unit ray multiple into the Voronoi layer function, which
// is nothing more than an fBm setup with some time dialation.
float c = noiseLayers(rd*2.);
// Optional: Adding a bit of random noise for a subtle dust effect.
c = max(c + dot(hash33(rd)*2. - 1., vec3(.015)), 0.);
// Coloring:
// Nebula.
c *= sqrt(c)*1.5; // Contrast.
vec3 col = firePalette(c); // Palettization.
//col = mix(col, col.zyx*.1+ c*.9, clamp((1.+rd.x+rd.y)*0.45, 0., 1.)); // Color dispersion.
col = mix(col, col.zyx*.15 + c*.85, min(pow(dot(rd.xy, rd.xy)*1.2, 1.5), 1.)); // Color dispersion.
col = pow(col, vec3(1.25)); // Tweaking the contrast a little.
// The fire palette on its own. Perhaps a little too much fire color.
//c = pow(c*1.33, 1.25);
//vec3 col = firePalette(c);
// Black and white, just to keep the art students happy. :)
//c *= c*1.5;
//vec3 col = vec3(c);
// Rough gamma correction, and done.
gl_FragColor = vec4(sqrt(clamp(col, 0., 1.)), 1);
}`
export const DefaultArgs = {
iTime: 0.0,
iResolution: [1, 1, 1]
}
export default function VoronoiClouds(args?: { iTime?: number; iResolution?: number[] }): MaterialParms {
const mat = new ShaderMaterial({
uniforms: {
iTime: { value: args?.iTime ?? DefaultArgs.iTime },
iResolution: { value: args?.iResolution ?? DefaultArgs.iResolution }
},
vertexShader: vertexShader,
fragmentShader: fragmentShader
})
return {
material: mat,
update: (delta) => {
mat.uniforms.iTime.value += delta
}
}
}
|
<filename>rest/asio_peer_connection.cc
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/* asio_peer_connection.cc -*- C++ -*-
<NAME>, 2 June 2014
Copyright (c) 2014 mldb.ai inc. All rights reserved.
*/
#include "asio_peer_connection.h"
#include "mldb/utils/string_functions.h"
#include "mldb/arch/backtrace.h"
#include "mldb/io/asio_thread_pool.h"
#include "mldb/io/asio_timer.h"
#include "mldb/watch/watch_impl.h"
#include <atomic>
#include <boost/asio.hpp>
using namespace std;
namespace MLDB {
/*****************************************************************************/
/* ASIO PEER CONNECTION */
/*****************************************************************************/
struct AsioPeerConnection::Itl {
Itl(std::shared_ptr<boost::asio::ip::tcp::socket> sock,
AsioPeerConnection * connection);
PeerConnectionStatus getStatus() const;
std::atomic<bool> shutdown_;
std::shared_ptr<boost::asio::ip::tcp::socket> sock;
boost::asio::strand strand;
AsioPeerConnection * connection;
PeerConnectionState currentState;
std::string currentError;
std::function<bool (std::string & data)> onSend;
// This mutex only protects changes in internal object state. The
// asio strand protects the actual reading and writing.
mutable std::recursive_mutex mutex; // TODO: should be able to get rid of it
uint64_t currentPacketLength;
std::string currentPacket;
std::unique_ptr<std::string> bufferedRead;
std::atomic<bool> currentlyReading;
std::atomic<bool> currentlyWriting;
};
AsioPeerConnection::Itl::
Itl(std::shared_ptr<boost::asio::ip::tcp::socket> sock,
AsioPeerConnection * connection)
: strand(sock->get_io_service()),
connection(connection)
{
this->sock = sock;
// Minimise latency by turning off Nagle's algorithm. Only really makes
// sense for real-time calls.
this->sock->set_option(boost::asio::ip::tcp::no_delay(true));
currentlyReading = false;
currentlyWriting = false;
currentState = (sock->is_open() ? ST_CONNECTED : ST_CLOSED);
currentError = "";
shutdown_ = false;
}
AsioPeerConnection::
AsioPeerConnection(std::shared_ptr<boost::asio::ip::tcp::socket> sock)
: itl(new Itl(sock, this))
{
}
AsioPeerConnection::
~AsioPeerConnection()
{
shutdown();
}
PeerConnectionStatus
AsioPeerConnection::
getStatus() const
{
return itl->getStatus();
}
PeerConnectionStatus
AsioPeerConnection::Itl::
getStatus() const
{
std::unique_lock<std::recursive_mutex> guard(mutex);
PeerConnectionStatus result;
result.state = currentState;
result.fd = sock->native_handle();
result.style = "socket(asio)";
boost::system::error_code err;
auto local_ep = sock->local_endpoint(err);
if (!err) {
result.local.addr = local_ep.address().to_string();
result.local.port = local_ep.port();
} else {
result.local.addr = err.message();
result.local.port = -1;
}
auto remote_ep = sock->remote_endpoint(err);
if (!err) {
result.remote.addr = remote_ep.address().to_string();
result.remote.port = remote_ep.port();
} else {
result.remote.addr = err.message();
result.remote.port = -1;
}
{
tcp_info tcpinfo;
socklen_t len = sizeof(tcpinfo);
int res = getsockopt(result.fd, IPPROTO_TCP, TCP_INFO, &tcpinfo, &len);
if (res != -1) {
result.rttMs = tcpinfo.tcpi_rtt / 1000.0;
result.rttVarianceMs = tcpinfo.tcpi_rttvar / 1000.0;
}
}
// endpoints
return result;
}
void
AsioPeerConnection::
shutdown()
{
std::unique_lock<std::recursive_mutex> guard(mutex);
itl->shutdown_ = true;
// First, cancel outstanding operations
boost::system::error_code error;
itl->sock->cancel(error);
// Swallow the error; we're trying to shut down
itl->currentState = ST_CLOSED;
itl->sock->close();
// ...
// Now wait for everything to catch up
}
void
AsioPeerConnection::
send(std::string && data)
{
std::unique_lock<std::recursive_mutex> guard(mutex);
ExcAssert(!itl->currentlyWriting);
ExcAssert(itl->sock);
//boost::system::error_code err;
uint64_t length = data.length();
itl->sock->send(boost::asio::buffer(&length, sizeof(length)));
itl->sock->send(boost::asio::buffer(data.c_str(), data.size()));
}
void
AsioPeerConnection::
startWriting(std::function<bool (std::string & data)> onSend)
{
std::unique_lock<std::recursive_mutex> guard(mutex);
ExcAssert(onSend);
this->itl->onSend = onSend;
if (!itl->currentlyWriting) {
doStartWriting(itl);
}
}
void
AsioPeerConnection::
doStartWriting(std::shared_ptr<Itl> itl)
{
ExcAssert(itl->onSend);
std::string newPacket;
bool hasPacket = itl->onSend(newPacket);
if (!hasPacket) {
itl->currentlyWriting = false;
return;
}
struct Packet {
uint64_t length;
string payload;
};
auto packet = std::make_shared<Packet>();
packet->length = newPacket.length();
packet->payload = std::move(newPacket);
// Create a lambda to capture the packet so that it stays put until the
// write is finished
auto onWriteDoneCb = [packet,itl] (boost::system::error_code err,
size_t bytesDone)
{
if (err) {
cerr << "onWriteDoneCb: erro = " << err.message() << endl;
}
else {
ExcAssertEqual(bytesDone, packet->length + 8);
}
//cerr << "write done callback: " << bytesDone << " bytes done"
// << endl;
onWriteDone(err, bytesDone, itl);
(void)packet.get();
};
std::vector<boost::asio::const_buffer> buffers = {
boost::asio::buffer((const void *)(&packet->length), 8),
boost::asio::buffer(packet->payload)
};
//cerr << "writing " << boost::asio::buffer_size(packet->buffers)
// << " bytes for packet of length " << packet->length << endl;
boost::asio::
async_write(*itl->sock, buffers, itl->strand.wrap(onWriteDoneCb));
//cerr << "done async write" << endl;
itl->currentlyWriting = true;
}
void
AsioPeerConnection::
onWriteDone(boost::system::error_code err, size_t bytesDone,
std::shared_ptr<Itl> itl)
{
#if 0
if (err) {
cerr << "Peer write had error " << err.message() << endl;
return;
}
#endif
//cerr << "wrote " << bytesDone << " bytes" << endl;
if (itl->shutdown_)
return;
if (err) {
cerr << "Peer write had error " << err.message() << endl;
notifyError(err, itl);
return;
}
std::unique_lock<std::recursive_mutex> guard(mutex);
if (itl->shutdown_)
return;
doStartWriting(itl);
}
void
AsioPeerConnection::
stopWriting()
{
std::unique_lock<std::recursive_mutex> guard(mutex);
itl->onSend = nullptr;
itl->currentlyWriting = false;
}
void
AsioPeerConnection::
startReading(std::function<bool (std::string && data)> onRecv)
{
std::unique_lock<std::recursive_mutex> guard(mutex);
ExcAssert(onRecv);
bool hadOnRecv = !!this->onRecv;
this->onRecv = onRecv;
if (itl->bufferedRead) {
if (!this->onRecv(std::move(*itl->bufferedRead)))
this->onRecv = nullptr;
itl->bufferedRead.reset();
}
if (!hadOnRecv && this->onRecv) {
doStartReading(itl);
}
}
void
AsioPeerConnection::
stopReading()
{
std::unique_lock<std::recursive_mutex> guard(mutex);
onRecv = nullptr;
itl->currentlyReading = false;
}
void
AsioPeerConnection::
doStartReading(std::shared_ptr<Itl> itl)
{
boost::asio::async_read(*itl->sock, boost::asio::buffer(&itl->currentPacketLength, 8),
itl->strand.wrap(std::bind(&AsioPeerConnection::onReadLengthDone,
std::placeholders::_1,
std::placeholders::_2,
itl)));
itl->currentlyReading = true;
}
void
AsioPeerConnection::
onReadLengthDone(boost::system::error_code err, size_t bytesDone,
std::shared_ptr<Itl> itl)
{
if (err == boost::system::errc::operation_canceled
|| err == boost::asio::error::operation_aborted) {
return;
}
if (itl->shutdown_)
return;
if (err) {
cerr << "Peer read length had error " << err.message() << endl;
notifyError(err, itl);
return;
}
if (bytesDone != 8) {
// This is a logic error; it should never happen. It's OK to
// crash the world.
throw MLDB::Exception("wrong number of length bytes read in packet");
}
//cerr << "itl->currentPacketLength = " << itl->currentPacketLength << endl;
// Create the space to read the packet into
itl->currentPacket.clear();
itl->currentPacket.resize(itl->currentPacketLength, 0);
boost::asio::async_read(*itl->sock, boost::asio::buffer(&itl->currentPacket[0], itl->currentPacketLength),
itl->strand.wrap(std::bind(&AsioPeerConnection::onReadDataDone,
std::placeholders::_1,
std::placeholders::_2,
itl)));
}
void
AsioPeerConnection::
onReadDataDone(boost::system::error_code err, size_t bytesDone,
std::shared_ptr<Itl> itl)
{
if (err == boost::system::errc::operation_canceled
|| err == boost::asio::error::operation_aborted) {
return;
}
if (err) {
cerr << "Peer read had error " << err.message() << endl;
}
if (itl->shutdown_)
return;
std::unique_lock<std::recursive_mutex> guard(mutex);
if (itl->shutdown_)
return;
//cerr << "onReadDataDone" << endl;
//cerr << "got packet " << currentPacket << endl;
if (bytesDone == itl->currentPacketLength) {
if (itl->connection->onRecv) {
if (!itl->connection->onRecv(std::move(itl->currentPacket))) {
itl->connection->onRecv = nullptr;
itl->currentlyReading = false;
}
}
else {
ExcAssert(!itl->bufferedRead);
itl->bufferedRead.reset(new std::string(std::move(itl->currentPacket)));
}
}
else {
ExcAssert(err);
}
if (err) {
cerr << "Peer read had error " << err.message() << endl;
notifyError(err, itl);
return;
}
if (itl->currentlyReading)
doStartReading(itl);
}
void
AsioPeerConnection::
setState(PeerConnectionState newState)
{
if (itl->currentState == newState)
return;
cerr << "peer connection state is at " << newState << endl;
itl->currentState = newState;
stateWatches.trigger(newState);
}
void
AsioPeerConnection::
notifyError(boost::system::error_code err, std::shared_ptr<Itl> itl)
{
cerr << "Peer connection had error " << err.message() << endl;
if (err == boost::asio::error::eof
|| err == boost::asio::error::connection_reset
|| err == boost::asio::error::broken_pipe) {
itl->connection->setState(ST_CLOSED);
return;
}
//state = ST_CLOSED;
abort();
}
WatchT<Date>
AsioPeerConnection::
getTimer(Date expiry, double period,
std::function<void (Date)> toBind)
{
return MLDB::getTimer(expiry, period, StrandHolder(itl->strand), toBind);
}
void
AsioPeerConnection::
postWorkSync(std::function<void ()> work)
{
itl->strand.post(work);
}
void
AsioPeerConnection::
postWorkAsync(std::function<void ()> work)
{
itl->strand.get_io_service().post(work);
}
} // namespace MLDB
|
Tim Sherwood is about to have his photograph taken when he spies an offensive image on the wall behind. He winces. ‘Oh, get that down, I can’t have that in the background,’ Sherwood insists. The insulting item is swiftly removed from his office. ‘It’s not like it’s a trophy,’ he says. ‘You can’t have an open top parade.’
The object in question is a framed commemoration of a match played on April 29, 2013. Aston Villa 6 Sunderland 1.
Sherwood means no disrespect but it pains him that a single fixture, from almost two years ago, is still being celebrated. Not that he wouldn’t settle for a fluky 1-0 against the run of play when the teams meet in seven days’ time. It’s just that rejoicing in one gloriously ancient 90-minute spell almost sums up Villa’s dwindling expectations. Gates are down, goals are down, confidence has been low.
Tim Sherwood poses for a picture in his office at Aston Villa's training ground before talking to Sportsmail
Sherwood was in good spirits as he sat down with Daily Mail chief sports writer Martin Samuel
Sherwood, like his touchline demeanour, was full of energy during his interview with Sportsmail
Sherwood takes a minute to admire a stained glass window in his office before the interview starts
TIM SHERWOOD'S BEST BITS Read the top 10 quotes from Martin Samuel's interview with Tim Sherwood
Sherwood surveys an immaculately manicured training ground. ‘Look at those nets,’ he says. ‘Brand new.’ And then the punchline. ‘That’s the problem, they’re actually 10 years old.’
He is a serious man, though, with a serious job.
Earlier this week, Villa recorded their first league win since December 7, over West Brom. The teams meet again in an FA Cup quarter-final on Saturday. Some think of it as respite, a match without the pressure of a fight for survival. Sherwood doesn’t agree. He needs momentum, he needs to reignite the fire.
On Tuesday, Villa Park was the liveliest it has been all season, aided by Sherwood’s inability to control his emotions on the touchline. He lived the game as intensely as any fan, by turns praying or sprinting with abandon to celebrate a goal. He knows he looks like a madman.
Sherwood went through a full range of emotions during Villa's 2-1 win over West Brom on Tuesday
Sherwood celebrates with his staff after Christian Benteke's penalty sealed a vital victory for his side
Sherwood appeals to the referee after Matt Lowton was brought down by Ben Foster in stoppage time
Sherwood shows how much victory against West Brom in the Premier League meant to him at full-time
‘I could try acting,’ he says. ‘I could sit down and make little notes and everyone would say I’ve matured. But I know that’s impossible. I can’t imagine being any different 500 games in. People thought I would calm down as a player, but I didn’t.
‘The day I retired I was the same lunatic that made his debut for Watford in 1987. I can’t believe the other managers are not as emotionally involved as I am, either. They’re all like me inside.’
The night that Villa defeated West Brom, their thunder was stolen by images of Gus Poyet and Steve Bruce having to be kept apart during Sunderland’s match with Hull City.
Sherwood sympathises. ‘It happened to me once last season with Tottenham,’ he recalls. ‘We were playing Chelsea. Nearly an hour in we had them where we wanted them. Then Jan Vertonghen makes a mistake, Younes Kaboul gets sent off, and we capitulate, lose 4-0.
‘I’m hot, I’m upset. Jose Mourinho shakes hands, doesn’t say much. Steve Holland, his assistant, comes up and he’s trying to be nice. “Unlucky mate,” he says. “You played really well in the first half.” I tell him to f*** off. Lost my temper. Called him a patronising c***. I had to phone and apologise. Still fuming, but it was my mistake. He didn’t mean it as I thought. You’re not safe in the heat of that battle.
Sherwoood says that in the heat of battle he sometimes finds it hard to control his emotions
Sherwood hopes his influence has helped Villa take a step in the right direction as they battle relegation
Sherwood believes Villa have players with the quality to keep the club in the Premier League
‘When Mourinho talks about referees and campaigns, that’s calculated. He knows what he’s doing. I saw him when Chelsea scored against Tottenham last Sunday. Tottenham were doing well until that point, but the goal went in and Mourinho turned to the bench as if it was all part of some masterplan.
‘It was like he was checking his watch. “That’s strange, 40 seconds early.” He has that way. But he’s Mourinho — he can do what he wants.
‘When you’ve got a room full of trophies and you can’t get the door shut, it’s different.’
Sherwood is 31 games into his managerial career, but he’s got firm ideas about the way he wants to play and how Villa move on, providing they stay up. It’s good to hear the voice of a young, opinionated English manager, in an age when even Brentford think only an imported intellect can fulfil their ambitions. The positive crowd reaction to a more open style — and a rare win — has merely confirmed his belief Villa cannot grind out results for survival.
‘We’re like Everton,’ he explains. ‘I don’t think we’ve got a group of players who are cut out for a relegation battle. We can’t be the Crystal Palace of last year, or the West Brom of this year. Digging in, blood and thunder, lump the ball in, protecting a lead, that’s not us.
Benteke, pictured in training earlier this week, scored the winning goal for Villa against West Brom
Scott Sinclair gets down to some sprinting in training earlier in the week as Villa prepare for West Brom
Sherwood says his Villa players are more suited to a passing style of football than a direct game
TIM SHERWOOD FACTFILE PLAYING CAREER Watford (1987-89): 51 games 2 goals Norwich (1989-92): 88 games 13 goals Blackburn (1992-99): 300 games 32 goals Tottenham (1999-03): 118 games 16 goals Portsmouth (2003-04): 33 games 1 goal Coventry (2004-05): 11 games 0 goals HONOURS Blackburn - Premier League 1994-95 Portsmouth - First Division 2002-03 INTERNATIONAL CAREER England caps: 3 England debut: 3-1 v Poland, 1999 MANAGERIAL CAREER Tottenham (2013-14): P28 W14 D4 L10 Aston Villa (2015-): P4 W2 D0 L2
‘Our squad is better on the ball, they’re more suited to pushing for a place in the Europa League.
‘Still, they’ve found themselves at the wrong end of the table, so what can they do? I tell them: we do it our way. Go and get the ball. If you give it away, OK, get it back and we start again. I think it takes more courage to do that. It’s easier to destroy than create.
‘When I was at Blackburn, there were times when it was difficult. My name would be read out and there were a few groans. I didn’t care. I’d sometimes tell David Batty, “I’ll give it away more times than you’ll get it this afternoon”.
‘It sounds a strange thing to say, but what I meant was I’ll always want it. I’ll get it so much, I’ll make more mistakes than some midfield players have touches. But I’ll get a lot more right, I’ll win the ball back, and I’ll always be involved. That is what I want from my players. The courage to take the game on.
‘I think of Andros Townsend. He’ll run it into the full back nine times, but then the 10th he’ll get past and put in a cross that wins the game, or stick it straight in the top corner like he did the other night. That attitude is the only way this group will get out of trouble.’
He adds: ‘The players have a duty, a responsibility, to fix this mess. I don’t want to hear crap about how difficult it is to play at home.
‘Playing for a big club comes with pressure. Anyone can do it for a lesser team — but you have to have b******s to play for Aston Villa. This is a big club.
‘The fans think they support a big club. They come here, they don’t want to be in the relegation zone. They’ve got the hump. It’s up to the players to spark them into life.
‘People say the fans have got to get behind the team. Hold on, why must they cheer? You make them cheer. They’re the only loyal people in the game. Make the difference for them, get them on your side.
Sherwood was captain of the Blackburn team that won the Premier League title back in 1995
Sherwood is mobbed by his Tottenham team-mates after scoring against Wolves at White Hart Lane in 2002
Sherwood avoids a challenge during England's 3-1 win over Poland in a European Championship qualifier
PREMIER LEAGUE TABLE Aston Villa's win over West Brom on Tuesday moved them out of the relegation zone with 10 games left to play.
‘Blackburn was the best club I ever had because of our success, but it was a walk in the park compared to playing for Tottenham. Midweek, those boys have come in straight from a bad day in the City. There are no replica shirts, just a lot of frustration. They’re going to take it out on you if it’s not going well.
‘So when the pressure is turned up like that, have you got it? Go and get the ball, and make us play.’
It is not straightforward to galvanise a football club, particularly one that has been in decline as long as Villa. Everyone knows the owner, Randy Lerner, would sell if he could and that investment is not what it was. This torpor was reflected in the football played under Paul Lambert.
Before Sherwood arrived, Villa had scored 12 goals in 25 league games. They had possession, but did nothing with it. Christian Benteke had two league goals all season, Gabriel Agbonlahor three, the last on November 24. Sherwood lost his first game to Stoke on an injury-time penalty. The players were on the floor. It was tough.
‘Sometimes it is easy to make an impact,’ Sherwood says. ‘I remember when Harry Redknapp went to Tottenham, following Juande Ramos. The players were not allowed chips, not allowed ketchup, not allowed white bread. He saw an opportunity. “What, is that affecting their crossing?” he would say.
‘He changed a few things and immediately the place lightened up. Good results — then they’re eating out of his hand. That’s why the FA Cup game is important. We’ve got to keep moving forward. The more games we win, the easier it becomes for me to get my message across.
Sherwood (left, along with Joe Jordan) was part of Harry Redknapp's coaching staff at Tottenham
Sherwood and Redknapp deep in conversation at Tottenham's training ground in Essex back in 2008
‘What I take from Harry is that sometimes you roll the dice. He’s a gambler by nature and that comes through. If you leave everything to luck, you’re going to be unlucky. He doesn’t do that. But if you’re not 100 per cent sure, take a gamble.
‘At Southampton when I was managing Tottenham, it wasn’t going well. We needed a change. I turned around to the bench. We had Etienne Capoue, Nabil Bentaleb and Lewis Holtby. I told Nabil to warm up and I could see the others looking at each other. What, him? But that was my gamble.
‘I wasn’t 100 per cent sure of them, but I knew this kid. I’d watched him in training. Every day was like his last on earth. He would cry if he lost a five-a-side. He played and never looked back. There is a bit of that here, just having to roll it.
‘Harry was brilliant for that. Spurs are 4-0 down to Inter Milan in the San Siro, the goalkeeper’s been sent off. I’ve watched the game from upstairs and it’s hell. I come into the dressing-room at half-time, Harry’s blood pressure is rising by the minute.
‘He asks me what I think. I say the game’s gone, get Gareth Bale off, save him for the weekend because we’re playing Everton and we’ll need him. Harry’s going mad. “Get f****** Gareth off?” he says. “He’s the only f****** chance we’ve got.”
‘He keeps him on, he scores a hat-trick, gets us back to 4-3 and, if it goes another 10 minutes, we win. The kid’s career springboards from that performance.
Gareth Bale scored a hat-trick for Tottenham as they lost 4-3 against Inter in the Champions League in 2010
‘I thought I was being calm and calculated — but he’s the one in the technical area. Everyone is staring at the back of his head. Go on then, what are you going to do? He can’t be thinking of next week.’
Neither can Sherwood. He hasn’t got time to consider reputations, egos or long-term planning. He is motivated only by what he sees each day on the training field.
There has never been a better time for a young player to get his chance at Villa, because the new manager lives in the present. ‘I’ve told the players, if you’re not in the team, I can find an excuse for why you’re not playing,’ he explains. ‘But you want the truth? The other 11 are better than you. If you train properly, next week it might be your turn. If you don’t, you’ll never get the chance to show me.
‘I’m honest. I won’t bluff them. I say to the kids: make a lasting impression. I want to be asking Gordon Cowans (Villa’s Under 21 coach) about you. I don’t expect them to always be fantastic, but I need to notice they are there.
‘I was an Arsenal fan. I grew up watching Brian Talbot on the North Bank at Highbury. I loved him.
Sherwood played for and managed Spurs but grew up watching Brian Talbot (centre) play for Arsenal
Sherwood, in action for Spurs against Leeds, was known as a tough tackler throughout his career
‘Then, when I was at Watford, I was playing against him in training every day. And every day I was tackling him, flying in, didn’t care.
‘The coaches used to call me Tackler Tim, or some rubbish. One day, I put one in and he said to Graham Taylor, “Why’s he keep doing that?” I have never forgotten his answer. “Brian, you know that shirt you wear on Saturday?” he said. “That’s the shirt he wants.” He was right, too.
‘Take Jack Grealish. I’ve had lots of chats with Jack. He knows what I think. I tell him: “I will take desire over ability every day”. Obviously, the ability can’t be too low. But if you have the ability — and he has — you’ll make it if you have desire. I’ll guide him along a path, and if he follows that path, in years to come Aston Villa will be trying to hold on to him as Tottenham are trying to hold on to Harry Kane now.
‘I like players. I know players. I’m not a Smedley Side-Parting.
‘Everything they’ve got up to, I’ve got up to. I’ve been around them all my life. I can tell in 10 minutes who’s going to be difficult, who needs a cuddle, who thinks he’s Jacko. No doctors or accountants went to my school. Players went to my school. I could stand with Alan Shearer or Teddy Sheringham in the dressing-room and have a row and we all, really, spoke the same language.
Sherwood is an admirer of Villa midfielder Jack Grealish, who he believes has plenty of desire and ability
Sherwood, now 46 years old, gets stuck in during Villa training earlier in the week
Sherwood says that he 'thinks he is a leader of men' but has developed the skills over many years
‘So I didn’t come in here all guns blazing or wanting to be their headmaster. You can’t get personal these days, get your hair cut and all that nonsense. You’ve got to move with the times. I left the stick at home, and the tickling brush. Now I feel I know them a bit better. Some get a whack, others a tickle.
‘I think I can be a leader of men, but you’re not born with that attitude. In the maternity ward, it’s not girls, boys and natural leaders. You have to become that.’
Just as Sherwood will have to become the type of manager who can one day look at his watch, raise a quizzical eyebrow and everyone will believe the action is part of some brilliant design: or maybe not. What is plain is that if Villa survive, phase two begins.
‘I want to be the best manager,’ he says. ‘I don’t want to be nicking a few quid and ticking over — I want to take a club somewhere and achieve. Now, the first achievement would be keeping Villa in the Premier League, but it isn’t ultimately what I want to do.
‘I don’t want to be scrapping around; I want to take them forward. I think I did that at Tottenham. I didn’t leave a crumbling house — Mauricio Pochettino has done a good job, but he had it laid out for him, with players like Kane and Bentaleb.
Sherwood believes Mauricio Pochettino is benefiting because of his work with Harry Kane
Sherwood believes Pochettino, who led Spurs to the Capital One Cup final, has done a good job
‘If Villa stay up, then we can worry about building our philosophy, or whatever the on-trend word is these days. There’s no time for that now. We had one foot in the Championship when I arrived and this would be our greatest escape.
‘But if we overcome this we get stronger. Southampton have made it hard for one of the established teams to finish fourth. There can be a lot of movement in this league.
‘Look at how well Everton did last year, now they’re three points off us. It can go the other way.
‘Relegation candidates one season, Europa League the next.’
|
package org.ml4j.tensor;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.jvmpy.symbolictensors.MultiplicationRules;
import org.jvmpy.symbolictensors.Size;
import org.ml4j.autograd.AutogradValue;
import org.ml4j.autograd.Value;
import org.ml4j.autograd.arithmetic.operations.DifferentiableWrappedArithmeticOperations;
import org.ml4j.autograd.impl.AutogradValueImpl;
import org.ml4j.autograd.impl.AutogradValueProperties;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
public abstract class DifferentiableWrappedTensorOperations<V extends Tensor<V, D> & Value<V, D, Size>, D extends TensorOperations<D>> extends AutogradValueImpl<V, D, Size> implements AutogradValue<V, D, Size>, TensorOperations<V>, org.ml4j.autograd.DataSupplier<D>, Tensor<V, D>, DifferentiableWrappedArithmeticOperations<V, D, Size> {
public DifferentiableWrappedTensorOperations(Supplier<D> data, AutogradValueProperties<Size> properties) {
super(properties, data);
}
public <X extends AutogradValue<X, Y, Z>, Y, Z> DifferentiableWrappedTensorOperations(AutogradValue<X, Y, Z> other, Function<Y, D> dataMapper, Function<Z, Size> contextMapper, Function<X, V> valueMapper, Function<V, X> valueReverseMapper, Supplier<Optional<V>> nativeGradientSupplier) {
super(other, dataMapper, contextMapper, valueMapper, valueReverseMapper, nativeGradientSupplier);
}
public DifferentiableWrappedTensorOperations(V other) {
super(other);
}
@Override
public V add(V other) {
return applyBinaryOperator(other, D::add, (g, p) -> g, (g, p) -> g, "add:" + size() + ":" + other.context(), (f, s) -> getMappedContext(f, s));
}
@Override
public V mul(V other) {
return applyBinaryOperator(other, D::mul, (g, p) -> g.mul(p.getRight()), (g, p) -> g.mul(p.getLeft()), "mul:" + size() + ":" + other.context(), (f, s) -> getMappedContext(f, s));
}
@Override
public boolean isNativeGradient() {
return data().get().isNativeGradient();
}
@Override
public V applyBinaryOperator(V other, BinaryOperator<D> forward, BiFunction<V, Pair<V, V>, V> backThis, BiFunction<V, Pair<V, V>, V> backOther, String op, BinaryOperator<Size> contextMapper) {
if (!size().getDimensions().equals(other.size().getDimensions())) {
try {
Size broadcastSize = MultiplicationRules.getBroadcast(size(), other.size());
if (broadcastSize.getDimensions().equals(size().getDimensions()) || broadcastSize.getDimensions().equals(other.size().getDimensions())) {
float scale1 = (float) broadcastSize.numel() / (float) size().numel();
float scale2 = (float) broadcastSize.numel() / (float) other.size().numel();
return super.applyBinaryOperator(other, forward, (g, p) -> getSub(backThis.apply(g, p), size(), scale1).mul(scale1), (g, p) -> getSub(backOther.apply(g, p), other.size(), scale2).mul(scale2), op, (f, s) -> broadcastSize);
} else {
throw new IllegalStateException();
}
} catch (IllegalArgumentException e) {
// Size cannot be broadcast, perhaps it's matMul.
}
}
return super.applyBinaryOperator(other, forward, backThis, backOther, op, contextMapper);
}
protected abstract V getSub(V other, Size size, float scale);
@Override
public V relu() {
return applyUnaryOperator(D::relu, (g, v) -> g.mul(v.gt(0)), "gt", s -> s);
}
@Override
public V view(Size size) {
if (size.numel() != numel()) {
throw new IllegalArgumentException("Number of elements do not match");
}
return applyUnaryOperator(v -> v.view(size), (g, v) -> g.view(size()), "view", s -> size);
}
@Override
public V norm() {
return applyUnaryOperator(t -> t.norm(), (g, v) -> backwardNotYetImplemented("norm"), "norm", s -> new Size());
}
@Override
public V sum(int...axes) {
return applyUnaryOperator(t -> t.sum(axes), (g, v) -> { if (axes.length > 0) throw new UnsupportedOperationException(); return v.mul(0).add(1).mul(g); }, "sum", s -> (axes.length == 0) ? new Size() : (axes.length == 1 && axes[0] == 0) ? new Size(1, size().dimensions()[1]) : new Size(size().dimensions()[0], 1) );
}
@Override
public V argMax(int i) {
return applyUnaryOperator(t -> t.argMax(i), (g, v) -> backwardNotYetImplemented("argMax"), "sum", s -> new Size() );
}
@Override
public V argMax() {
return applyUnaryOperator(t -> t.argMax(), (g, v) -> backwardNotYetImplemented("argMax"), "sum", s -> new Size() );
}
@Override
public V mean() {
return applyUnaryOperator(t -> t.mean(), (g, v) -> { return v.mul(0).add(1).mul(g).div(v.numel()); }, "mean", s -> new Size());
}
public V backwardNotYetImplemented(String op) {
throw new UnsupportedOperationException(op);
}
public V t() {
return applyUnaryOperator(D::t, (g, v) -> g.t(), "t", s -> s.t());
}
@Override
public V sigmoid() {
return applyUnaryOperator(D::sigmoid, (g, v) -> g.mul(sigGrad(v.getDataAsFloatArray()[0])), "sigmoid", s -> s);
}
@Override
public V exp() {
return applyUnaryOperator(D::exp, (g, v) -> backwardNotYetImplemented("exp"), "exp", s -> s);
}
@Override
public V log() {
return applyUnaryOperator(D::log, (g, v) -> backwardNotYetImplemented("log"), "log", s -> s);
}
@Override
public V getTensor(int...indexes) {
int[] inds = new int[indexes.length];
int nonOneDimensions = 0;
for (int i = 0; i < indexes.length; i++) {
inds[i] = indexes[i] == -1 ? size().dimensions()[i] : 1;
if (inds[i] != 1) {
nonOneDimensions ++;
}
}
int[] indsNonOne = new int[nonOneDimensions];
int ind = 0;
for (int i = 0; i < indexes.length; i++) {
if (inds[i] != 1) {
indsNonOne[ind] = inds[i];
ind++;
}
}
return applyUnaryOperator(t -> t.getTensor(indexes), (g, v) -> backwardNotYetImplemented("getTensor"), "getTensor", s -> new Size(indsNonOne));
}
@Override
public V getTensor(int[]...ranges) {
Pair<int[], int[][]> indsAll = getTensorRanges(size(), ranges);
int[] inds = indsAll.getLeft();
int[][] inds2 = indsAll.getRight();
return applyUnaryOperator(t -> t.getTensor(ranges), (g, v) -> {V a = createAutogradValue(additiveIdentity(), new AutogradValueProperties<Size>().setContext(v.context()).setRegistry(properties().getRegistry()).setChildren(g.getGradNode().prev()).setNext(g.getGradNode().next()).setRequires_grad(g.requires_grad()).setCreate_graph(g.create_graph()).setName("rangeBackward")); var b = g.getTensor(ranges); a.putTensor(b, ranges); return a; }, "getTensor", s -> new Size(inds));
}
private Pair<int[], int[][]> getTensorRanges(Size size, int[]...ranges) {
int[] inds = new int[ranges.length];
int[][] inds2 = new int[inds.length][2];
List<Integer> is = new ArrayList<>();
for (int i = 0; i < ranges.length; i++) {
if (ranges[i][0] == -1 && ranges[i][1] == -1) {
inds[i] = size.dimensions()[i];
is.add(inds[i]);
inds2[i][0] = 0;
inds2[i][1] = size.dimensions()[i];;
} else {
int l = ranges[i][0] == -1 ? 0 : (ranges[i][0]);
int r = ranges[i][1] == -1 ? size.dimensions()[i] : (ranges[i][1]);
inds2[i][0] = l;
inds2[i][1] = r;
inds[i] = r - l;
is.add(inds[i]);
}
}
return new ImmutablePair<>(inds, inds2);
}
@Override
public void putTensor(V tensor, int[]...ranges) {
int[] inds = new int[ranges.length];
for (int i = 0; i < ranges.length; i++) {
if (ranges[i][0] == -1 && ranges[i][1] == -1) {
inds[i] = size().dimensions()[i];
} else {
int l = ranges[i][0] == -1 ? 0 : (ranges[i][0]);
int r = ranges[i][1] == -1 ? size().dimensions()[i] : (ranges[i][1]);
inds[i] = r - l;
}
}
applyInlineUnaryOperator(t -> { t.putTensor(tensor.data().get(), ranges); return t; }, "putTensor");
}
@Override
public void putTensor(V tensor, int...indexes) {
applyInlineUnaryOperator(t -> { t.putTensor(tensor.data().get(), indexes); return t; }, "putTensor");
}
@Override
public V cloneTensor() {
return applyUnaryOperator(D::cloneTensor, (g, v) -> this.backwardNotYetImplemented("cloneTensor"), "cloneTensor", s -> s);
}
@Override
public V reshape(Size size) {
V result = applyUnaryOperator(f -> f.reshape(size), (g, v) -> g.reshape(size()), "reshape", s -> size);
result.properties().addLink(this.getValueNode());
this.properties().addLink(result.getValueNode());
return result;
}
@Override
public V resize_(Size size) {
V result = applyInlineUnaryOperator(t -> t.resize_(size), "resize_");
this.properties().setContext(size);
return result;
}
@Override
public V mul_(V other) {
return applyInlineBinaryOperator(other, D::mul_, "mul_");
}
@Override
public V div_(V other) {
return applyInlineBinaryOperator(other, D::div_, "div_");
}
@Override
public V mul_(float v) {
return applyInlineUnaryOperator(t -> t.mul_(v), "mul");
}
@Override
public V div_(float v) {
return applyInlineUnaryOperator(t -> t.div_(v), "div");
}
@Override
public V sub_(float v) {
return applyInlineUnaryOperator(t -> t.sub_(v), "sub");
}
@Override
public V add_(float v) {
return applyInlineUnaryOperator(t -> t.add_(v), "add");
}
@Override
public void put(int index, float v) {
applyInlineUnaryOperator(t -> { t.put(index, v); return t; }, "put");
}
@Override
public void put(float v, int...indexes) {
applyInlineUnaryOperator(t -> { t.put(v, indexes); return t; }, "put");
}
@Override
public float get(int index) {
return data().get().get(index);
}
@Override
public float get(int... indexes) {
return data().get().get(indexes);
}
@Override
public V matmul(V other) {
Size[] sizes = MultiplicationRules.matmul(size(), other.size());
return this.applyBinaryOperator(other, (f, s) -> f.reshape(sizes[0]).matmul(s.reshape(sizes[1])).reshape(sizes[3]), (g, p) -> {
return g.reshape(sizes[2]).matmul(p.getRight().reshape(sizes[1]).t()).reshape(size());
}, (g, p) -> {
return g.reshape(sizes[2]).t().matmul(p.getLeft().reshape(sizes[0])).t().reshape(other.size());
}, "matmul", (f, s) -> {
Size result = sizes[3];
int[] dims = result.dimensions();
int [] firstDims = new int[dims.length- 1];
for (int i = 0; i < firstDims.length; i++) {
firstDims[i] = dims[i];
}
return new Size(new Size(firstDims), new Size(dims[dims.length - 1]));
});
}
@Override
public Size getMappedContext(Size f, Size s) {
return MultiplicationRules.getBroadcast(f, s);
}
@Override
public V bernoulli() {
return applyUnaryOperator(D::bernoulli, (g, v) -> g, "gt", s -> s);
}
@Override
public int numel() {
return size().numel();
}
@Override
public V columnSums() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public V normal_(float v1, float v2) {
return applyInlineUnaryOperator(t -> t.normal_(v1, v2), "normal");
}
@Override
public V fill_(float value) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int size(int dim) {
if (dim == -1) {
return size().numel();
} else {
return size().getDimensions().get(dim);
}
}
@Override
public Size size() {
return context();
}
@Override
public V zero_() {
return applyInlineUnaryOperator(t -> t.zero_(), "zero");
}
@Override
public V view(int... dims) {
if (dims.length == 1 && dims[0] == -1) {
return applyUnaryOperator(t -> t.view(-1), (g, v) -> g.view(size()), "view", s -> new Size(s.numel()));
}
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public V rowSums() {
throw new UnsupportedOperationException("Not yet implemented");
}
public float sig(float x) {
return 1f / (1f + (float)Math.exp(-x));
}
public float sigGrad(float x) {
float s = sig(x);
return s * ( 1 - s);
}
@Override
public float[] getDataAsFloatArray() {
return data().get().getDataAsFloatArray();
}
}
|
<gh_stars>0
#!/usr/bin/env python
#
# VMAccess extension
#
# Copyright 2014 Microsoft Corporation
#
# 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.
#
# Requires Python 2.7+
import os
import sys
import imp
import base64
import re
import json
import platform
import shutil
import time
import traceback
from Utils.WAAgentUtil import waagent
import Utils.HandlerUtil as Util
#Define global variables
ExtensionShortName = 'VMAccess'
BeginCertificateTag = '-----BEGIN CERTIFICATE-----'
EndCertificateTag = '-----END CERTIFICATE-----'
OutputSplitter = ';'
def main():
waagent.LoggerInit('/var/log/waagent.log','/dev/stdout')
waagent.Log("%s started to handle." %(ExtensionShortName))
waagent.MyDistro = waagent.GetMyDistro()
for a in sys.argv[1:]:
if re.match("^([-/]*)(disable)", a):
disable()
elif re.match("^([-/]*)(uninstall)", a):
uninstall()
elif re.match("^([-/]*)(install)", a):
install()
elif re.match("^([-/]*)(enable)", a):
enable()
elif re.match("^([-/]*)(update)", a):
update()
def install():
hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName)
hutil.do_parse_context('Uninstall')
hutil.do_exit(0,'Install','Installed','0', 'Install Succeeded')
def enable():
hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName)
hutil.do_parse_context('Enable')
try:
protect_settings = hutil._context._config['runtimeSettings'][0]['handlerSettings'].get('protectedSettings')
reset_ssh = protect_settings.get('reset_ssh')
# check port each time the VM boots up
if reset_ssh:
_open_ssh_port()
hutil.log("Succeeded in check and open ssh port.")
hutil.exit_if_enabled()
remove_user = protect_settings.get('remove_user')
if reset_ssh:
_reset_sshd_config("/etc/ssh/sshd_config")
hutil.log("Succeeded in reset sshd_config.")
if remove_user:
_remove_user_account(remove_user, hutil)
_set_user_account_pub_key(protect_settings, hutil)
hutil.do_exit(0, 'Enable', 'success','0', 'Enable succeeded.')
except Exception, e:
hutil.error("Failed to enable the extension with error: %s, stack trace: %s" %(str(e), traceback.format_exc()))
hutil.do_exit(1, 'Enable','error','0', 'Enable failed.')
def uninstall():
hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName)
hutil.do_parse_context('Uninstall')
hutil.do_exit(0,'Uninstall','success','0', 'Uninstall succeeded')
def disable():
hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName)
hutil.do_parse_context('Disable')
hutil.do_exit(0,'Disable','success','0', 'Disable Succeeded')
def update():
hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName)
hutil.do_parse_context('Upadate')
hutil.do_exit(0,'Update','success','0', 'Update Succeeded')
def _remove_user_account(user_name, hutil):
try:
sudoers = _get_other_sudoers(user_name)
waagent.MyDistro.DeleteAccount(user_name)
_save_other_sudoers(sudoers)
except Exception, e:
waagent.AddExtensionEvent(name=hutil.get_name(),
op=waagent.WALAEventOperation.Enable,
isSuccess=False,
message="(02102)Failed to remove user.")
raise Exception("Failed to remove user {0}".format(e))
def _set_user_account_pub_key(protect_settings, hutil):
ovf_xml = waagent.GetFileContents('/var/lib/waagent/ovf-env.xml')
ovf_env = waagent.OvfEnv().Parse(ovf_xml)
# user name must be provided if set ssh key or password
if not protect_settings or not protect_settings.has_key('username'):
return
user_name = protect_settings['username']
user_pass = <PASSWORD>('password')
cert_txt = protect_settings.get('ssh_key')
if(not(user_pass) and not(cert_txt) and not(ovf_env.SshPublicKeys)):
raise Exception("No password or ssh_key is specified.")
#Reset user account and password, password could be empty
sudoers = _get_other_sudoers(user_name)
error_string= waagent.MyDistro.CreateAccount(user_name, user_pass, None, None)
_save_other_sudoers(sudoers)
if error_string != None:
waagent.AddExtensionEvent(name=hutil.get_name(),
op=waagent.WALAEventOperation.Enable,
isSuccess=False,
message="(02101)Failed to create the account or set the password.")
raise Exception("Failed to create the account or set the password: " + error_string)
hutil.log("Succeeded in create the account or set the password.")
#Allow password authentication if user_pass is provided
if user_pass is not None:
_allow_password_auth()
#Reset ssh key with the new public key passed in or reuse old public key.
if cert_txt or len(ovf_env.SshPublicKeys) > 0:
try:
pub_path = os.path.join('/home/', user_name, '.ssh','authorized_keys')
ovf_env.UserName = user_name
if cert_txt:
_save_cert_str_as_file(cert_txt, 'temp.crt')
else :
for pkey in ovf_env.SshPublicKeys:
if pkey[1]:
shutil.copy(os.path.join(waagent.LibDir, pkey[0] + '.crt'), os.path.join(os.getcwd(),'temp.crt'))
break
pub_path = ovf_env.PrepareDir(pub_path)
retcode = waagent.Run(waagent.Openssl + " x509 -in temp.crt -noout -pubkey > temp.pub")
if retcode > 0:
raise Exception("Failed to generate public key file.")
waagent.MyDistro.sshDeployPublicKey('temp.pub',pub_path)
waagent.MyDistro.setSelinuxContext(pub_path,'unconfined_u:object_r:ssh_home_t:s0')
waagent.ChangeOwner(pub_path, user_name)
os.remove('temp.pub')
os.remove('temp.crt')
hutil.log("Succeeded in resetting ssh_key.")
except:
waagent.AddExtensionEvent(name=hutil.get_name(),
op=waagent.WALAEventOperation.Enable,
isSuccess=False,
message="(02100)Failed to reset ssh key.")
def _get_other_sudoers(userName):
sudoersFile = '/etc/sudoers.d/waagent'
if not os.path.isfile(sudoersFile):
return None
sudoers = waagent.GetFileContents(sudoersFile).split("\n")
sudoers = filter(lambda x : userName not in x, sudoers)
return sudoers
def _save_other_sudoers(sudoers):
sudoersFile = '/etc/sudoers.d/waagent'
if sudoers is None:
return
waagent.AppendFileContents(sudoersFile, "\n".join(sudoers))
os.chmod("/etc/sudoers.d/waagent", 0440)
def _allow_password_auth():
configPath = '/etc/ssh/sshd_config'
config = waagent.GetFileContents(configPath).split("\n")
_set_sshd_config(config, "PasswordAuthentication", "yes")
_set_sshd_config(config, "ChallengeResponseAuthentication", "yes")
waagent.ReplaceFileContentsAtomic(configPath, "\n".join(config))
def _set_sshd_config(config, name, val):
notfound = True
for i in range(0, len(config)):
if config[i].startswith(name):
config[i] = "{0} {1}".format(name, val)
notfound = False
elif config[i].startswith("Match"):
#Match block must be put in the end of sshd config
break
if notfound:
config.insert(i, "{0} {1}".format(name, val))
return config
def _reset_sshd_config(sshd_file_path):
distro = platform.dist()
distro_name = distro[0]
version = distro[1]
config_file_path = os.path.join(os.getcwd(), 'resources', '%s_%s' %(distro_name,version))
if not(os.path.exists(config_file_path)):
config_file_path = os.path.join(os.getcwd(), 'resources', '%s_%s' %(distro_name,'default'))
if not(os.path.exists(config_file_path)):
config_file_path = os.path.join(os.getcwd(), 'resources', 'default')
_backup_sshd_config(sshd_file_path)
if distro_name == "CoreOS":
# Parse sshd port from config_file_path
sshd_port = 22
regex = re.compile(r"^Port\s+(\d+)", re.VERBOSE)
with open(config_file_path) as f:
for line in f:
match = regex.match(line)
if match:
sshd_port = match.group(1)
break
# Prepare cloud init config for coreos-cloudinit
cfg_tempfile = "/tmp/cloudinit.cfg"
cfg_content = "#cloud-config\n\n"
# Overwrite /etc/ssh/sshd_config
cfg_content += "write_files:\n"
cfg_content += " - path: {0}\n".format(sshd_file_path)
cfg_content += " permissions: 0600\n"
cfg_content += " owner: root:root\n"
cfg_content += " content: |\n"
for line in GetFileContents(config_file_path).split('\n'):
cfg_content += " {0}\n".format(line)
# Change the sshd port in /etc/systemd/system/sshd.socket
cfg_content += "\ncoreos:\n"
cfg_content += " units:\n"
cfg_content += " - name: sshd.socket\n"
cfg_content += " command: restart\n"
cfg_content += " content: |\n"
cfg_content += " [Socket]\n"
cfg_content += " ListenStream={0}\n".format(sshd_port)
cfg_content += " Accept=yes\n"
SetFileContents(cfg_tempfile, cfg_content)
Run("coreos-cloudinit -from-file " + cfg_tempfile, chk_err=False)
os.remove(cfg_tempfile)
else:
shutil.copyfile(config_file_path, sshd_file_path)
waagent.MyDistro.restartSshService()
def _backup_sshd_config(sshd_file_path):
if(os.path.exists(sshd_file_path)):
backup_file_name = '%s_%s' %(sshd_file_path, time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
shutil.copyfile(sshd_file_path, backup_file_name)
def _save_cert_str_as_file(cert_txt, file_name):
cert_start = cert_txt.index(BeginCertificateTag)
if(cert_txt >= 0):
cert_txt = cert_txt[cert_start + len(BeginCertificateTag):]
cert_end = cert_txt.index(EndCertificateTag)
if(cert_end >= 0):
cert_txt = cert_txt[:cert_end]
cert_txt = cert_txt.strip()
cert_txt = "{0}\n{1}\n{2}\n".format(BeginCertificateTag, cert_txt, EndCertificateTag)
waagent.SetFileContents(file_name, cert_txt)
def _open_ssh_port():
_del_rule_if_exists('INPUT -p tcp -m tcp --dport 22 -j DROP')
_del_rule_if_exists('INPUT -p tcp -m tcp --dport 22 -j REJECT')
_del_rule_if_exists('INPUT -p -j DROP')
_del_rule_if_exists('INPUT -p -j REJECT')
_insert_rule_if_not_exists('INPUT -p tcp -m tcp --dport 22 -j ACCEPT')
_del_rule_if_exists('OUTPUT -p tcp -m tcp --sport 22 -j DROP')
_del_rule_if_exists('OUTPUT -p tcp -m tcp --sport 22 -j REJECT')
_del_rule_if_exists('OUTPUT -p -j DROP')
_del_rule_if_exists('OUTPUT -p -j REJECT')
_insert_rule_if_not_exists('OUTPUT -p tcp -m tcp --dport 22 -j ACCEPT')
def _del_rule_if_exists(rule_string):
match_string = '-A %s' %rule_string
cmd_result = waagent.RunGetOutput("iptables-save")
while cmd_result[0] == 0 and (rule_string in cmd_result[1]):
waagent.Run("iptables -D %s" %rule_string)
cmd_result = waagent.RunGetOutput("iptables-save")
def _insert_rule_if_not_exists(rule_string):
match_string = '-A %s' %rule_string
cmd_result = waagent.RunGetOutput("iptables-save")
if cmd_result[0] == 0 and (rule_string not in cmd_result[1]):
waagent.Run("iptables -I %s" %rule_string)
if __name__ == '__main__' :
main()
|
Induction with Lopinavir-Based Treatment Followed by Switch to Nevirapine-Based Regimen versus Non-Nucleoside Reverse Transcriptase Inhibitors-Based Treatment for First Line Antiretroviral Therapy in HIV Infected Children Three Years and Older
Background The World Health Organization recommends non-nucleoside reverse transcriptase inhibitors (NNRTIs)-based antiretroviral therapy (ART) for children three years and older. In younger children, starting ART with lopinavir boosted with ritonavir (LPVr) results in lower risk of virological failure, but data in children three years and older are scarce, and long-term ART with LPVr is problematic in resource-poor settings. Methodology Retrospective cohort of children three years and older who started triple ART including LPVr or a NNRTI between 2007 and 2013 in a rural setting in India. Children who started LPVr were switched to nevirapine-based ART after virological suppression. We analysed two outcomes, virological suppression (HIV-RNA <400 copies/ml) within one year of ART using logistic regression, and time to virological failure (HIV-RNA >1000 copies/ml) after virological suppression using Cox proportional hazard regression. A sensitivity analysis was performed using inverse probability of treatment weighting (IPTW) based of propensity score methods. Findings Of 325 children having a viral load during the first year of ART, 74/83 (89.2%) in the LPVr group achieved virological suppression versus 185/242 (76.5%) in the NNRTI group. In a multivariable analysis, the use of LPVr-based ART was associated with higher probability of virological suppression (adjusted odds ratio 3.19, 95% confidence interval 1.11–9.13). After IPTW, the estimated risk difference was 12.2% (95% CI, 2.9–21.5). In a multivariable analysis including 292 children who had virological suppression and available viral loads after one year of ART, children switched from LPVr to nevirapine did not have significant higher risk of virological failure (adjusted hazard ratio 1.18, 95% CI 0.36–3.81). Conclusions In a cohort of HIV infected children three years and older in a resource-limited setting, an LPVr induction- nevirapine maintenance strategy resulted in more initial virological suppression and similar incidence of virological failure after initial virological suppression than NNRTI-based regimens.
Introduction
Due to higher viral loads, pharmacokinetic variability and suboptimal adherence because of complex regimens and frequent dosing adjustments, suppression of viral replication after initiation of antiretroviral therapy (ART) is more difficult to achieve in children than in adults . Compared with non-nucleoside reverse transcriptase inhibitors (NNRTIs), protease inhibitors (PIs) have a higher genetic barrier . Studies performed in adults in resourcelimited settings show that boosted PI-based regimens result in less NRTI resistances . In children ,3 years, randomized control trials have demonstrated that the use of lopinavir boosted with ritonavir (LPVr) based regimens has lower risk of virological failure than ART containing nevirapine (NVP) . In children .3 years, observational studies in resource-limited setting suggest that the use of PI-based ART is also associated with lower risk of virological failure, but data are scarce .
Once virological suppression is achieved, the risk of virological failure of ART with NNRTIs is considerably reduced . In children taking PI-based regimens, switching to a NNRTI-based regimen after virological suppression can result in multiple benefits, such as alignment with adult ART, lower cost, better metabolic profile, simplification of ART with fixed-dose combinations, and preserving PIs for second line treatment . In this study, we compared the virological response of children who received NNRTI-based ART with those treated with LPVr-based ART followed by switch to NVP-based treatment in an HIV cohort study in India.
Methods
This study was approved by the Ethical Committee of the Rural Development Trust (RDT) Hospital. Written informed consent was given by caretakers for their information to be stored in the study database and used for research.
Setting
The study was performed in Anantapur, a district situated in the South border of Andhra Pradesh, India. Anantapur has a population of approximately four million people, and 72% of them live in rural areas . RDT is a non-governmental organization that provides medical care to HIV infected people free of charge, including medicines, consultations, and hospital admission charges. In our setting, the HIV epidemic is largely driven by heterosexual transmission and it is characterized by poor socio-economic conditions and high levels of illiteracy . Although the vast majority of children acquire HIV perinatally, 8% of female children acquire HIV through sexual contacts and 90% of them are diagnosed after aged 18 months. Near half of children have lost one or both of their parents .
Study design and definitions of variables of interest
The Vicente Ferrer HIV Cohort Study (VFHCS) is an open cohort study of all HIV infected patients who have attended Bathalapalli RDT Hospital. The baseline characteristics of the cohort have been described in detail elsewhere . The cohort is fairly representative of the HIV population in the district, as it covers approximately 70% of all HIV infected people registered in the district . For this study, we selected HIV infected children aged 3 to 16 years who started first-line ART from January 1 st 2007 to December 31 st 2013 from the VFHCS database. The selection of patients from the database was executed on June 14 th 2014 (end of the follow-up period).
ART was started by clinical criteria (clinical stage 3 or 4 of the World Health Organization ) or by immunological criteria (CD4 count ,750 cells/ml or ,20% in children aged 36-59 months, and CD4 count ,350 cells/ml in children aged .59 months) according to the Indian National Guidelines . Children started ART with two NRTIs and a NNRTI (NVP or efavirenz) or LPVr. Children who started LPVr were switched to a NVP-based regimen after achieving virological suppression. To facilitate dose calculations, we used weight band-based dosing of paediatric LPVr tablets (100 mg/25 mg) to achieve an approximate dose of 300 mg/m 2 /dose (10-20 kg, 2-0-2; 20-30 kg, 3-0-3; .30 kg, 4-0-4) . Paediatric LPVr tablets were substituted by larger adult tablets (200 mg/50 mg) if the child was able to swallow them (in these cases, the dosing in the 20-30 kg band was 2-0-1 adult tablets). Caretakers and children were instructed not to break LPVr tablets. We did not use liquid formulation of LPVr due to its poorer palatability, and cold-chain requirements. Other anti-retroviral drugs were given as per WHO and National guidelines .
Viral load was performed every six months after ART initiation. High viral load at baseline was defined as having .100,000 copies/ml of HIV-RNA . Initial virological suppression was defined as having ,400 copies/ml of HIV-RNA during the first year of ART. Following the WHO definition, virological failure was defined as having .1,000 copies/ml of HIV-RNA after six months of ART in two consecutive viral load determinations . However, children having a single viral load .1,000 copies/ml only in the last viral load determination were considered to have virological failure.
Designation of the community of patients was performed by self-identification. Scheduled caste community is marginalised in the traditional Hindu caste hierarchy and, therefore, suffers social and economical exclusion and disadvantage . Scheduled tribe community is generally geographically isolated with limited economical and social contact with the rest of the population . Scheduled castes and scheduled tribes are considered socially disadvantaged communities and are supported by positive discrimination schemes operated by the Government of India .
Clinical staging was performed following WHO guidelines for HIV disease in children .
In HIV infected children ,5 years, the CD4 lymphocyte percentage has generally been preferred for monitoring the immune status because of the variability of the CD4 cell count during the first years of life . However, an analysis of the HIV Paediatric Prognostic Markers Collaborative Study (HPPMCS) demonstrated that the CD4 percentage provides little or no additional prognostic value compared with the CD4 cell count in children . Therefore, the immune status of children was calculated using the 12-month risk of AIDS used by the HPPMCS, which uses the CD4 cell count and the age of children to calculate the level of immunodeficiency (i.e., high 12-month risk of AIDS indicates low CD4 cell counts for the age and vice versa) . Because of the small number of older children included in the HPPMCS, children older than 12 years were considered to be 12 years old to calculate the 12-month AIDS risk .
Statistical analysis
To compare the effectiveness of NNRTI-based ART (NNRTI group) versus LPVr-based ART followed by switch to NVP-based ART after achieving virological suppression (LPVr induction-NVP maintenance group), we performed two analyses. For the first analysis, we studied the proportion of children who achieved virological suppression (HIV-RNA ,400 copies/ml) during the first year of ART. Secondly, we performed a time-to-event analysis from ART initiation to virological failure among those children who achieved virological suppression and had available viral loads after one year of ART.
Continuous variables were compared using the rank sum test and categorical variables were compared using the x 2 test. Univariate and multivariable analysis of factors associated with initial virological suppression were performed using logistic regression. Univariate and multivariable analysis of factors associated with time to virological failure after initial virological suppression were performed using Cox proportional hazard regression. To include all children in the multivariable models, missing values were imputed using multiple imputations by chained equation assuming missing at random .
In a sensitivity analysis to minimize the effect of confounding and obtain an unbiased estimate of the treatment effect, differences in baseline characteristics of the two groups were balanced using propensity score methods to estimate the average treatment effect. To include non-linear effects and interactions, propensity scores were estimated via boosted models using the ''twang'' package in the R statistical computing environment (R Foundation for Statistical Computing, Vienna, Austria) . To select the optimal interation of generalized boosted models, we set to minimize the means of the absolute standardized difference . The propensity scores were used to estimate the inverse probability of treatment weights (IPTW) . As two variables had missing values, multiple imputations were performed to obtain twenty complete datasets. IPTW were computed for each dataset and then, we calculated the average of the IPTWs . These sampling weights were used to compare the initial virological suppression and the time to virological failure of the two groups using robust variance to account for the weighted nature of the sample .
Except for the estimation of propensity scores, the statistical analysis was performed using Stata Statistical Software (Stata Corporation. Release 12.1, College Station, Texas, USA).
Results
During the study period, 466 children started ART. 55 children were excluded because they died or were lost to follow up before having a viral load determination (10 in the LPVr induction-NVP maintenance group and 45 in the NNRTI group). Although previous exposure to NVP was not an exclusion criterion, none of the caretakers of children included in the study referred previous exposure to NVP.
Eighty-six children who had viral load determinations after one year of ART but not during the first year were not included in the first analysis. Therefore, 325 were included in the analysis of virological suppression during the first year of ART, 83 in the LPVr induction-NVP maintenance group and 242 in the NNRTI group (205 were on NVP and 37 were on efavirenz). In the LPVr induction-NVP maintenance group, the median duration of LPVr before switch to NVP was 213 days (interquartile range 180-250). Differences between the two groups are presented in Table 1. In the second analysis of time to virological failure, we included 292 children who achieved virological suppression and had viral load determination after one year of ART, 66 in the LPVr induction-NVP maintenance group and 226 in the NNRTI group (197 were on NVP and 29 were on efavirenz). Differences between the two groups were similar to the ones found in the analysis of initial virological suppression ( Table 3). The Kaplan-Meier estimates of the incidence of virological failure showed no significant differences between the two groups ( Figure 1). Univariate and multivariable analysis of factors associated with initial virological failure are presented in Table 4. In the multivariable analysis with multiple imputation of missing values of the baseline viral load and the 12-month AIDS risk, we did not find statistically significant differences in time to virological failure between the LPVr induction-NVP maintenance group and the NNRTI group (adjusted hazard ratio 1.18, 95% CI 0.36-3.81). In sensitivity analyses, removing high baseline viral load from the model and imputing only missing values of 12-month AIDS risk (aHR 1.00, 95% CI 0.35-2.91) or using only complete cases (aHR 0.98, 95% CI 0.34-2.83) showed similar results. In the IPTW model, we also did not find statistically significant differences in time to virological failure between the LPVr induction-NVP maintenance group and the NNRTI group (HR 1.48, 95% CI 0.54-4.01; p-value = 0.443).
Among 71 children in the NNRTI group and 12 in the LPVr induction-NVP maintenance group who had virological failure, genotypic resistance testing was available in 44 children of the NNRTI group and in three of the LPVr induction-NVP maintenance group ( Table 5). The median time to virological failure was 395 days (interquartile range 279-731) in the NNRTI group and 245.5 days (IQR, 211.5-556) in the LPVr induction-NVP maintenance group. While in the LPVr induction-NVP maintenance group only one child had two-class resistance (NNRTI and NRTI), 36 (82%) children in the NNRTI group had two-class resistance.
Discussion
In this cohort study using routine clinical data of children three years and older from a resource-limited setting, the use of LPVrbased ART was associated with an increased probability of initial virological suppression and a subsequent switch from LPVr to NVP was not associated with a higher risk of virological failure compared with children starting NNRTI-based ART. The results of this study are in contrast with the 2013 guidelines of the WHO, which recommend NNRTI-based regimens for first line ART in children three years and older . If our findings are confirmed in other settings, the results of this study could have important public health implications to help reduce virological failures among children starting ART in developing countries.
The higher proportion of children achieving initial virological suppression with LPVr induction therapy is in accordance with an international multisite clinical trial in children younger than three years . In this clinical trial, children in the NVP group had higher risk of virological failure, and those who experienced virological failure had more drug resistances . In our study, we observed fewer resistances in the LPVr induction-NVP maintenance group too, but the number of children with available drug resistance testing was small. While protease inhibitors have a relatively high barrier to the development of resistance, there are several single-gene mutations that lead to NNRTI resistance. NNRTI resistance occurs early after starting ART, when viral load and viral replication are high and, therefore, the chances of development of NNRTI mutations are also higher . Once the viral load is low, the risk of developing NNRTI mutations is considerably reduced. After virological suppression, the incidence of virological failure was similar in both groups, indicating that children switched from LPVr to NVP-based regimens did not have higher risk of virological failure than those children who started ART with NNRTI-based regimens and achieved virological suppression. However, in our study none of the children was exposed to NVP for prevention of vertical transmission, so switching from LPVr to NVP in previously exposed children may require more intense virological monitoring . Viral load monitoring is not readily available in developing countries, so the implementation of this induction-maintenance strategy might be problematic where viral load is not available. However, the 2013 WHO guidelines, which recommend using viral load monitoring in HIV patients on ART, and the commercialization of new low-cost and simple viral load technologies might lead National HIV programmes in low-and middle-countries to scale-up viral load monitoring in the near future . On the other hand, the majority of children in our study received six to nine months of LPVr-based ART before switch to NVP-based regimens, resulting in lower rates of virological failure and resistance. In setting where viral load is not available, induction therapy with LPVr-based ART during six or nine months followed by switch to NVP-based ART instead of ART initiation with NNRTI-based regimens could be beneficial, but new studies are needed to confirm this hypothesis. The study has some limitations. Our results reflect the ''real life'' of HIV infected children in a resource-limited setting. However, unlike clinical trials, observational studies can be biased due to unknown confounders. The selection of treatment was not randomized, so factors not included in the multivariable analyses might have influenced the outcomes of study. In addition, we did not have complete data for all cases; particularly many children had missing values of baseline HIV viral load. Nevertheless, we performed extensive sensitivity analyses, which showed similar results with different statistical methods. Our findings need to be confirmed by observational studies performed in other settings or, ideally, by a randomized clinical trial.
Conclusions
In a large cohort of HIV infected children three years and older from a resource-limited setting and without previous exposure to NVP, starting ART with LPVr-based regimens was associated with higher probability of virological suppression than starting with NNRTI-based regimens. Once virological suppression was achieved, children switched from LPVr to NVP-based treatment did not have a higher risk of virological failure than children who started NNRTI-based ART and achieved virological suppression. If these results are confirmed in other settings, this LPVr induction-NVP maintenance strategy could help reduce virological failures among HIV infected children three years and older starting ART.
Author Contributions
Conceived and designed the experiments: GAU. Analyzed the data: GAU. Contributed reagents/materials/analysis tools: GAU RP MM PKN. Contributed to the writing of the manuscript: GAU RP MM PKN.
|
<filename>deep_utils/dummy_objects/augmentation/__init__.py
from .cutmix import *
|
import s from 'underscore.string';
import * as colors from 'colorette';
// force enable colors on dev env
if (process.env.NODE_ENV !== 'production') {
colors.options.enabled = true;
}
type LogColors = 'white' | 'blue' | 'green' | 'magenta' | 'red';
export function showBox(title: string, message: string, color?: LogColors): void {
const msgLines = message.split('\n');
const len = Math.max.apply(
null,
msgLines.map((line) => line.length),
);
const topLine = `+--${s.pad('', len, '-')}--+`;
const separator = `| ${s.pad('', len, '')} |`;
const lines = [];
lines.push(topLine);
if (title) {
lines.push(`| ${s.lrpad(title, len)} |`);
lines.push(topLine);
}
lines.push(separator);
[...lines, ...msgLines.map((line) => `| ${s.rpad(line, len)} |`), separator, topLine].forEach((line) =>
console.log(color ? colors[color](line) : line),
);
}
export function showErrorBox(title: string, message: string): void {
showBox(title, message, 'red');
}
export function showSuccessBox(title: string, message: string): void {
showBox(title, message, 'green');
}
export function showWarningBox(title: string, message: string): void {
showBox(title, message, 'magenta');
}
|
from railrl.data_management.replay_buffer import ReplayBuffer
class ProxyBuffer(ReplayBuffer):
def __init__(self, replay_buffer):
self._wrapped_buffer = replay_buffer
def add_sample(self, *args, **kwargs):
self._wrapped_buffer.add_sample(*args, **kwargs)
def terminate_episode(self, *args, **kwargs):
self._wrapped_buffer.terminate_episode(*args, **kwargs)
def num_steps_can_sample(self, *args, **kwargs):
self._wrapped_buffer.num_steps_can_sample(*args, **kwargs)
def add_path(self, *args, **kwargs):
self._wrapped_buffer.add_path(*args, **kwargs)
def add_paths(self, *args, **kwargs):
self._wrapped_buffer.add_paths(*args, **kwargs)
def random_batch(self, *args, **kwargs):
self._wrapped_buffer.random_batch(*args, **kwargs)
def get_diagnostics(self, *args, **kwargs):
return self._wrapped_buffer.get_diagnostics(*args, **kwargs)
def get_snapshot(self, *args, **kwargs):
return self._wrapped_buffer.get_snapshot(*args, **kwargs)
def end_epoch(self, *args, **kwargs):
return self._wrapped_buffer.end_epoch(*args, **kwargs)
@property
def wrapped_buffer(self):
return self._wrapped_buffer
def __getattr__(self, attr):
if attr == '_wrapped_buffer':
raise AttributeError()
return getattr(self._wrapped_buffer, attr)
|
<gh_stars>1-10
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "WebviewJSEventHandlerBase.h"
#import "IWCShareCardPkgExt.h"
#import "WCNewShareCardConsumedViewDelegate.h"
@class NSString, WCNewShareCardConsumedView;
@interface WebviewJSEventHandler_consumedShareCard : WebviewJSEventHandlerBase <IWCShareCardPkgExt, WCNewShareCardConsumedViewDelegate>
{
NSString *_consumedCardId;
NSString *_consumedCode;
WCNewShareCardConsumedView *_newconsumedView;
}
- (void).cxx_destruct;
- (void)dealloc;
- (void)handleJSEvent:(id)arg1 HandlerFacade:(id)arg2 ExtraData:(id)arg3;
- (void)onMsgNotifyShareCardConsumed:(id)arg1 sharedCardId:(id)arg2 consumedBoxId:(id)arg3 subscribeAppUserName:(id)arg4 subscribeWording:(id)arg5 retMsg:(id)arg6;
- (void)onShareCardAfterConsumed:(_Bool)arg1;
- (void)onShareCardConsumedViewCloseBtnClick;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
/**
* Simple tests for the hamster API.
* @author Steffen Becker
*
*/
@TestInstance(Lifecycle.PER_CLASS)
public class TerritoryInitTests {
/**
* Size used in this test for both, colums and rows.
*/
private static final int TERRITORY_SIZE = 4;
/**
* Example territory.
*/
private final String exampleTerritory =
"4\n"
+ "4\n"
+ "> \n"
+ "* \n"
+ " \n"
+ " \n"
+ "0\n"
+ "1\n"
+ "0\n";
/**
* Field containing the hamster game used in tests.
*/
private HamsterGame game;
/**
* During a test, this contains a reference to the default hamster.
*/
private Hamster paule;
/**
* Initialize a game and its UI.
*/
@BeforeAll
public void createHamsterGame() {
game = new HamsterGame();
}
/**
* Before each test, load the default territory.
*/
@BeforeEach
public void initializeTest() {
game.initialize(getClass().getResourceAsStream("/_territories/example02.ter"));
paule = game.getTerritory().getDefaultHamster();
}
/**
* Test loading a territory from an Input Stream.
*/
@Test
public void testLoadFromInputStream() {
game.initialize(exampleTerritory);
paule = game.getTerritory().getDefaultHamster();
assertEquals(game.getTerritory().getTerritorySize(), new Size(TERRITORY_SIZE, TERRITORY_SIZE));
assertEquals(paule.getLocation(), Location.from(0, 0));
assertEquals(game.getTerritory().getTotalGrainCount(), 1);
}
/**
* Test creating a territory via API.
*/
@Test
public void testCreateTerritoryViaAPI() {
final TerritoryBuilder territoryBuilder = game.getNewTerritoryBuilder();
territoryBuilder.initializeTerritory(new Size(TERRITORY_SIZE, TERRITORY_SIZE));
territoryBuilder.defaultHamsterAt(Location.ORIGIN, Direction.EAST, 0);
territoryBuilder.grainAt(Location.from(1, 0));
game.initialize(territoryBuilder);
paule = game.getTerritory().getDefaultHamster();
assertEquals(game.getTerritory().getTerritorySize(), new Size(TERRITORY_SIZE, TERRITORY_SIZE));
assertEquals(paule.getLocation(), Location.from(0, 0));
assertEquals(game.getTerritory().getTotalGrainCount(), 1);
}
}
|
#include<stdio.h>
#include<vector>
#include<algorithm>
#define SIZE 131072
using namespace std;
typedef long long ll;
ll mod=1000000007;
ll powsum[SIZE+1][6];
void calcpow()
{
ll now[6];
fill(now,now+6,0);
for(int i=1;i<=SIZE;i++)
{
ll pl=1;
powsum[i][0]=i;
for(int j=1;j<=5;j++)
{
pl=pl*i%mod;
now[j]=(now[j]+pl)%mod;
powsum[i][j]=now[j];
}
}
}
class segtree
{
public:
vector<vector<ll> >seg;
ll flag[SIZE*2];
ll tim(ll a,ll b,ll c)
{
return (((a*b)%mod)*c)%mod;
}
vector<ll>unite(vector<ll>a,vector<ll>b,int asiz)
{
vector<ll>ret;
ret.resize(6);
ll d1=asiz;
ll d2=d1*asiz%mod;
ll d3=d2*asiz%mod;
ll d4=d3*asiz%mod;
ll d5=d4*asiz%mod;
ret[0]=(a[0]+b[0])%mod;
ret[1]=(a[1]+b[1]+d1*b[0])%mod;
ret[2]=(a[2]+b[2]+tim(d1,2,b[1])+d2*b[0])%mod;
ret[3]=(a[3]+b[3]+tim(d1,3,b[2])+tim(d2,3,b[1])+d3*b[0])%mod;
ret[4]=(a[4]+b[4]+tim(d1,4,b[3])+tim(d2,6,b[2])+tim(d3,4,b[1])+d4*b[0])%mod;
ret[5]=(a[5]+b[5]+tim(d1,5,b[4])+tim(d2,10,b[3])+tim(d3,10,b[2])+tim(d4,5,b[1])+d5*b[0])%mod;
return ret;
}
void init(vector<ll>vec)
{
seg.resize(SIZE*2);
for(int i=0;i<SIZE*2;i++)
{
flag[i]=-1;
seg[i].resize(6);
}
for(int i=0;i<vec.size();i++)
{
for(int j=0;j<=5;j++)
{
seg[SIZE+i][j]=vec[i];
}
}
dfs(1,SIZE);
}
void dfs(int node,int dist)
{
if(node>=SIZE)
{
return;
}
dfs(node*2,dist/2);
dfs(node*2+1,dist/2);
seg[node]=unite(seg[node*2],seg[node*2+1],dist/2);
}
void update(int beg,int end,int node,int lb,int ub,ll num)
{
if(ub<beg||end<lb)
{
return;
}
if(beg<=lb&&ub<=end)
{
for(int i=0;i<=5;i++)
{
seg[node][i]=(num*powsum[ub-lb+1][i])%mod;
}
flag[node]=num;
return;
}
if(flag[node]!=-1)
{
for(int i=0;i<=5;i++)
{
seg[node*2][i]=(flag[node]*powsum[(ub-lb+1)/2][i])%mod;
seg[node*2+1][i]=(flag[node]*powsum[(ub-lb+1)/2][i])%mod;
}
flag[node*2]=flag[node*2+1]=flag[node];
flag[node]=-1;
}
update(beg,end,node*2,lb,(lb+ub)/2,num);
update(beg,end,node*2+1,(lb+ub)/2+1,ub,num);
vector<ll>ret=unite(seg[node*2],seg[node*2+1],(ub-lb+1)/2);
seg[node]=ret;
}
vector<ll>sum(int beg,int end,int node,int lb,int ub)
{
if(ub<beg||end<lb)
{
vector<ll>z;
for(int i=0;i<=5;i++)
{
z.push_back(0);
}
return z;
}
if(beg<=lb&&ub<=end)
{
return seg[node];
}
if(flag[node]!=-1)
{
for(int i=0;i<=5;i++)
{
seg[node*2][i]=(flag[node]*powsum[(ub-lb+1)/2][i])%mod;
seg[node*2+1][i]=(flag[node]*powsum[(ub-lb+1)/2][i])%mod;
}
flag[node*2]=flag[node*2+1]=flag[node];
flag[node]=-1;
}
vector<ll>va=sum(beg,end,node*2,lb,(lb+ub)/2),vb=sum(beg,end,node*2+1,(lb+ub)/2+1,ub);
vector<ll>ret=unite(va,vb,min((ub-lb+1)/2,max((lb+ub)/2+1-beg,0)));
return ret;
}
};
segtree tree;
int main()
{
calcpow();
int num,query;
scanf("%d%d",&num,&query);
vector<ll>vec;
for(int i=0;i<num;i++)
{
ll zan;
scanf("%I64d",&zan);
vec.push_back(zan);
}
tree.init(vec);
for(int i=0;i<query;i++)
{
char za;
int zb,zc;
ll zd;
scanf(" %c%d%d%I64d",&za,&zb,&zc,&zd);
zb--;
zc--;
if(za=='=')
{
tree.update(zb,zc,1,0,SIZE-1,zd);
}
else
{
vector<ll>ret=tree.sum(zb,zc,1,0,SIZE-1);
printf("%I64d\n",ret[zd]);
}
}
}
|
a = input()
i = int(a)
n = 0
lst2 = []
while n<i :
n+=1
b = input()
lst = b.split(" ")
for j in b :
lst2+=j
x = lst2[-1]
if x == "o" :
print("FILIPINO")
if x == "u" :
print("JAPANESE")
if x == "a" :
print("KOREAN")
|
// Copyright 2020 <NAME>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collector
import (
"bytes"
"fmt"
"regexp"
"strconv"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
configPingTimeout = kingpin.Flag("collector.ping.timeout", "Timeout for mco ping").Default("1").String()
)
type PingMetric struct {
Status int
Time float64
}
type PingCollector struct {
logger log.Logger
identity string
Status *prometheus.Desc
Time *prometheus.Desc
}
func init() {
registerCollector("ping", true, NewPingCollector)
}
func NewPingCollector(logger log.Logger, identity string) Collector {
return &PingCollector{
logger: logger,
identity: identity,
Status: prometheus.NewDesc(prometheus.BuildFQName(namespace, "ping", "status"),
"mco ping status, 1=successful 0=not successful", nil, nil),
Time: prometheus.NewDesc(prometheus.BuildFQName(namespace, "ping", "seconds"),
"mco ping time in seconds", nil, nil),
}
}
func (c *PingCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.Status
ch <- c.Time
}
func (c *PingCollector) Collect(ch chan<- prometheus.Metric) {
level.Debug(c.logger).Log("msg", "Collecting ping metric")
err := c.collect(ch)
if err != nil {
ch <- prometheus.MustNewConstMetric(collectError, prometheus.GaugeValue, 1, "ping")
} else {
ch <- prometheus.MustNewConstMetric(collectError, prometheus.GaugeValue, 0, "ping")
}
}
func (c *PingCollector) collect(ch chan<- prometheus.Metric) error {
collectTime := time.Now()
metric, err := ping(c.logger, c.identity)
if err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(c.Status, prometheus.GaugeValue, float64(metric.Status))
ch <- prometheus.MustNewConstMetric(c.Time, prometheus.GaugeValue, metric.Time)
ch <- prometheus.MustNewConstMetric(collectDuration, prometheus.GaugeValue, time.Since(collectTime).Seconds(), "ping")
return nil
}
func ping(logger log.Logger, identity string) (PingMetric, error) {
var metric PingMetric
mco := *mcoPath
timeout := *configPingTimeout
cmd := execCommand(mco, "ping", "--timeout", timeout, "-I", identity)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
re := regexp.MustCompile(`\r?\n`)
outlog := re.ReplaceAllString(out.String(), " ")
if err != nil {
level.Error(logger).Log("error", fmt.Sprintf("PING: %s : %s", outlog, err))
metric.Status = 0
} else {
metric.Status = 1
}
timePattern := regexp.MustCompile(`time=([0-9.]+) ([a-z]+)`)
timeMatch := timePattern.FindStringSubmatch(out.String())
if len(timeMatch) == 3 {
time, err := strconv.ParseFloat(timeMatch[1], 64)
if err != nil {
level.Error(logger).Log("error", fmt.Sprintf("Error parsing time %s for %s: %s", outlog, identity, err.Error()))
return metric, err
}
unit := timeMatch[2]
switch unit {
case "ms":
time = time / 1000.0
}
metric.Time = time
}
return metric, nil
}
|
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List.
*
* Memory Usage: 38 MB, less than 6.48% of Java online submissions for Reverse Linked List.
*/
public ListNode reverseList(ListNode head) {
if (Objects.isNull(head)) {
return null;
}
ListNode result = null;
ListNode current = head;
while (Objects.nonNull(current)) {
ListNode pre = current.next;
current.next = result;
result = current;
current = pre;
}
return result;
}
|
Dream Big by /u/youngluck
“Think left and think right
Think low and think high.
Oh, the thinks you can think up if only you try!”
One thing that never fails to surprise us is the limitless potential of the reddit community. Like this example of art imitating life. This is why we wanted to highlight the creative side of reddit. Art and Culture are an integral part of all communities, and the reddit community is no different.
Art, being subjective, can mean different things to different people. One look atr/art and /r/museum shows the reddit community obviously has an interest in looking at things that make their eyes and brain feel nice. We want to share only a tiny selection of the subreddits on offer. This is only the tip of the iceberg of the various art related subreddits that exist.
Painting/Drawing: You may have heard of the popular /r/redditgetsdrawn, where redditors draw redditors, but there are a number of other subreddits dedicated to the appreciation and creation of different types of artwork. Here are a few of our favorites:
Creation/Design: Have a look at how creative people can be when it comes to items of a 3D variety.
Creative writing subreddits: A place where walls of text (be they beautifully written, funny, moving or thought provoking) are encouraged rather than apologised for, and where tl:dr is rarely an issue.
Photography: A picture is worth 1000 upvotes.
Everyone has their own creative outlet, and nearly every creative outlet has its own subreddit. If you can’t find a subreddit that captures your creative vision it might be time to start a movement for yourself. If you want to learn more there are plenty of resources from the /r/WritingPrompts wiki to /r/learnart. We hope you found this blog post inspirational. Go forth on reddit and make art!
|
def time_differences() -> typing.List[float]:
ties = create_time_ties()
ret = [tie[0].time - tie[1].time for tie in ties]
return ret
|
package com.miotech.kun.workflow.executor;
import com.google.common.collect.Iterables;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.miotech.kun.commons.db.DatabaseOperator;
import com.miotech.kun.commons.pubsub.event.Event;
import com.miotech.kun.commons.pubsub.publish.EventPublisher;
import com.miotech.kun.commons.pubsub.subscribe.EventSubscriber;
import com.miotech.kun.commons.utils.Props;
import com.miotech.kun.metadata.core.model.dataset.DataStore;
import com.miotech.kun.metadata.facade.LineageServiceFacade;
import com.miotech.kun.metadata.facade.MetadataServiceFacade;
import com.miotech.kun.workflow.LocalScheduler;
import com.miotech.kun.workflow.TaskRunStateMachine;
import com.miotech.kun.workflow.common.executetarget.ExecuteTargetService;
import com.miotech.kun.workflow.common.operator.dao.OperatorDao;
import com.miotech.kun.workflow.common.resource.ResourceLoader;
import com.miotech.kun.workflow.common.task.dao.TaskDao;
import com.miotech.kun.workflow.common.taskrun.bo.TaskAttemptProps;
import com.miotech.kun.workflow.common.taskrun.dao.TaskRunDao;
import com.miotech.kun.workflow.core.Executor;
import com.miotech.kun.workflow.core.Scheduler;
import com.miotech.kun.workflow.core.event.*;
import com.miotech.kun.workflow.core.execution.KunOperator;
import com.miotech.kun.workflow.core.model.executetarget.ExecuteTarget;
import com.miotech.kun.workflow.core.model.operator.Operator;
import com.miotech.kun.workflow.core.model.task.CheckType;
import com.miotech.kun.workflow.core.model.task.Task;
import com.miotech.kun.workflow.core.model.taskrun.TaskAttempt;
import com.miotech.kun.workflow.core.model.taskrun.TaskRun;
import com.miotech.kun.workflow.core.model.taskrun.TaskRunStatus;
import com.miotech.kun.workflow.core.model.worker.WorkerInstance;
import com.miotech.kun.workflow.core.model.worker.WorkerInstanceKind;
import com.miotech.kun.workflow.core.resource.Resource;
import com.miotech.kun.workflow.executor.local.*;
import com.miotech.kun.workflow.executor.mock.*;
import com.miotech.kun.workflow.testing.event.EventCollector;
import com.miotech.kun.workflow.testing.factory.MockOperatorFactory;
import com.miotech.kun.workflow.testing.factory.MockTaskAttemptFactory;
import com.miotech.kun.workflow.testing.factory.MockTaskFactory;
import com.miotech.kun.workflow.testing.factory.MockTaskRunFactory;
import com.miotech.kun.workflow.testing.operator.OperatorCompiler;
import com.miotech.kun.workflow.utils.ResourceUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.neo4j.ogm.session.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.doAnswer;
public class LocalExecutorTest extends CommonTestBase {
@Inject
private Executor executor;
@Inject
private OperatorDao operatorDao;
@Inject
private TaskRunDao taskRunDao;
@Inject
private TaskDao taskDao;
@Inject
private ResourceLoader resourceLoader;
@Inject
private EventBus eventBus;
@Inject
private MiscService miscService;
private LocalProcessBackend spyBackend;
@Inject
private AbstractQueueManager localQueueManager;
@Inject
private DataSource dataSource;
@Inject
private LocalProcessMonitor workerMonitor;
@Inject
private WorkerLifeCycleManager workerLifeCycleManager;
@Inject
private ExecuteTargetService executeTargetService;
@Inject
private DatabaseOperator databaseOperator;
@Inject
private TaskRunStateMachine taskRunStateMachine;
private MockEventSubscriber mockEventSubscriber;
private Props props;
private final Logger logger = LoggerFactory.getLogger(LocalExecutorTest.class);
public TemporaryFolder tempFolder = new TemporaryFolder();
private EventCollector eventCollector;
@Override
protected boolean usePostgres() {
return true;
}
@Override
protected void configuration() {
props = new Props();
props.put("executor.env.resourceQueues", "default,test");
props.put("executor.env.resourceQueues.default.quota.workerNumbers", 2);
props.put("executor.env.resourceQueues.test.quota.workerNumbers", 2);
props.put("datasource.maxPoolSize", 1);
props.put("datasource.minimumIdle", 0);
props.put("neo4j.uri", neo4jContainer.getBoltUrl());
props.put("neo4j.username", "neo4j");
props.put("neo4j.password", neo4jContainer.getAdminPassword());
super.configuration();
MetadataServiceFacade mockMetadataFacade = Mockito.mock(MetadataServiceFacade.class);
bind(SessionFactory.class, mock(SessionFactory.class));
bind(MetadataServiceFacade.class, mockMetadataFacade);
bind(LineageServiceFacade.class, mock(LineageServiceFacade.class));
bind(EventBus.class, new EventBus());
bind(EventPublisher.class, new NopEventPublisher());
mockEventSubscriber = new MockEventSubscriber();
bind(EventSubscriber.class, mockEventSubscriber);
LocalProcessBackend localProcessBackend = new LocalProcessBackend();
spyBackend = spy(localProcessBackend);
bind(LocalProcessBackend.class, spyBackend);
bind(AbstractQueueManager.class, LocalQueueManage.class);
bind(Props.class, props);
bind(WorkerMonitor.class, LocalProcessMonitor.class);
bind(WorkerLifeCycleManager.class, LocalProcessLifeCycleManager.class);
bind(Executor.class, LocalExecutor.class);
bind(Scheduler.class, LocalScheduler.class);
}
@BeforeEach
public void setUp() throws IOException{
tempFolder.create();
databaseOperator.update("truncate table kun_wf_target RESTART IDENTITY");
props.put("datasource.jdbcUrl", postgres.getJdbcUrl() + "&stringtype=unspecified");
props.put("datasource.username", postgres.getUsername());
props.put("datasource.password", <PASSWORD>());
props.put("datasource.driverClassName", "org.postgresql.Driver");
executor = injector.getInstance(Executor.class);
workerLifeCycleManager.init();
eventCollector = new EventCollector();
eventBus.register(eventCollector);
workerMonitor.start();
taskRunStateMachine.start();
}
@AfterEach
@Override
public void tearDown() {
workerLifeCycleManager.shutdown();
workerMonitor.stop();
super.tearDown();
try {
((HikariDataSource) dataSource).close();
} catch (Exception e) {
}
}
private static class NopEventPublisher implements EventPublisher {
@Override
public void publish(Event event) {
// nop
}
}
@Test
//taskAttempt未下发到worker执行,executor重启
public void executorRestartBeforeWorkerStart() throws IOException {
TaskRun mockTaskRun = MockTaskRunFactory.createTaskRun();
TaskAttempt attempt = MockTaskAttemptFactory.createTaskAttemptWithStatus(mockTaskRun, TaskRunStatus.CREATED);
prepareAttempt(TestOperator1.class, attempt);
doAnswer(invocation -> {
//do noting to ensure worker not start
return null;
}).when(spyBackend).startProcess(ArgumentMatchers.any(), ArgumentMatchers.any());
executor.submit(attempt);
executor.reset();
doAnswer(invocation ->
invocation.callRealMethod()
).when(spyBackend).startProcess(ArgumentMatchers.any(), ArgumentMatchers.any());
executor.recover();
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world!"));
assertThat(content, containsString("URLClassLoader"));
assertThat(content, not(containsString("AppClassLoader")));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(attempt.getId());
assertThat(finishedEvent.getAttemptId(), is(attempt.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.SUCCESS));
assertThat(finishedEvent.getInlets(), hasSize(2));
assertThat(finishedEvent.getOutlets(), hasSize(1));
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
//任务下发到worker执行后executor重启
public void executorRestartAfterWorkerStarted() throws IOException {
TaskRun mockTaskRun = MockTaskRunFactory.createTaskRun();
TaskAttempt attempt = MockTaskAttemptFactory.createTaskAttemptWithStatus(mockTaskRun, TaskRunStatus.CREATED);
prepareAttempt(TestOperator1.class, attempt);
executor.submit(attempt);
awaitUntilRunning(attempt.getId());
executor.reset();
executor.recover();
awaitUntilAttemptDone(attempt.getId());
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world!"));
assertThat(content, containsString("URLClassLoader"));
assertThat(content, not(containsString("AppClassLoader")));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(attempt.getId());
assertThat(finishedEvent.getAttemptId(), is(attempt.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.SUCCESS));
assertThat(finishedEvent.getInlets(), hasSize(2));
assertThat(finishedEvent.getOutlets(), hasSize(1));
awaitUntilProcessDown("default", 0);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
//taskAttempt下发到worker执行,executor重启,重启前销毁worker
public void executorRestartWhenWorkerIsRunning() throws IOException {
TaskRun mockTaskRun = MockTaskRunFactory.createTaskRun();
TaskAttempt attempt = MockTaskAttemptFactory.createTaskAttemptWithStatus(mockTaskRun, TaskRunStatus.CREATED);
prepareAttempt(TestOperator1.class, attempt);
doAnswer(invocation -> {
TaskRunTransitionEvent taskRunTransitionEvent = new TaskRunTransitionEvent(TaskRunTransitionEventType.RUNNING,attempt.getId());
eventBus.post(taskRunTransitionEvent);
return null;
}).when(spyBackend).startProcess(ArgumentMatchers.any(), ArgumentMatchers.any());
executor.submit(attempt);
awaitUntilRunning(attempt.getId());
doAnswer(invocation ->
invocation.callRealMethod()
).when(spyBackend).startProcess(ArgumentMatchers.any(), ArgumentMatchers.any());
executor.reset();
executor.recover();
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world!"));
assertThat(content, containsString("URLClassLoader"));
assertThat(content, not(containsString("AppClassLoader")));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(attempt.getId());
assertThat(finishedEvent.getAttemptId(), is(attempt.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.SUCCESS));
assertThat(finishedEvent.getInlets(), hasSize(2));
assertThat(finishedEvent.getOutlets(), hasSize(1));
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
//提交的taskAttempt已经下发到worker中执行
public void submitTaskAttemptIsRunning() throws InterruptedException {
TaskRun taskRun = MockTaskRunFactory.createTaskRun();
TaskAttempt runningTaskAttempt = MockTaskAttemptFactory.createTaskAttemptWithStatus(taskRun, TaskRunStatus.CREATED);
prepareAttempt(TestOperator8.class, runningTaskAttempt);
executor.submit(runningTaskAttempt);
//wait attempt Running
awaitUntilRunning(runningTaskAttempt.getId());
TaskAttempt createdTaskAttempt = MockTaskAttemptFactory.createTaskAttemptWithStatus(taskRun, TaskRunStatus.CREATED);
taskRunDao.createAttempt(createdTaskAttempt);
TaskAttempt queuedTaskAttempt = MockTaskAttemptFactory.createTaskAttemptWithStatus(taskRun, TaskRunStatus.QUEUED);
taskRunDao.createAttempt(queuedTaskAttempt);
boolean submitCreated = executor.submit(createdTaskAttempt);
boolean submitQueued = executor.submit(queuedTaskAttempt);
assertThat(submitCreated, is(false));
assertThat(submitQueued, is(false));
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers() - 1));
//clean up running process
executor.cancel(runningTaskAttempt.getId());
awaitUntilProcessDown("default", 0);
// events
assertStatusHistory(runningTaskAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.ABORTED);
}
@Test
//提交的taskAttempt已经下发到worker中执行
public void submitTaskAttemptHasFinish() {
TaskRun taskRun = MockTaskRunFactory.createTaskRun();
TaskAttempt finishTaskAttempt = MockTaskAttemptFactory.createTaskAttemptWithStatus(taskRun, TaskRunStatus.CREATED);
prepareAttempt(TestOperator1.class, finishTaskAttempt);
executor.submit(finishTaskAttempt);
awaitUntilAttemptDone(finishTaskAttempt.getId());
TaskAttempt newTaskAttempt = MockTaskAttemptFactory.createTaskAttempt(taskRun);
taskRunDao.createAttempt(newTaskAttempt);
awaitUntilProcessDown("default", 0);
boolean result = executor.submit(newTaskAttempt);
assertThat(result, is(true));
// events
assertStatusHistory(finishTaskAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testSubmit_ok() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator1.class);
// process
executor.submit(attempt);
logger.info("attemptId = {}", attempt.getId());
// verify
awaitUntilAttemptDone(attempt.getId());
logger.info("task done");
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
assertThat(taskRunDao.getTermAtOfTaskRun(taskRun.getId()), is(taskRun.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world!"));
assertThat(content, containsString("URLClassLoader"));
assertThat(content, not(containsString("AppClassLoader")));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
awaitUntilProcessDown("default", 0);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(attempt.getId());
assertThat(finishedEvent.getAttemptId(), is(attempt.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.SUCCESS));
assertThat(finishedEvent.getInlets(), hasSize(2));
assertThat(finishedEvent.getOutlets(), hasSize(1));
// inlets/outlets
List<DataStore> inlets = taskRun.getInlets();
List<DataStore> outlets = taskRun.getOutlets();
assertThat(finishedEvent.getInlets(), sameBeanAs(inlets));
assertThat(finishedEvent.getOutlets(), sameBeanAs(outlets));
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testSubmit_then_overwriteOperatorJar() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator1.class, "TestOperator1");
// process
executor.submit(attempt);
awaitUntilAttemptDone(attempt.getId());
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world!"));
// overwrite operator jar
attempt = prepareAttempt(TestOperator1_1.class, "TestOperator1");
executor.submit(attempt);
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
// task_run and task_attempt
attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
// logs
log = resourceLoader.getResource(attemptProps.getLogPath());
content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world2!"));
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testSubmit_ok_concurrent_running() throws IOException {
// prepare
TaskAttempt attempt1 = prepareAttempt(TestOperator1.class);
TaskAttempt attempt2 = prepareAttempt(TestOperator2.class);
// process
executor.submit(attempt1);
executor.submit(attempt2);
// verify
awaitUntilAttemptDone(attempt1.getId());
awaitUntilAttemptDone(attempt2.getId());
awaitUntilProcessDown("default", 0);
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt1.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt2.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.FAILED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
// events
assertStatusHistory(attempt1.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(attempt1.getId());
assertThat(finishedEvent.getAttemptId(), is(attempt1.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.SUCCESS));
assertThat(finishedEvent.getInlets(), hasSize(2));
assertThat(finishedEvent.getOutlets(), hasSize(1));
assertStatusHistory(attempt2.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.FAILED);
finishedEvent = getFinishedEvent(attempt2.getId());
assertThat(finishedEvent.getAttemptId(), is(attempt2.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.FAILED));
assertThat(finishedEvent.getInlets(), hasSize(0));
assertThat(finishedEvent.getOutlets(), hasSize(0));
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testSubmit_fail_running_failure() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator2.class);
// process
executor.submit(attempt);
// verify
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.FAILED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
assertThat(taskRunDao.getTermAtOfTaskRun(taskRun.getId()), is(taskRun.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Execution Failed"));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.FAILED);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testSubmit_fail_unexpected_exception() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator3.class);
// process
executor.submit(attempt);
// verify
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.FAILED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Unexpected exception occurred"));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.FAILED);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testSubmit_fail_operator_not_found() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator1.class, "TestOperator1", "TestOperator999");
// process
executor.submit(attempt);
// verify
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.FAILED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Failed to load jar"));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.FAILED);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testStop_attempt_aborted() throws Exception {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator4.class);
// process
executor.submit(attempt);
awaitUntilRunning(attempt.getId());
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers() - 1));
awaitUntilOperatorRunning(attempt.getId());
executor.cancel(attempt.getId());
// wait until aborted
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
// verify
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.ABORTED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("TestOperator4 is aborting"));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.ABORTED);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testStop_attempt_force_aborted() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator5.class);
// process
executor.submit(attempt);
awaitUntilRunning(attempt.getId());
awaitUntilOperatorRunning(attempt.getId());
executor.cancel(attempt.getId());
// wait until aborted
awaitUntilAttemptAbort(attempt.getId());
awaitUntilProcessDown("default", 0);
// verify
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.ABORTED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.ABORTED);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testAbort_attempt_cost_time() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator7.class);
// process
executor.submit(attempt);
awaitUntilRunning(attempt.getId());
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers() - 1));
awaitUntilOperatorRunning(attempt.getId());
executor.cancel(attempt.getId());
// wait until aborted
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
// verify
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.ABORTED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("TestOperator7 is aborting"));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.ABORTED);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Test
public void testStop_attempt_abort_throws_exception() throws IOException {
// prepare
TaskAttempt attempt = prepareAttempt(TestOperator6.class);
// process
executor.submit(attempt);
awaitUntilRunning(attempt.getId());
awaitUntilOperatorRunning(attempt.getId());
executor.cancel(attempt.getId());
// wait until aborted
awaitUntilAttemptDone(attempt.getId());
awaitUntilProcessDown("default", 0);
// verify
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(attempt.getTaskRun().getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.ABORTED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun taskRun = taskRunDao.fetchLatestTaskRun(attempt.getTaskRun().getTask().getId());
assertThat(taskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(taskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(taskRun.getEndAt(), is(attemptProps.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Unexpected exception occurred during aborting operator."));
// events
assertStatusHistory(attempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.ABORTED);
assertThat(localQueueManager.getCapacity("default"), is(localQueueManager.getResourceQueue("default").getWorkerNumbers()));
}
@Disabled
public void abortTaskAttemptInQueue() {
//prepare
TaskAttempt taskAttempt = prepareAttempt(TestOperator1.class);
doAnswer(invocation -> {
//do noting to ensure worker not start
return null;
}).when(spyBackend).startProcess(ArgumentMatchers.any(), ArgumentMatchers.any());
executor.submit(taskAttempt);
//verify
TaskAttempt saved = taskRunDao.fetchAttemptById(taskAttempt.getId()).get();
assertThat(saved.getStatus(), is(TaskRunStatus.QUEUED));
executor.cancel(taskAttempt.getId());
awaitUntilAttemptAbort(taskAttempt.getId());
// events
assertStatusHistory(taskAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.ABORTED);
awaitUntilProcessDown("default", 0);
assertThat(localQueueManager.getCapacity("default"), is(2));
}
@Test
public void abortTaskAttemptCreated() {
//prepare
TaskAttempt taskAttempt = prepareAttempt(TestOperator1.class);
//verify
TaskAttempt saved = taskRunDao.fetchAttemptById(taskAttempt.getId()).get();
assertThat(saved.getStatus(), is(TaskRunStatus.CREATED));
executor.cancel(taskAttempt.getId());
awaitUntilAttemptAbort(taskAttempt.getId());
// events
assertStatusHistory(taskAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.ABORTED);
}
@Test
public void resourceIsolationTest() {
doAnswer(invocation -> {
String queueName = invocation.getArgument(0, String.class);
List<ProcessSnapShot> result = new ArrayList<>();
if (queueName.equals("default")) {
WorkerInstance workerInstance1 = new WorkerInstance(111, "222", "local", WorkerInstanceKind.LOCAL_PROCESS);
ProcessSnapShot processSnapShot1 = new ProcessSnapShot(workerInstance1, TaskRunStatus.RUNNING);
result.add(processSnapShot1);
WorkerInstance workerInstance2 = new WorkerInstance(222, "333", "local", WorkerInstanceKind.LOCAL_PROCESS);
ProcessSnapShot processSnapShot2 = new ProcessSnapShot(workerInstance2, TaskRunStatus.RUNNING);
result.add(processSnapShot2);
return result;
} else {
return invocation.callRealMethod();
}
}).when(spyBackend).fetchRunningProcess("default");
//prepare TaskAttempt
TaskAttempt defaultAttempt = prepareAttempt(TestOperator6.class);
//submit default queue attempt
executor.submit(defaultAttempt);
Task task = MockTaskFactory.createTask().cloneBuilder().withQueueName("test").build();
TaskRun taskRun = MockTaskRunFactory.createTaskRun(task);
TaskAttempt taskAttempt = MockTaskAttemptFactory.createTaskAttempt(taskRun);
TaskAttempt userAttempt = prepareAttempt(TestOperator6.class, taskAttempt);
// submit test attempt
executor.submit(userAttempt);
awaitUntilAttemptDone(userAttempt.getId());
awaitUntilProcessDown("test", 0);
// verify default attempt
TaskAttemptProps defaultAttemptProps = taskRunDao.fetchLatestTaskAttempt(defaultAttempt.getTaskRun().getId());
assertThat(defaultAttemptProps.getAttempt(), is(1));
assertThat(defaultAttemptProps.getStatus(), is(TaskRunStatus.QUEUED));
// verify events
assertStatusHistory(defaultAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED);
// verify user attempt
TaskAttemptProps userAttemptProps = taskRunDao.fetchLatestTaskAttempt(userAttempt.getTaskRun().getId());
assertThat(userAttemptProps.getAttempt(), is(1));
assertThat(userAttemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(userAttemptProps.getLogPath(), is(notNullValue()));
assertThat(userAttemptProps.getStartAt(), is(notNullValue()));
assertThat(userAttemptProps.getEndAt(), is(notNullValue()));
// events
assertStatusHistory(userAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
//verity resource
assertThat(localQueueManager.getCapacity("default"), is(0));
assertThat(localQueueManager.getResourceQueue("default").getWorkerNumbers(), is(2));
assertThat(localQueueManager.getCapacity("test"), is(2));
assertThat(localQueueManager.getResourceQueue("test").getWorkerNumbers(), is(2));
}
@Test
public void runTaskWithPriority() {
Task task1 = MockTaskFactory.createTask().cloneBuilder().withQueueName("test").
withPriority(16).build();
TaskRun taskRun1 = MockTaskRunFactory.createTaskRun(task1);
TaskAttempt taskAttempt1 = prepareAttempt(TestOperator1.class, MockTaskAttemptFactory.createTaskAttempt(taskRun1));
Task task2 = MockTaskFactory.createTask().cloneBuilder().withQueueName("test").
withPriority(24).build();
TaskRun taskRun2 = MockTaskRunFactory.createTaskRun(task2);
TaskAttempt taskAttempt2 = prepareAttempt(TestOperator1.class, MockTaskAttemptFactory.createTaskAttempt(taskRun2));
Task task3 = MockTaskFactory.createTask().cloneBuilder().withQueueName("test").
withPriority(8).build();
TaskRun taskRun3 = MockTaskRunFactory.createTaskRun(task3);
TaskAttempt taskAttempt3 = prepareAttempt(TestOperator1.class, MockTaskAttemptFactory.createTaskAttempt(taskRun3));
executor.submit(taskAttempt1);
executor.submit(taskAttempt2);
executor.submit(taskAttempt3);
awaitUntilAttemptDone(taskAttempt3.getId());
awaitUntilProcessDown("test", 0);
//verify
TaskAttemptProps attemptProps1 = taskRunDao.fetchLatestTaskAttempt(taskRun1.getId());
assertThat(attemptProps1.getAttempt(), is(1));
assertThat(attemptProps1.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps1.getLogPath(), is(notNullValue()));
assertThat(attemptProps1.getStartAt(), is(notNullValue()));
assertThat(attemptProps1.getEndAt(), is(notNullValue()));
TaskAttemptProps attemptProps2 = taskRunDao.fetchLatestTaskAttempt(taskRun2.getId());
assertThat(attemptProps2.getAttempt(), is(1));
assertThat(attemptProps2.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps2.getLogPath(), is(notNullValue()));
assertThat(attemptProps2.getStartAt(), is(notNullValue()));
assertThat(attemptProps2.getEndAt(), is(notNullValue()));
TaskAttemptProps attemptProps3 = taskRunDao.fetchLatestTaskAttempt(taskRun3.getId());
assertThat(attemptProps3.getAttempt(), is(1));
assertThat(attemptProps3.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps3.getLogPath(), is(notNullValue()));
assertThat(attemptProps3.getStartAt(), is(notNullValue()));
assertThat(attemptProps3.getEndAt(), is(notNullValue()));
assertThat(attemptProps3.getStartAt(), greaterThan(attemptProps2.getStartAt()));
assertThat(attemptProps1.getStartAt(), lessThan(attemptProps3.getStartAt()));
}
@Test
public void taskRunTestCaseFailed_should_be_validate_failed() throws IOException {
//mock data quality
TaskAttemptCheckEventListener listener = new TaskAttemptCheckEventListener();
listener.setValidateResult(false);
eventBus.register(listener);
//prepare
Task task = MockTaskFactory.createTask().cloneBuilder()
.withCheckType(CheckType.WAIT_EVENT)
.build();
TaskRun taskRun = MockTaskRunFactory.createTaskRun(task);
TaskAttempt taskAttempt = MockTaskAttemptFactory.createTaskAttempt(taskRun);
prepareAttempt(TestOperator1.class, taskAttempt);
executor.submit(taskAttempt);
// verify
awaitUntilAttemptDone(taskAttempt.getId());
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(taskRun.getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.CHECK_FAILED));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun finishedTaskRun = taskRunDao.fetchLatestTaskRun(task.getId());
assertThat(finishedTaskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(finishedTaskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(finishedTaskRun.getEndAt(), is(attemptProps.getEndAt()));
assertThat(taskRunDao.getTermAtOfTaskRun(finishedTaskRun.getId()), is(finishedTaskRun.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world!"));
assertThat(content, containsString("URLClassLoader"));
assertThat(content, not(containsString("AppClassLoader")));
// events
assertStatusHistory(taskAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.CHECK_FAILED);
awaitUntilProcessDown("default", 0);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(taskAttempt.getId());
assertThat(finishedEvent.getAttemptId(), is(taskAttempt.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.CHECK_FAILED));
assertThat(finishedEvent.getInlets(), hasSize(2));
assertThat(finishedEvent.getOutlets(), hasSize(1));
}
@Test
public void taskRunTestCasePass_should_be_success() throws IOException {
//mock data quality
TaskAttemptCheckEventListener listener = new TaskAttemptCheckEventListener();
listener.setValidateResult(true);
eventBus.register(listener);
//prepare
Task task = MockTaskFactory.createTask().cloneBuilder()
.withCheckType(CheckType.WAIT_EVENT)
.build();
TaskRun taskRun = MockTaskRunFactory.createTaskRun(task);
TaskAttempt taskAttempt = MockTaskAttemptFactory.createTaskAttempt(taskRun);
prepareAttempt(TestOperator1.class, taskAttempt);
executor.submit(taskAttempt);
// verify
awaitUntilAttemptDone(taskAttempt.getId());
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(taskRun.getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun finishedTaskRun = taskRunDao.fetchLatestTaskRun(task.getId());
assertThat(finishedTaskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(finishedTaskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(finishedTaskRun.getEndAt(), is(attemptProps.getEndAt()));
assertThat(taskRunDao.getTermAtOfTaskRun(finishedTaskRun.getId()), is(finishedTaskRun.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("Hello, world!"));
assertThat(content, containsString("URLClassLoader"));
assertThat(content, not(containsString("AppClassLoader")));
// events
assertStatusHistory(taskAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
awaitUntilProcessDown("default", 0);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(taskAttempt.getId());
assertThat(finishedEvent.getAttemptId(), is(taskAttempt.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.SUCCESS));
assertThat(finishedEvent.getInlets(), hasSize(2));
assertThat(finishedEvent.getOutlets(), hasSize(1));
}
@Test
public void runWorkerWithTarget() throws IOException {
//prepare
ExecuteTarget testTarget = ExecuteTarget.newBuilder()
.withName("test")
.build();
executeTargetService.createExecuteTarget(testTarget);
ExecuteTarget prodTarget = ExecuteTarget.newBuilder()
.withName("prod")
.build();
executeTargetService.createExecuteTarget(prodTarget);
ExecuteTarget expectTarget = executeTargetService.fetchExecuteTarget("test");
Task task = MockTaskFactory.createTask();
TaskRun taskRun = MockTaskRunFactory.createTaskRun(task)
.cloneBuilder()
.withExecuteTarget(expectTarget)
.build();
TaskAttempt taskAttempt = MockTaskAttemptFactory.createTaskAttempt(taskRun);
prepareAttempt(TestTargetOperator.class, taskAttempt);
executor.submit(taskAttempt);
// verify
awaitUntilAttemptDone(taskAttempt.getId());
// task_run and task_attempt
TaskAttemptProps attemptProps = taskRunDao.fetchLatestTaskAttempt(taskRun.getId());
assertThat(attemptProps.getAttempt(), is(1));
assertThat(attemptProps.getStatus(), is(TaskRunStatus.SUCCESS));
assertThat(attemptProps.getLogPath(), is(notNullValue()));
assertThat(attemptProps.getStartAt(), is(notNullValue()));
assertThat(attemptProps.getEndAt(), is(notNullValue()));
TaskRun finishedTaskRun = taskRunDao.fetchLatestTaskRun(task.getId());
assertThat(finishedTaskRun.getStatus(), is(attemptProps.getStatus()));
assertThat(finishedTaskRun.getStartAt(), is(attemptProps.getStartAt()));
assertThat(finishedTaskRun.getEndAt(), is(attemptProps.getEndAt()));
assertThat(taskRunDao.getTermAtOfTaskRun(finishedTaskRun.getId()), is(finishedTaskRun.getEndAt()));
// logs
Resource log = resourceLoader.getResource(attemptProps.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
assertThat(content, containsString("running target is " + expectTarget.getName()));
// events
assertStatusHistory(taskAttempt.getId(),
TaskRunStatus.CREATED,
TaskRunStatus.QUEUED,
TaskRunStatus.RUNNING,
TaskRunStatus.CHECK,
TaskRunStatus.SUCCESS);
awaitUntilProcessDown("default", 0);
TaskAttemptFinishedEvent finishedEvent = getFinishedEvent(taskAttempt.getId());
assertThat(finishedEvent.getAttemptId(), is(taskAttempt.getId()));
assertThat(finishedEvent.getFinalStatus(), is(TaskRunStatus.SUCCESS));
}
@Test
public void fetchTaskRunInQueued_queued_at_should_not_null() {
Task task = MockTaskFactory.createTask();
taskDao.create(task);
TaskRun taskRun = MockTaskRunFactory.createTaskRun(task);
taskRunDao.createTaskRun(taskRun);
TaskAttempt taskAttempt = MockTaskAttemptFactory.createTaskAttempt(taskRun);
taskRunDao.createAttempt(taskAttempt);
executor.submit(taskAttempt);
doAnswer(invocation -> {
String queueName = invocation.getArgument(0, String.class);
List<ProcessSnapShot> result = new ArrayList<>();
if (queueName.equals("default")) {
WorkerInstance workerInstance1 = new WorkerInstance(111, "222", "local", WorkerInstanceKind.LOCAL_PROCESS);
ProcessSnapShot processSnapShot1 = new ProcessSnapShot(workerInstance1, TaskRunStatus.RUNNING);
result.add(processSnapShot1);
WorkerInstance workerInstance2 = new WorkerInstance(222, "333", "local", WorkerInstanceKind.LOCAL_PROCESS);
ProcessSnapShot processSnapShot2 = new ProcessSnapShot(workerInstance2, TaskRunStatus.RUNNING);
result.add(processSnapShot2);
return result;
} else {
return invocation.callRealMethod();
}
}).when(spyBackend).fetchRunningProcess("default");
TaskRun queuedTaskRun = taskRunDao.fetchTaskRunById(taskRun.getId()).get();
assertThat(queuedTaskRun.getQueuedAt(), notNullValue());
assertThat(queuedTaskRun.getStatus(), is(TaskRunStatus.QUEUED));
}
private TaskAttempt prepareAttempt(Class<? extends KunOperator> operatorClass) {
return prepareAttempt(operatorClass, operatorClass.getSimpleName());
}
private TaskAttempt prepareAttempt(Class<? extends KunOperator> operatorClass, String operatorClassName) {
TaskAttempt attempt = MockTaskAttemptFactory.createTaskAttempt();
long operatorId = attempt.getTaskRun().getTask().getOperatorId();
Operator op = MockOperatorFactory.createOperator()
.cloneBuilder()
.withId(operatorId)
.withName("Operator_" + operatorId)
.withClassName(operatorClassName)
.withPackagePath(compileJar(operatorClass, operatorClassName))
.build();
operatorDao.createWithId(op, operatorId);
taskDao.create(attempt.getTaskRun().getTask());
taskRunDao.createTaskRun(attempt.getTaskRun());
taskRunDao.createAttempt(attempt);
return attempt;
}
private TaskAttempt prepareAttempt(Class<? extends KunOperator> operatorClass, TaskAttempt attempt) {
long operatorId = attempt.getTaskRun().getTask().getOperatorId();
Operator op = MockOperatorFactory.createOperator()
.cloneBuilder()
.withId(operatorId)
.withName("Operator_" + operatorId)
.withClassName(operatorClass.getSimpleName())
.withPackagePath(compileJar(operatorClass, operatorClass.getSimpleName()))
.build();
operatorDao.createWithId(op, operatorId);
taskDao.create(attempt.getTaskRun().getTask());
taskRunDao.createTaskRun(attempt.getTaskRun());
taskRunDao.createAttempt(attempt);
return attempt;
}
private TaskAttempt prepareAttempt(Class<? extends KunOperator> operatorClass, String operatorClassName, String fakeClassName) {
TaskAttempt attempt = MockTaskAttemptFactory.createTaskAttempt();
long operatorId = attempt.getTaskRun().getTask().getOperatorId();
com.miotech.kun.workflow.core.model.operator.Operator
op = MockOperatorFactory.createOperator()
.cloneBuilder()
.withId(operatorId)
.withName("Operator_" + operatorId)
.withClassName(fakeClassName)
.withPackagePath(compileJar(operatorClass, operatorClassName))
.build();
operatorDao.createWithId(op, operatorId);
taskDao.create(attempt.getTaskRun().getTask());
taskRunDao.createTaskRun(attempt.getTaskRun());
taskRunDao.createAttempt(attempt);
return attempt;
}
private String compileJar(Class<? extends KunOperator> operatorClass, String operatorClassName) {
return OperatorCompiler.compileJar(operatorClass, operatorClassName);
}
private void assertStatusHistory(Long attemptId, TaskRunStatus... asserts) {
checkArgument(asserts.length > 1);
List<Event> events = eventCollector.getEvents();
List<Event> eventsOfAttempt = events.stream()
.filter(e -> e instanceof TaskAttemptStatusChangeEvent &&
((TaskAttemptStatusChangeEvent) e).getAttemptId() == attemptId)
.collect(Collectors.toList());
logger.info(eventsOfAttempt.toString());
for (int i = 0; i < asserts.length - 1; i++) {
TaskAttemptStatusChangeEvent event = (TaskAttemptStatusChangeEvent) eventsOfAttempt.get(i);
assertThat(event.getAttemptId(), is(attemptId));
assertThat(event.getFromStatus(), is(asserts[i]));
assertThat(event.getToStatus(), is(asserts[i + 1]));
}
}
private TaskAttemptFinishedEvent getFinishedEvent(Long attemptId) {
List<Event> events = eventCollector.getEvents();
events = events.stream()
.filter(e -> e instanceof TaskAttemptFinishedEvent &&
((TaskAttemptFinishedEvent) e).getAttemptId().equals(attemptId))
.collect(Collectors.toList());
return (TaskAttemptFinishedEvent) Iterables.getOnlyElement(events);
}
private void awaitUntilRunning(Long attemptId) {
await().atMost(120, TimeUnit.SECONDS)
.until(() -> {
TaskAttempt attempt = taskRunDao.fetchAttemptById(attemptId).get();
return attempt.getStatus().equals(TaskRunStatus.RUNNING);
});
}
private void awaitUntilOperatorRunning(Long attemptId) {
TaskAttempt taskAttempt = taskRunDao.fetchAttemptById(attemptId).get();
await().atMost(120, TimeUnit.SECONDS).until(() -> {
try {
Resource log = resourceLoader.getResource(taskAttempt.getLogPath());
String content = ResourceUtils.content(log.getInputStream());
return content.contains("Operator start running");
} catch (Exception e) {
return false;
}
});
}
private void awaitUntilProcessDown(String queueName, Integer runningProcess) {
await().atMost(120, TimeUnit.SECONDS).until(() ->
localQueueManager.getCapacity(queueName) == localQueueManager.getResourceQueue(queueName).getWorkerNumbers() - runningProcess
);
}
private void awaitUntilAttemptDone(long attemptId) {
await().atMost(120, TimeUnit.SECONDS).until(() -> {
Optional<TaskRunStatus> s = taskRunDao.fetchTaskAttemptStatus(attemptId);
return s.isPresent() && (s.get().isFinished());
});
}
private void awaitUntilAttemptAbort(long attemptId) {
await().atMost(20, TimeUnit.SECONDS).until(() -> {
Optional<TaskRunStatus> s = taskRunDao.fetchTaskAttemptStatus(attemptId);
return s.isPresent() && (s.get().isAborted());
});
}
private TestWorker2 getTestWorker() {
return new TestWorker2();
}
class TaskAttemptCheckEventListener {
private boolean validateResult;
public void setValidateResult(boolean validateResult) {
this.validateResult = validateResult;
}
@Subscribe
public void onReceive(Event event) {
if (event instanceof TaskAttemptCheckEvent) {
Long taskRunId = ((TaskAttemptCheckEvent) event).getTaskRunId();
CheckResultEvent checkResultEvent = new CheckResultEvent(taskRunId, validateResult);
mockEventSubscriber.receiveEvent(checkResultEvent);
}
}
}
}
|
Sparts Campaigning.
Spartacist League Forms Syrian Battalion in Support of ISIS
RAQQAH, SYRIA – Marking the first time since the Bolivian National Revolution that Trotskyists have rallied in armed defence of their values, members of the Spartacist League of Britain have travelled to “the Caliphate” in order to defend ISIS from “imperialism”.
The formation of the so-called “Hammer Battalion” follows an announcement earlier this week of Spartacist League support for ISIS military victory.
“However, a senior ISIS source has hinted that not everyone in the movement is supportive of the group’s actions: “They spend more time condemning others for not being ISIS enough than actually fighting. Three of our best men were killed last month in a fight over whether the Soviet Union was a ‘deformed’ or ‘degenerated’ worker’s state.”
See more on Workers’ Spatula.
The source for this?
SL/B National Conference Summer 2015. The fight for a Leninist party
We must guard against a tendency, noted in the documents adopted by the December 2014 plenums of the ICL International Executive Committee and the SL/US Central Committee, to succumb to the pressure bearing down on our party to weaken our opposition to imperialism. The reintegration of Crimea into Russia in the aftermath of an imperialist-sponsored, fascist-infested coup in Kiev and the referenda for “self-rule” in the East Ukrainian provinces of Donetsk and Luhansk were largely met with howls of outrage by the liberal and reformist left in the West…. We took a correct, Leninist stance in forthrightly declaring “Crimea is Russian” and in defending the right to self-rule in Eastern Ukraine. The US, supported by Britain, is now at war with the Islamic State (ISIS), which was initially funded by extremist Wahhabis in Saudi Arabia. [An IS motion of 23 October 2014 said:] “We have a military side with the reactionary ISIL when it engages in military conflict with the imperialists and their local forces on the ground, including the Iraqi Kurdish pesh merga, the Baghdad government, Shi’ite militias and the Syrian Kurds. We give no political support to any of these retrograde forces.”…
The justification?
Here is some background:
Workers Vanguard 3rd of April 2015.
It is the duty of class-conscious workers everywhere, particularly in the U.S., to oppose all wars and occupations carried out by the imperialists. When the U.S. began air strikes against ISIS last year, we explained that “any force, however unsavory, that attacks, repels or otherwise impedes U.S. forces strikes a blow in the interests of the exploited and the oppressed” (“U.S. Out of Iraq! No Intervention in Syria!” WV No. 1051, 5 September 2014). We take a military side with ISIS when it targets the imperialists and forces acting as their proxies, including the Baghdad government and the Shi’ite militias as well as the Kurdish pesh merga forces in Northern Iraq and the Syrian Kurdish nationalists. This does not mean we give the slightest political support to the reactionary ISIS butchers.
Workers Hammer(UK) Winter 2014 – 15.
Many liberals and reformist organisations, while claiming to oppose the imperialists’ intervention in Syria/Iraq, are simultaneously backing the Kurdish forces that are acting as imperialist proxies. In the battle for the predominantly Kurdish city of Kobani in northern Syria, the US has carried out airstrikes against ISIS and dropped arms and other supplies to fighters on the ground, mainly from the military wing of the Democratic Union Party (PYD), which is allied to the nationalist Kurdistan Workers Party (PKK) based in Turkey. PYD military forces are acting as ground troops and spotters for the US imperialists, thus tying the fortunes of the oppressed Kurdish population to the imperialists’ war against ISIS. While we uphold the right of national self-determination for the Kurdish people, who are oppressed by the bourgeois regimes in Iran, Iraq, Syria and Turkey, “championing the Kurds in the current conflict can only mean lending support to imperialist plunder”, as we explain in “Down with US/British war against ISIS!”
Workers Vanguard. 31st October 2014.
ISIS today is in battle against the local tools of U.S. imperialism, the main enemy of the world’s working people. A setback for the U.S. in Syria might give pause to Washington in its military adventures, including by encouraging opposition at home. Such opposition adds to the tinder that must be ignited in class struggle against the capitalist rulers who, in their quest for ever greater profits, beat down the workers, black people and immigrants.
In our opinion the Sparts show the ultimate degeneration of revolutionary “defeatism” (wishing the destruction of one’s own ‘ruling class’ and its military).
This is where it led during the Second World War: saying that the Allies, backed by the French Resistance, were the same as the SS and Vichy.
One might say that the ultimate blame for this moral bankrupcy can be put at Trotsky’s feet.
As this indicates – on the eve of the Second World War.
Trotsky sharply rejected any notion of taking sides in the war: By his victories and bestialities, Hitler provokes naturally the sharp hatred of workers the world over. But between this legitimate hatred of workers and the helping of his weaker but less reactionary enemies is an unbridgeable gulf. The victory of the imperialists of Great Britain and France would not be less frightful for the ultimate fate of mankind than that of Hitler and Mussolini. Bourgeois democracy cannot be saved. By helping their bourgeoisie against foreign Fascism, the workers would only accelerate the victory of Fascism in their own country. The task posed by history is not to support one part of the imperialist system against another but to make an end of the system as a whole. Just as in 1914, Trotsky was urging his followers to swim against the stream. In doing so, he cut through the ideological claptrap of the ‘democracies’ opposed to Hitler. What he failed to do was to offer any real indication of a strategy which would enable the tiny Trotskyist current to relate to the broad anti-Fascist movement that would emerge in occupied Europe. More: With the Masses, Against the Stream Marxists Archive.
Ian Birchall, the author of the article cited above, is a lot more forgiving to the “errors” that resulted from these words than the Tendance is.
Advertisements
|
About
I had a dream in 2007 during a nap in Nebraska. I saw the USSR's footage they commanded be shown everytime they were talked of on tv. Before 1983.
I will redo this footage with the kickstarter money.
THE VIDEO - I saw two women. The petite one was sitting and wore a grey wool sweater. It had a black oval on the bust. Also on the bust were two spigots. These fawcetts had 5 pointed handles. The other woman would approach, gesture for permission, then proceeded to move her fingers around the handles. Without touching the handles her fingers were "spider walking" around the air in between the handle points. Every other finger would lift up and reset into the next space. She did this with both hands. (It was similar to Eric Idle in the movie Monty Python's Meaning of Life in the scene with his copper chest plate with fauwcetts on the bust. He says, "Fishy-Fishy-Fishy-Fishy-Foo!") The second scene is a close up of this. The third scene was an angled wall lower left closer and upper right farther. There were odd shaped/painted light bulbs every so often horizontal and vertically spaced on the angled wall.
THE AUDIO - Background noise is tanks crankling- "The USSR State Department commands the following footage be shown everytime they are mentioned in the media. The Russian people get their special feeling from it. It was filmed in the "?" Technique. There is more of this footage to be shown at a later more peaceable date."
This was completely brain welded in 1983. Manchurian Candidate style. But 24 years later I remembered during a nap. All but the technique...we can call it Alzheimer's can't we...Steven V. Garwood
This film will serve as an ad for my improv classical rock music. I am a lead guitarist singer songwriter.
My music videos are on this website...
http://www.stevegarwood.net/
|
<gh_stars>0
package com.example.songthrush;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitX {
private Retrofit retrofit;
private APIInterface apiInterface;
private String BASE_URL = "https://50857eed2072.ngrok.io";
public APIInterface init() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiInterface = retrofit.create(APIInterface.class);
return apiInterface;
}
}
|
// This is the source file for the standalone command line interpreter. It is
// not needed if you are embedding Wren in an application.
static void failIf(bool condition, int exitCode, const char* format, ...)
{
if (!condition) return;
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
exit(exitCode);
}
|
/**
* Label provider for {@link ApplicationLeaf} instances.
*
* @author Alexander Wert
*
*/
public class ApplicationLabelProvider extends StyledCellIndexLabelProvider {
/**
* Empty.
*/
private static final StyledString EMPTY = new StyledString();
/**
* {@inheritDoc}
*/
@Override
protected StyledString getStyledText(Object element, int index) {
if (element instanceof IApplicationProvider) {
ApplicationDefinition appDef = ((IApplicationProvider) element).getApplication();
switch (index) {
case 0:
return new StyledString(appDef.getApplicationName());
case 1:
return new StyledString(String.valueOf(appDef.getBusinessTransactionDefinitions().size()));
case 2:
return new StyledString(TextFormatter.clearLineBreaks(StringUtils.defaultString(appDef.getDescription())));
default:
return EMPTY;
}
}
return EMPTY;
}
/**
* {@inheritDoc}
*/
@Override
protected Image getColumnImage(Object element, int index) {
if (element instanceof IApplicationProvider) {
ApplicationDefinition appDef = ((IApplicationProvider) element).getApplication();
switch (index) {
case 0:
return ImageFormatter.getApplicationDefinitionImage(appDef);
default:
return super.getColumnImage(element, index);
}
}
return super.getColumnImage(element, index);
}
/**
* {@inheritDoc}
*/
@Override
protected Color getForeground(Object element, int index) {
if (element instanceof IApplicationProvider) {
ApplicationDefinition appDefinition = ((IApplicationProvider) element).getApplication();
if (appDefinition.getId() == ApplicationDefinition.DEFAULT_ID) {
return Display.getCurrent().getSystemColor(SWT.COLOR_DARK_CYAN);
}
}
return super.getForeground(element, index);
}
}
|
Manganese Dioxide (α-MnO₂) and Graphene Oxide (GO) Nanocomposites: An Efficient Promotor for the Oxidative Deprotection of Trimethylsilyl, Tetrahydropyranyl and Methoxymethyl Ethers.
Manganese dioxide (α-MnO₂) and graphene oxide (GO nanocomposites were prepared and successfully characterized using Fourier-transform infrared (FT-IR), field emission scanning-electron microscopy (FE-SEM), and energy-dispersive X-ray spectroscopy (EDX) mapping methods and Xray diffraction (XRD) analyses. This reagent is an efficient catalyst for the aerobic oxidation of trimethylsilyl (TMS), tetrahedropyranyl (THP), and methoxymethyl ethers (MOM) to their corresponding carbonyl compounds in the presence of K₂CO₃. All reactions were performed in n-hexane under mild and completely heterogeneous reaction conditions. Our novel method has the advantages of excellent yields, short reaction times, availability and reusability of the catalyst and simple and easy work-up procedure compared to the conventional methods reported in the literature.
|
import { getStaticGetter, transpileModule } from './transpile';
describe('parse props', () => {
it('prop optional', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val?: string;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: true,
reflect: false,
required: false,
type: 'string',
getter: false,
setter: false,
},
});
expect(t.property.attribute).toBe('val');
expect(t.property.type).toBe('string');
expect(t.property.optional).toBe(true);
expect(t.cmp.hasProp).toBe(true);
});
it('prop required', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val!: string;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
reflect: false,
required: true,
type: 'string',
getter: false,
setter: false,
},
});
expect(t.property.required).toBe(true);
});
it('prop mutable', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop({ mutable: true }) val: string;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
defaultValue: undefined,
docs: {
text: '',
tags: [],
},
mutable: true,
optional: false,
reflect: false,
required: false,
type: 'string',
getter: false,
setter: false,
},
});
expect(t.property.mutable).toBe(true);
});
it('prop reflectAttr', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop({ reflect: true }) val: string;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
reflect: true,
required: false,
type: 'string',
getter: false,
setter: false,
},
});
expect(t.property.reflect).toBe(true);
expect(t.cmp.hasReflect).toBe(true);
});
it('prop array', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val: string[];
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
complexType: {
references: {},
resolved: '{}', // TODO, needs to be string[]
original: 'string[]',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
required: false,
type: 'unknown',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('unknown');
expect(t.property.attribute).toBe(undefined);
expect(t.property.reflect).toBe(false);
});
it('prop object', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val: Object;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {
Object: {
location: 'global',
},
},
resolved: 'any',
original: 'Object',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'any',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('any');
expect(t.property.attribute).toBe('val');
expect(t.property.reflect).toBe(false);
});
it('prop multiword', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() multiWord: string;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
multiWord: {
attribute: 'multi-word',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
docs: {
text: '',
tags: [],
},
defaultValue: undefined,
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'string',
getter: false,
setter: false,
},
});
expect(t.property.name).toBe('multiWord');
expect(t.property.attribute).toBe('multi-word');
});
it('prop w/ string type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val: string;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'string',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('string');
expect(t.property.attribute).toBe('val');
});
it('prop w/ number type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val: number;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'number',
original: 'number',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'number',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('number');
expect(t.property.attribute).toBe('val');
});
it('prop w/ boolean type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val: boolean;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'boolean',
original: 'boolean',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'boolean',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('boolean');
expect(t.property.attribute).toBe('val');
});
it('prop w/ any type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val: any;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'any',
original: 'any',
},
docs: {
text: '',
tags: [],
},
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'any',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('any');
expect(t.property.attribute).toBe('val');
});
it('prop w/ inferred string type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val = 'mph';
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
docs: {
text: '',
tags: [],
},
defaultValue: `'mph'`,
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'string',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('string');
expect(t.property.attribute).toBe('val');
});
it('prop w/ inferred number type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val = 88;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'number',
original: 'number',
},
docs: {
text: '',
tags: [],
},
defaultValue: '88',
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'number',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('number');
expect(t.property.attribute).toBe('val');
});
it('prop w/ inferred boolean type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val = false;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'boolean',
original: 'boolean',
},
docs: {
text: '',
tags: [],
},
defaultValue: 'false',
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'boolean',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('boolean');
expect(t.property.attribute).toBe('val');
});
it('prop w/ inferred any type from null', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop() val = null;
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'any',
original: 'any',
},
docs: {
text: '',
tags: [],
},
defaultValue: 'null',
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'any',
getter: false,
setter: false,
},
});
expect(t.property.type).toBe('any');
expect(t.property.attribute).toBe('val');
});
it('prop getter w/ inferred string type', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
@Prop()
get val() {
return 'hello';
};
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'string',
original: 'string',
},
docs: {
text: '',
tags: [],
},
defaultValue: `'hello'`,
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'string',
getter: true,
setter: false,
},
});
expect(t.property.type).toBe('string');
expect(t.property.attribute).toBe('val');
});
it('prop getter w/ inferred number type from property access expression', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
private _numberVal = 3;
@Prop()
get val() {
return this._numberVal;
};
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'number',
original: 'number',
},
docs: {
text: '',
tags: [],
},
defaultValue: `3`,
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'number',
getter: true,
setter: false,
},
});
expect(t.property.type).toBe('number');
expect(t.property.attribute).toBe('val');
});
it('prop getter and setter w/ inferred boolean type from property access expression', () => {
const t = transpileModule(`
@Component({tag: 'cmp-a'})
export class CmpA {
private _boolVal = false;
@Prop()
get val() {
return this._boolVal;
};
set val(newVal: boolean) {
this._boolVal = newVal;
};
}
`);
expect(getStaticGetter(t.outputText, 'properties')).toEqual({
val: {
attribute: 'val',
complexType: {
references: {},
resolved: 'boolean',
original: 'boolean',
},
docs: {
text: '',
tags: [],
},
defaultValue: `false`,
mutable: false,
optional: false,
reflect: false,
required: false,
type: 'boolean',
getter: true,
setter: true,
},
});
expect(t.property.type).toBe('boolean');
expect(t.property.attribute).toBe('val');
});
});
|
For as much as Kevin Love has publicly resisted the discussion of free agency this season, it has been on his mind. He has never been completely comfortable in Cleveland, with his role, nor his connection to those around him. Throughout the year, league sources say, one destination grew in possibility as his exit strategy: The Boston Celtics.
Boston has been no sure thing to lure Love, but it had a better shot than most had believed. If Love left the Cavaliers, the Celtics had closed the gap on the Los Angeles Lakers, league sources told Yahoo Sports.
Scroll to continue with content Ad
An MRI will reveal the extent of damage to Kevin Love's shoulder. (Getty Images)
The Celtics were waiting for July, and the chance to let coach Brad Stevens lay out Love's expanded role in his system. General manager Danny Ainge wanted a chance to sell Love on a vision for surrounding him with complementary talent, on maximizing his popularity as New England's next star.
And so, suddenly, maybe everything changed on Sunday. Kelly Olynyk and Love tangled, Love's left shoulder apparently separated and clearly he's beyond furious. He called the play "bush league," and insisted that Olynyk "did it on purpose."
Within the Celtics, those defending Olynyk privately suggested on Sunday that "he's sort of uncoordinated and awkward" and that played a part in the mishap. Eventually, someone with Boston will probably need to convince Love about that theory too. Love could be lost for Games 1 and 2 of the second-round series against either Chicago or Milwaukee – or longer – based on the results of an MRI exam in Cleveland.
Story continues
It is only natural that if Love lost something significant in Boston – his season, for instance – embracing a free-agent move to the Celtics could be complicated, if not completely compromised. Love left the Garden with legitimate loathing of the Celtics on Sunday, and how that lasts could shape the future of the Cavaliers and Celtics.
Something else happened, too, on Sunday and maybe it turns out to be a benefit for Cleveland's partnership with Love: The Cavs had his back. They went a little crazy, but they had his back. Kendrick Perkins leveled Jae Crowder on a screen, and J.R. Smith floored Crowder with a hellacious backhand to his face. They tried to hurt the Celtics back, and that doesn't happen much in the NBA anymore.
Cleveland's J.R. Smith was ejected from Game 4 after delivering a flagrant foul. (Getty Images)
In the playoffs, futures and fortunes can change in a moment. All hell broke loose in Game 4, and it could take weeks and months to understand the fallout.
When Love was pushing Minnesota for a trade a year ago, he spent a weekend in Boston trying to get a sense of the city. He hit the bars, the box seats at Fenway Park and left intrigued with the possibilities. Boston never had the parts to make a deal with Minnesota, which moved Love to Cleveland for the No. 1 overall pick in the NBA draft. The Cavaliers never would've traded Andrew Wiggins had Love offered team owner Dan Gilbert and general manager David Griffin the slightest uncertainty on his commitment to stay long-term. Cleveland wasn't trading the No. 1 overall pick – in fact, two of them counting Anthony Bennett – for a Love rental.
Nevertheless, Love's commitment at an NBA-sanctioned July meeting in Las Vegas was non-binding. Around the NBA and within the Cavaliers, they understand: Love wouldn't hesitate to bail on the franchise. Love can opt-out of his contract into free agency this summer, or stay one more year and hit the market in 2016. There isn't a team in pursuit of Love who hasn't done significant research and left unconvinced that Love won't minimally explore the market this summer. That was the case before the playoffs, anyway. Before Sunday.
Teams know that Love would want to do something he never had the chance to do pre-trade with the Cavaliers: Sit down, meet with the coach, management and hear how it'll fit for him. That's when those who know Love and Stevens well believed that such a setting would've strengthened the Celtics' candidacy, would've made them the franchise to beat in free agency.
The best chance the Cavaliers had of re-selling Love on a Cavaliers future had been this postseason. He never knew the feeling of winning in the playoffs, nor how things could change once he started making plays in the postseason. If people started to see Love as a winning player making winning plays – not merely an individual chasing stats and endorsements – perhaps that would influence Love about how he feels about his role in that Cleveland system, about his fit in the environment. Around the Cavaliers, there has been a sense of separation this year. Love never seemed fully integrated into the team, nor it with him.
How a free agent feels about his situation in December and January and February can change in April and May and June, and that's what Cleveland had hoped with him.
Everything is unclear now. Love will get an MRI in Cleveland, and everyone will wait to discover the damage done to his shoulder, the damage done to Boston's free-agent pursuit. All hell broke loose at the Garden on Sunday, and suddenly Kevin Love's future became even murkier.
|
ESPN’s Dave Schoenfield, custodian of the SweetSpot blog, recently pointed out a remarkable statistic: in exactly one fewer plate appearance, David Ortiz struck out 62 fewer times in 2011 than 2010. Incredibly, there is very little precedent for such a decline.
Besides Ortiz, only one other player in baseball history struck out 62 fewer times in consecutive 500 PA seasons (within a band of +/- 10 PAs between the two years). In 1975, Jeff Burroughs led the American league with 155 strikeouts, but managed to trim that total to 93 in 1976, despite coming to the plate nine more times, which actually makes his accomplishment more impressive. Otherwise, only six other players experienced a decline of at least 40 strikeouts from one 500 PA season to the next.
Players With the Largest Strikeout Decline, 1901-2011
Note: Includes only a comparison of consecutive 500 PA seasons within a +/- 10 PA band.
Source: fangraphs.com and priority calculations
In terms of strikeout rate (K/PA), Ortiz’ 2011 decline of 10.2% ranks as the second most impressive improvement in consecutive 500 PA seasons. The only other drop off above 10% was turned in by Mark Belanger, who went from 114 strikeouts in 1968 to 54 in 1969. Because Belanger’s decline was accomplished in 63 more plate appearances, his 12.4% improvement easily outdistances even Ortiz’ steep drop-off.
Players With the Largest Strikeout Rate Decline, 1901-2011
Note: Includes only a comparison of consecutive 500 PA seasons.
Source: fangraphs.com and priority calculations
Now that we’ve established that Ortiz’ decline was historic, the next question is how did he do it? Considering the high year-to-year correlation of a player’s strike out rate (h/t fangraphs’ Bill Petti), the chances of such a large decline being random isn’t very likely. So, Big Papi’s improvement suggests he either benefited from a more favorable distribution of his at bats or made a significant adjustment to his approach at the plate.
My first guess was Ortiz may have either faced fewer lefties or simply had a much better season against them, but neither was the case. Not only did Ortiz have one fewer plate appearance against left handers in 2011, but the declines in his strikeouts were the same for both righties (43.1%) and lefties (42.1%). So, the Red Sox’ DH didn’t benefit from a more favorable platoon split.
David Ortiz’ PITCHf/x Data, 2010 vs. 2011
Source: fangraphs.com
The first hint about an explanation comes from an analysis of Ortiz’ PITCHf/x data. The one number that jumps out is the significant increase the rate of contact Ortiz made (Contact%), especially on pitches out of the zone (O-Contact %). As a result, Ortiz’ swing and miss rate (SwStr%) also declined to the lowest level since joining the Red Sox. Meanwhile, Ortiz saw 210 fewer pitches and faced 46 fewer two-strike counts, thanks in large part to 35 more at bats of two pitchers or less (including 26 more outcomes on the first pitch).
David Ortiz’ Batting Count Data, 2010 vs. 2011
Source: baseball-reference.com
Although the natural inference would be to assume Ortiz’ strikeout decline was due to a more aggressive approach, the percentage of balls he offered at was relatively unchanged. Rather, it seems as if pitchers were being more aggressive earlier in the count (perhaps because of the perception that Ortiz’ bat speed was slowing). In 2011, Ortiz saw a first strike in 56.9% of his at bats, an increase from 49.5% the year before. So, if aggression is a factor, the onus is at least as much on the opposition.
Having 46 fewer two-strike counts is a big reason why Ortiz’ K-rate declined so precipitously, but it isn’t the only factor. After all, with two strikes, Big Papi’s K-rate declined from 42.7% in 2010 to 28.2% in 2011. What’s more, he also hit much better with two strikes, increasing his OPS in the split from .686 to .804 (for an sOPS+ of 208). In other words, Ortiz was simply a much better hitter in 2011.
David Ortiz’ Strikeout Rates, 2000 to 2011
Source: fangraphs.com
Perhaps more important than how Ortiz was able to avoid striking out in 2011 is whether he will be able to repeat that performance in 2012. It might seem like a difficult task for a big slugger like Ortiz to maintain such a low strike rate, but a look at his career rates suggests 2010 may be the real outlier. Although Ortiz has had success while striking out at higher rates, the DH’s continued ability to avoiding going down on strikes could dictate the level of his performance in 2012, making his contact rates a bellwether Red Sox fans might want to monitor during the season.
Start Spreading the News! Twitter
Facebook
Reddit
More
Google
Email
LinkedIn
|
int main(void) {
int a, b, c, d, e;
a = nondet();
b = nondet();
c = nondet();
d = nondet();
e = nondet();
while (a < 0 || b < 0 || c < d || e < 0) {
if (a < 0) {
a = -a;
b -= a;
e -= a;
} else if (b < 0) {
b = -b;
a -= b;
c -= b;
} else if (c < 0) {
c = -c;
b -= c;
d -= c;
} else if (d < 0) {
d = -d;
c -= d;
e -= d;
} else if (e < 0) {
e = -e;
d -= e;
a -= e;
}
}
}
|
import * as F from "../src/bacon"
import { run, Sync } from "./_base"
describe("EventStream.delay", () => {
it("results in EventStream", () => {
expect(F.once(1).delay(1)).toBeInstanceOf(F.EventStream)
})
it("delays all events the given amount milliseconds", () => {
const recording = run((record, _, now) => {
F.sequentially(1, [1, 2, 3])
.map(val => ({ tick: now(), val }))
.delay(5)
.onValue(({ val, tick }) => record({ val, delay: now() - tick }))
})
expect(recording).toMatchSnapshot()
})
})
describe("Property.delay", () => {
it("results in Property", () => {
expect(F.constant(1).delay(1)).toBeInstanceOf(F.Property)
})
it("passes initial event immediately and after that delays all events the given amount milliseconds", () => {
const recording = run((record, _, now) => {
F.sequentially(1, [1, 2, 3])
.toProperty(0)
.map(val => ({ tick: now(), val }))
.delay(5)
.onValue(({ val, tick }) => record({ val, delay: now() - tick }))
record(Sync)
})
expect(recording).toMatchSnapshot()
})
})
|
/*
* Wait for capture to stop and all in-flight buffers to be finished with by
* the video hardware. This must be called under &priv->lock
*
*/
static void rcar_vin_wait_stop_streaming(struct rcar_vin_priv *priv)
{
while (priv->state != STOPPED) {
if (priv->state == RUNNING)
rcar_vin_request_capture_stop(priv);
if (priv->state == STOPPING) {
priv->request_to_stop = true;
spin_unlock_irq(&priv->lock);
if (!wait_for_completion_timeout(
&priv->capture_stop,
msecs_to_jiffies(TIMEOUT_MS)))
priv->state = STOPPED;
spin_lock_irq(&priv->lock);
}
}
}
|
<filename>service/secretsmanager/api_op_ListSecretVersionIds.go
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package secretsmanager
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/internal/awsutil"
)
type ListSecretVersionIdsInput struct {
_ struct{} `type:"structure"`
// (Optional) Specifies that you want the results to include versions that do
// not have any staging labels attached to them. Such versions are considered
// deprecated and are subject to deletion by Secrets Manager as needed.
IncludeDeprecated *bool `type:"boolean"`
// (Optional) Limits the number of results that you want to include in the response.
// If you don't include this parameter, it defaults to a value that's specific
// to the operation. If additional items exist beyond the maximum you specify,
// the NextToken response element is present and has a value (isn't null). Include
// that value as the NextToken request parameter in the next call to the operation
// to get the next part of the results. Note that Secrets Manager might return
// fewer results than the maximum even when there are more results available.
// You should check NextToken after every operation to ensure that you receive
// all of the results.
MaxResults *int64 `min:"1" type:"integer"`
// (Optional) Use this parameter in a request if you receive a NextToken response
// in a previous request that indicates that there's more output available.
// In a subsequent call, set it to the value of the previous call's NextToken
// response to indicate where the output should continue from.
NextToken *string `min:"1" type:"string"`
// The identifier for the secret containing the versions you want to list. You
// can specify either the Amazon Resource Name (ARN) or the friendly name of
// the secret.
//
// If you specify an ARN, we generally recommend that you specify a complete
// ARN. You can specify a partial ARN too—for example, if you don’t include
// the final hyphen and six random characters that Secrets Manager adds at the
// end of the ARN when you created the secret. A partial ARN match can work
// as long as it uniquely matches only one secret. However, if your secret has
// a name that ends in a hyphen followed by six characters (before Secrets Manager
// adds the hyphen and six characters to the ARN) and you try to use that as
// a partial ARN, then those characters cause Secrets Manager to assume that
// you’re specifying a complete ARN. This confusion can cause unexpected results.
// To avoid this situation, we recommend that you don’t create secret names
// that end with a hyphen followed by six characters.
//
// SecretId is a required field
SecretId *string `min:"1" type:"string" required:"true"`
}
// String returns the string representation
func (s ListSecretVersionIdsInput) String() string {
return awsutil.Prettify(s)
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListSecretVersionIdsInput) Validate() error {
invalidParams := aws.ErrInvalidParams{Context: "ListSecretVersionIdsInput"}
if s.MaxResults != nil && *s.MaxResults < 1 {
invalidParams.Add(aws.NewErrParamMinValue("MaxResults", 1))
}
if s.NextToken != nil && len(*s.NextToken) < 1 {
invalidParams.Add(aws.NewErrParamMinLen("NextToken", 1))
}
if s.SecretId == nil {
invalidParams.Add(aws.NewErrParamRequired("SecretId"))
}
if s.SecretId != nil && len(*s.SecretId) < 1 {
invalidParams.Add(aws.NewErrParamMinLen("SecretId", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
type ListSecretVersionIdsOutput struct {
_ struct{} `type:"structure"`
// The Amazon Resource Name (ARN) for the secret.
//
// Secrets Manager automatically adds several random characters to the name
// at the end of the ARN when you initially create a secret. This affects only
// the ARN and not the actual friendly name. This ensures that if you create
// a new secret with the same name as an old secret that you previously deleted,
// then users with access to the old secret don't automatically get access to
// the new secret because the ARNs are different.
ARN *string `min:"20" type:"string"`
// The friendly name of the secret.
Name *string `min:"1" type:"string"`
// If present in the response, this value indicates that there's more output
// available than what's included in the current response. This can occur even
// when the response includes no values at all, such as when you ask for a filtered
// view of a very long list. Use this value in the NextToken request parameter
// in a subsequent call to the operation to continue processing and get the
// next part of the output. You should repeat this until the NextToken response
// element comes back empty (as null).
NextToken *string `min:"1" type:"string"`
// The list of the currently available versions of the specified secret.
Versions []SecretVersionsListEntry `type:"list"`
}
// String returns the string representation
func (s ListSecretVersionIdsOutput) String() string {
return awsutil.Prettify(s)
}
const opListSecretVersionIds = "ListSecretVersionIds"
// ListSecretVersionIdsRequest returns a request value for making API operation for
// AWS Secrets Manager.
//
// Lists all of the versions attached to the specified secret. The output does
// not include the SecretString or SecretBinary fields. By default, the list
// includes only versions that have at least one staging label in VersionStage
// attached.
//
// Always check the NextToken response parameter when calling any of the List*
// operations. These operations can occasionally return an empty or shorter
// than expected list of results even when there are more results available.
// When this happens, the NextToken response parameter contains a value to pass
// to the next call to the same API to request the next part of the list.
//
// Minimum permissions
//
// To run this command, you must have the following permissions:
//
// * secretsmanager:ListSecretVersionIds
//
// Related operations
//
// * To list the secrets in an account, use ListSecrets.
//
// // Example sending a request using ListSecretVersionIdsRequest.
// req := client.ListSecretVersionIdsRequest(params)
// resp, err := req.Send(context.TODO())
// if err == nil {
// fmt.Println(resp)
// }
//
// Please also see https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/ListSecretVersionIds
func (c *Client) ListSecretVersionIdsRequest(input *ListSecretVersionIdsInput) ListSecretVersionIdsRequest {
op := &aws.Operation{
Name: opListSecretVersionIds,
HTTPMethod: "POST",
HTTPPath: "/",
Paginator: &aws.Paginator{
InputTokens: []string{"NextToken"},
OutputTokens: []string{"NextToken"},
LimitToken: "MaxResults",
TruncationToken: "",
},
}
if input == nil {
input = &ListSecretVersionIdsInput{}
}
req := c.newRequest(op, input, &ListSecretVersionIdsOutput{})
return ListSecretVersionIdsRequest{Request: req, Input: input, Copy: c.ListSecretVersionIdsRequest}
}
// ListSecretVersionIdsRequest is the request type for the
// ListSecretVersionIds API operation.
type ListSecretVersionIdsRequest struct {
*aws.Request
Input *ListSecretVersionIdsInput
Copy func(*ListSecretVersionIdsInput) ListSecretVersionIdsRequest
}
// Send marshals and sends the ListSecretVersionIds API request.
func (r ListSecretVersionIdsRequest) Send(ctx context.Context) (*ListSecretVersionIdsResponse, error) {
r.Request.SetContext(ctx)
err := r.Request.Send()
if err != nil {
return nil, err
}
resp := &ListSecretVersionIdsResponse{
ListSecretVersionIdsOutput: r.Request.Data.(*ListSecretVersionIdsOutput),
response: &aws.Response{Request: r.Request},
}
return resp, nil
}
// NewListSecretVersionIdsRequestPaginator returns a paginator for ListSecretVersionIds.
// Use Next method to get the next page, and CurrentPage to get the current
// response page from the paginator. Next will return false, if there are
// no more pages, or an error was encountered.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over pages.
// req := client.ListSecretVersionIdsRequest(input)
// p := secretsmanager.NewListSecretVersionIdsRequestPaginator(req)
//
// for p.Next(context.TODO()) {
// page := p.CurrentPage()
// }
//
// if err := p.Err(); err != nil {
// return err
// }
//
func NewListSecretVersionIdsPaginator(req ListSecretVersionIdsRequest) ListSecretVersionIdsPaginator {
return ListSecretVersionIdsPaginator{
Pager: aws.Pager{
NewRequest: func(ctx context.Context) (*aws.Request, error) {
var inCpy *ListSecretVersionIdsInput
if req.Input != nil {
tmp := *req.Input
inCpy = &tmp
}
newReq := req.Copy(inCpy)
newReq.SetContext(ctx)
return newReq.Request, nil
},
},
}
}
// ListSecretVersionIdsPaginator is used to paginate the request. This can be done by
// calling Next and CurrentPage.
type ListSecretVersionIdsPaginator struct {
aws.Pager
}
func (p *ListSecretVersionIdsPaginator) CurrentPage() *ListSecretVersionIdsOutput {
return p.Pager.CurrentPage().(*ListSecretVersionIdsOutput)
}
// ListSecretVersionIdsResponse is the response type for the
// ListSecretVersionIds API operation.
type ListSecretVersionIdsResponse struct {
*ListSecretVersionIdsOutput
response *aws.Response
}
// SDKResponseMetdata returns the response metadata for the
// ListSecretVersionIds request.
func (r *ListSecretVersionIdsResponse) SDKResponseMetdata() *aws.Response {
return r.response
}
|
.
Many mechanisms of different nature-hemodynamic, metabolic and reflex-may cause syncope. We have studied all patients referred for syncope to the Divisions of Cardiology and Neurology of our Hospital, focusing five end-points: standardize a diagnostic protocol; evaluate the diagnostic value of the different tools in the diagnosis of syncope; evaluate the causes of syncope in our patients; value the importance of systematic cardiological-neurological co-operation in these patients; observe the prognosis of patients with syncopal attacks. We have studied 330 patients referred to our Divisions for syncopal attacks (239 in Cardiology and 91 in Neurology) with a protocol organized in 4 steps of increasing levels of complexity: step 1: history, clinical examination, standard electrocardiogram, carotid sinus massage, chest radiography, neurological and cardiological examination; step 2: two-dimensional Doppler echocardiography, dynamic 24-72 hour ECG, standard electroencephalogram (EEG), head-up tilt-table test; step 3: EEG after sleep deprivation, computed tomography, Doppler evaluation of carotid flows, transesophageal electrophysiologic study (EPS); step 4: Oxford test for 24-hour evaluation of arterial blood pressure, intracavitary EPS. We have found in 165 patients (50%) a cardiac syncope, in 78 (23.6%) a reflex syncope, in 43 patients (13%) a syncope of different origin ("non cardiac-non reflex") and in 44 patients (13.4%) we have not been able to find a cause of patient's syncopal attacks. We have established a diagnosis in 148 patients (51.7% of diagnoses) with step 1 examinations, in 98 cases (34.2%) with step 2, in 33 (11.5%) with step 3 and in 7 (2.5%) with step 4 examinations. One hundred-twenty three patients - or relatives of died patients-(37.3%) have answered our follow-up questionnaire (mean follow-up 54.85 +/- 13.73 months, range 36-78 months). Among them, patients with cardiac syncope have had a mortality rate of 18.57%, those with reflex syncope of 7.69%, those with "non cardiac-non reflex" syncope of 7.14%. No patients with syncope of unknown origin died. Our study demonstrates that in the evaluation of patients with syncope, the simplest diagnostic tools are of great value: in fact we have obtained 86% of the diagnoses with the first 2 steps examinations. Furthermore, our study confirms that cardiac syncope has a higher mortality rate compared to other forms of syncope. Co-operation between our Divisions has not been very useful in increasing the number of diagnosed cases, but it has allowed to correctly and rapidly direct our attention toward one form of syncope so that we have been able to speed up the diagnostic process.
|
Suspect Shot, Taken Into Custody Following Barricade Situation At FOX 45
A young man in an animal costume and surgical mask who walked into Baltimore TV station WBFF FOX 45 Thursday claiming to have a bomb was shot and wounded by police, who determined that his alleged explosive consisted of aluminum-wrapped chocolate bars duct-taped to a flotation device.
Police spokesman TJ Smith says the man is hospitalized in serious but stable condition. He was not yet named at a briefing late Thursday afternoon, as he has not yet been charged, but Smith said he is a 25-year-old white male believed to be from Howard County. Police had no further information about the suspect's background.
"It's become all to common in America for us to gather like this to examine the bizarre, dangerous behavior of a singular individual," police Commissioner Kevin Davis said. "I don't have a rational explanation for irrational behavior."
Davis said the man voluntarily walked out of the building and across 41st Street, but did not listen to officers' orders and kept his hands in his pockets. That's when three officers fired a total of at least three shots, striking the suspect at least once. As there was still what he claimed to be a bomb attached to his chest, he remained on the median of 41st Street and is conscious. Police are interacting with him and manipulating his body using a bomb-handling robot.
The device strapped to his chest was actually made up of candy bars wrapped with foil, connected with wiring, a motherboard and apparent fire extinguisher parts wired to a handheld apparatus all meant to resemble a real explosive.
"It does not appear this device was something capable of being an actual explosive," Smith said.
A motive is not yet known.
"Why did he do this? We don't know the answer to that, and we want to know the answer to that," Davis said.
Davis said he realizes people will raise questions about the fact that the man has not yet been treated by paramedics, but emphasized police can't guarantee that the device strapped to the man is safe. The robot has removed the hedgehog onesie worn by the man and removed the rest of his clothes before he was eventually loaded by SWAT officers into an armored vehicle, then an ambulance.
"We want to treat him," Davis said
WBFF reporters and staff from nearby stations are tweeting from the scene. All staff and police are accounted for.
Video of man walking out of @FOXBaltimore pic.twitter.com/3Q2i4gwtw6 — Shelley Orman (@ShelleyOFox45) April 28, 2016
Loud bangs at Fox45... pic.twitter.com/UCKZM0bkwv — Paul McGrew (@McGrewFox45) April 28, 2016
The studio is in the 2000 block of West 41st Street. The building was evacuated around the time police were called at 1:20 p.m. and police and fire resources responded to the scene.
"I would say I've never had to evacuate because of a threat," said WBFF-TV news director Mike Tomko, who added the station's newscasts tonight would proceed as usual if they're allowed back inside.
If not, The Baltimore Sun reports, they will carry the newscast from sister station WJLA or use a remote production truck to broadcast from across the street.
"[The newsroom employees] are a little worried, but everybody's safe," Tomko said. "They're all professionals."
He said it's not unusual for people to visit the station trying to get their message across, but what happened here is: a man wearing a mask and sunglasses entered and said he had a bomb.
The security guard, Jourel Apostolidies, said the man handed him a flash drive. On the drive were videos of the man talking to the camera about what he believed were government conspiracies.
"My first thought was to get him out," he said. "My first instinct was to make sure he keeps his cool head."
The man was wearing a hedgehog onesie, light vest and combat boots, Apostolidies said. After he issued a request for staff to evacuate, he said he sat down and talked with the man.
"I'm not going to say I saw a bomb, what I saw was an attempt to make a fake bomb," he said.
Police credited the work of staff like Apostolidies for surreptitiously calling 911 and facilitating a safe and orderly evacuation.
In 2014, a disturbed man rammed a dump truck into the studios of WMAR-TV in Towson, an incident police spokesman TJ Smith noted led other broadcasters in Baltimore to step up security. The suspect in Thursday's incident got no further than the vestibule.
Davis said a car fire at the scene was arson-related, with a rag around the area of the gas tank. He said police needed to check the other vehicles and the rest of the building, though it's not clear whether the car fire and bomb scare are directly related.
"We're going to be here for a while," Davis said.
LIVE on #Periscope: Fox Baltimore bomb threat https://t.co/eEbYmcWdiw — Casey Clark (@CaseyClarkjr) April 28, 2016
Bomb threat at @FOXBaltimore building. Suspicious person in our lobby. pic.twitter.com/iPDCh2i0Hf — Keith Daniels Fox45 (@KeithDFox45) April 28, 2016
Reporters for Fox 45 say a man walked into the lobby and claimed he had a bomb.
LIVE on #Periscope: Fire in Fox45 parking lot https://t.co/6Zh4i8vNQl — Paul Gessler (@PaulGessler) April 28, 2016
Staff were told to stand back from the building.
|
import { Injectable } from '@nestjs/common';
import { Response } from 'express';
import {
blockchain,
pubsub,
transactionMiner,
transactionPool,
wallet,
} from '../coin';
import Wallet from '../coin/wallet';
export type mineBlock = {
data: any;
};
export type transact = {
amount: number;
recipient: string;
};
@Injectable()
export class ApiService {
pong() {
return {
message: 'pong',
};
}
getBlocks() {
return blockchain.chain;
}
mineBlock(body: mineBlock) {
const { data } = body;
blockchain.addBlock(data);
pubsub.broadcastChain();
}
transact(res: Response, body: transact) {
const { amount, recipient } = body;
let transaction: any = transactionPool.existingTransaction(
wallet.publicKey,
);
try {
if (transaction) {
transaction.update({ senderWallet: wallet, recipient, amount });
} else {
transaction = wallet.createTransaction({
recipient,
amount,
chain: blockchain.chain,
});
}
} catch (err) {
return res.status(400).json({ type: 'error', message: err.message });
}
transactionPool.setTransaction(transaction);
pubsub.broadcastTransaction(transaction);
return { type: 'success', transaction };
}
transactionPoolMap() {
return transactionPool.transactionMap;
}
mineTransactions() {
return transactionMiner.mineTransactions();
}
walletInfo() {
const address = wallet.publicKey;
return {
address,
balance: Wallet.calculateBalance(blockchain.chain, address),
};
}
generateSomeData() {
const wallet1 = new Wallet();
const wallet2 = new Wallet();
const genWalletTransaction = ({ wallet, recipient, amount }) => {
const transaction = wallet.createTransaction({
recipient,
amount,
chain: blockchain.chain,
});
transactionPool.setTransaction(transaction);
};
const walletAction = () =>
genWalletTransaction({ wallet, recipient: wallet1.publicKey, amount: 5 });
const walletAction1 = () =>
genWalletTransaction({
wallet: wallet1,
recipient: wallet2.publicKey,
amount: 15,
});
const walletAction2 = () =>
genWalletTransaction({
wallet: wallet2,
recipient: wallet.publicKey,
amount: 25,
});
for (let i = 0; i < 10; i++) {
if (i % 3 === 0) {
walletAction();
walletAction1();
} else if (i % 3 === 1) {
walletAction();
walletAction2();
} else {
walletAction1();
walletAction2();
}
transactionMiner.mineTransactions();
}
return { message: 'Some data generated' };
}
}
|
<gh_stars>0
package com.rutar.apfloat_point;
import org.apfloat.*;
import static org.apfloat.Apfloat.ZERO;
// ............................................................................
public class ApfloatPoint {
/**
* Значення координати X
*/
public Apfloat x = null;
/**
* Значення координати Y
*/
public Apfloat y = null;
/**
* Точність виконання розрахунків
*/
public static int PRECISION = 12;
/**
* Точка з координатами (0, 0)
*/
public static final ApfloatPoint POINT_ZERO = new ApfloatPoint(0, 0);
/**
* Точка з координатами (1, 1)
*/
public static final ApfloatPoint POINT_ONE = new ApfloatPoint(1, 1);
///////////////////////////////////////////////////////////////////////////////
/**
* Конструктор класу ApfloatPoint
* @param x значення координати X
* @param y значення координати Y
*/
public ApfloatPoint (double x, double y) {
this.x = new Apfloat(x, PRECISION);
this.y = new Apfloat(y, PRECISION);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Конструктор класу ApfloatPoint
* @param x значення координати X
* @param y значення координати Y
*/
public ApfloatPoint (String x, String y) {
this.x = new Apfloat(x, PRECISION);
this.y = new Apfloat(y, PRECISION);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Конструктор класу ApfloatPoint
* @param x значення координати X
* @param y значення координати Y
*/
public ApfloatPoint (Apfloat x, Apfloat y) {
this.x = x.precision(PRECISION);
this.y = y.precision(PRECISION);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод порівнює екземпляр класу з іншим об'єктом класу ApfloatPoint
* @param point об'єкт для порівняння
* @return true, якщо об'єкти еквівалентні
*/
public boolean equals (ApfloatPoint point) {
int compareX = this.x.compareTo(point.x);
int compareY = this.y.compareTo(point.y);
return (compareX == 0) && (compareY == 0);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод порівнює між собою два об'єкти класу ApfloatPoint
* @param first перший об'єкт для порівняння
* @param second другий об'єкт для порівняння
* @return true, якщо об'єкти еквівалентні
*/
public static boolean equals (ApfloatPoint first,
ApfloatPoint second) {
int compareX = first.x.compareTo(second.x);
int compareY = first.y.compareTo(second.y);
return (compareX == 0) && (compareY == 0);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод додає до координат екземпляру класу значення X та Y
* @param x значення для додавання по X
* @param y значення для додавання по Y
* @return результат додавання
*/
public ApfloatPoint add (double x, double y) {
Apfloat X = new Apfloat(x).precision(PRECISION);
Apfloat Y = new Apfloat(y).precision(PRECISION);
return new ApfloatPoint(this.x.add(X).precision(PRECISION),
this.y.add(Y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод додає до координат екземпляру класу значення X та Y
* @param x значення для додавання по X
* @param y значення для додавання по Y
* @return результат додавання
*/
public ApfloatPoint add (Apfloat x, Apfloat y) {
x = x.precision(PRECISION);
y = y.precision(PRECISION);
return new ApfloatPoint(this.x.add(x).precision(PRECISION),
this.y.add(y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод додає до координат екземпляру класу координати заданої точки
* @param point точка для додавання
* @return результат додавання
*/
public ApfloatPoint add (ApfloatPoint point) {
return new ApfloatPoint(x.add(point.x).precision(PRECISION),
y.add(point.y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод віднімає від координат екземпляру класу значення X та Y
* @param x значення для віднімання по X
* @param y значення для віднімання по Y
* @return результат віднімання
*/
public ApfloatPoint subtract (double x, double y) {
Apfloat X = new Apfloat(x).precision(PRECISION);
Apfloat Y = new Apfloat(y).precision(PRECISION);
return new ApfloatPoint(this.x.subtract(X).precision(PRECISION),
this.y.subtract(Y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод віднімає від координат екземпляру класу значення X та Y
* @param x значення для віднімання по X
* @param y значення для віднімання по Y
* @return результат віднімання
*/
public ApfloatPoint subtract (Apfloat x, Apfloat y) {
x = x.precision(PRECISION);
y = y.precision(PRECISION);
return new ApfloatPoint(this.x.subtract(x).precision(PRECISION),
this.y.subtract(y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод віднімає від координат екземпляру класу координати заданої точки
* @param point точка для віднімання
* @return результат віднімання
*/
public ApfloatPoint subtract (ApfloatPoint point) {
return new ApfloatPoint(x.subtract(point.x).precision(PRECISION),
y.subtract(point.y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод перемножує координати екземпляру класу на число
* @param numeric число для множення
* @return результат множення
*/
public ApfloatPoint multiply (double numeric) {
Apfloat N = new Apfloat(numeric).precision(PRECISION);
return new ApfloatPoint(this.x.multiply(N).precision(PRECISION),
this.y.multiply(N).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод перемножує координати екземпляру класу на число
* @param numeric число для множення
* @return результат множення
*/
public ApfloatPoint multiply (Apfloat numeric) {
numeric = numeric.precision(PRECISION);
return new ApfloatPoint(x.multiply(numeric).precision(PRECISION),
y.multiply(numeric).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод перемножує координати екземпляру класу на значення X та Y
* @param x значення для множення по X
* @param y значення для множення по Y
* @return результат множення
*/
public ApfloatPoint multiply (double x, double y) {
Apfloat X = new Apfloat(x).precision(PRECISION);
Apfloat Y = new Apfloat(y).precision(PRECISION);
return new ApfloatPoint(this.x.multiply(X).precision(PRECISION),
this.y.multiply(Y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод перемножує координати екземпляру класу на значення X та Y
* @param x значення для множення по X
* @param y значення для множення по Y
* @return результат множення
*/
public ApfloatPoint multiply (Apfloat x, Apfloat y) {
x = x.precision(PRECISION);
y = y.precision(PRECISION);
return new ApfloatPoint(this.x.multiply(x).precision(PRECISION),
this.y.multiply(y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод перемножує координати екземпляру класу на координати заданої точки
* @param point точка для множення
* @return результат множення
*/
public ApfloatPoint multiply (ApfloatPoint point) {
return new ApfloatPoint(x.multiply(point.x).precision(PRECISION),
y.multiply(point.y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод розділяє координати екземпляру класу на число
* @param numeric число для ділення
* @return результат ділення
*/
public ApfloatPoint divide (double numeric) {
Apfloat N = new Apfloat(numeric).precision(PRECISION);
return new ApfloatPoint(this.x.divide(N).precision(PRECISION),
this.y.divide(N).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод розділяє координати екземпляру класу на число
* @param numeric число для ділення
* @return результат ділення
*/
public ApfloatPoint divide (Apfloat numeric) {
numeric = numeric.precision(PRECISION);
return new ApfloatPoint(x.divide(numeric).precision(PRECISION),
y.divide(numeric).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод розділяє координати екземпляру класу на значення X та Y
* @param x значення для ділення по X
* @param y значення для ділення по Y
* @return результат ділення
*/
public ApfloatPoint divide (double x, double y) {
Apfloat X = new Apfloat(x).precision(PRECISION);
Apfloat Y = new Apfloat(y).precision(PRECISION);
return new ApfloatPoint(this.x.divide(X).precision(PRECISION),
this.y.divide(Y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод розділяє координати екземпляру класу на значення X та Y
* @param x значення для ділення по X
* @param y значення для ділення по Y
* @return результат ділення
*/
public ApfloatPoint divide (Apfloat x, Apfloat y) {
x = x.precision(PRECISION);
y = y.precision(PRECISION);
return new ApfloatPoint(this.x.divide(x).precision(PRECISION),
this.y.divide(y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод розділяє координати екземпляру класу на координати заданої точки
* @param point точка для ділення
* @return результат ділення
*/
public ApfloatPoint divide (ApfloatPoint point) {
return new ApfloatPoint(x.divide(point.x).precision(PRECISION),
y.divide(point.y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод повертає точку за заданий кут відносно центру координат
* @param rotateAngle кут повороту за годинниковою стрілкою
* @return точка, повернена на заданий кут
*/
public ApfloatPoint rotatePoint (double rotateAngle) {
return rotatePoint(POINT_ZERO, rotateAngle);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод повертає точку за заданий кут відносно заданої точки повороту
* @param origin точка, відносно якої здійснюється поворот
* @param rotateAngle кут повороту за годинниковою стрілкою
* @return точка, повернена на заданий кут
*/
public ApfloatPoint rotatePoint (ApfloatPoint origin,
double rotateAngle) {
Apfloat angle = new Apfloat(rotateAngle, PRECISION);
angle = ApfloatMath.toRadians(angle);
Apfloat dx = x.subtract(origin.x);
Apfloat dy = y.subtract(origin.y);
Apfloat X = dy.multiply(ApfloatMath.sin(angle))
.add(dx.multiply(ApfloatMath.cos(angle)));
Apfloat Y = dy.multiply(ApfloatMath.cos(angle))
.subtract(dx.multiply(ApfloatMath.sin(angle)));
return new ApfloatPoint(X.add(origin.x).precision(PRECISION),
Y.add(origin.y).precision(PRECISION));
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод повертає дирекційний кут відрізка, який утворений двома точками
* @param start початкова точка
* @param end кінцева точка
* @return значення дирекційного кута
*/
public static Apfloat getDirectionalAngle (ApfloatPoint start,
ApfloatPoint end) {
// Точки співпадають
if (equals(start, end)) { return ZERO.precision(PRECISION); }
Apfloat dx = end.x.subtract(start.x);
Apfloat dy = end.y.subtract(start.y);
// ............................................................................
// Координати Y співпадають
if (start.y.compareTo(end.y) == 0) {
if (dx.compareTo(ZERO) > 0) { return new Apfloat(0, PRECISION); }
else { return new Apfloat(180, PRECISION); }
}
// ............................................................................
// Координати X співпадають
if (start.x.compareTo(end.x) == 0) {
if (dy.compareTo(ZERO) > 0) { return new Apfloat(90, PRECISION); }
else { return new Apfloat(270, PRECISION); }
}
// ............................................................................
// Виконання обчислень
Apfloat rumb = dy.divide(dx);
Apfloat angle = ApfloatMath.atan(rumb);
angle = ApfloatMath.toDegrees(angle);
angle = ApfloatMath.abs(angle);
// I чверть
if (dx.compareTo(ZERO) > 0 && dy.compareTo(ZERO) > 0)
{ return angle.precision(PRECISION); }
// II чверть
if (dx.compareTo(ZERO) < 0 && dy.compareTo(ZERO) > 0)
{ return new Apfloat(180).subtract(angle).precision(PRECISION); }
// III чверть
if (dx.compareTo(ZERO) < 0 && dy.compareTo(ZERO) < 0)
{ return new Apfloat(180).add(angle).precision(PRECISION); }
// IV чверть
if (dx.compareTo(ZERO) > 0 && dy.compareTo(ZERO) < 0)
{ return new Apfloat(360).subtract(angle).precision(PRECISION); }
return ZERO.precision(PRECISION);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод повертає довжину відрізка між 2 точками
* @param start початкова точка
* @param end кінцева точка
* @return довжина відрізка між 2 точками
*/
public static Apfloat getSegmentLenght (ApfloatPoint start,
ApfloatPoint end) {
Apfloat dx = end.x.subtract(start.x);
Apfloat dy = end.y.subtract(start.y);
Apfloat dx_pow = ApfloatMath.pow(dx, 2);
Apfloat dy_pow = ApfloatMath.pow(dy, 2);
return ApfloatMath.sqrt(dx_pow.add(dy_pow)).precision(PRECISION);
}
///////////////////////////////////////////////////////////////////////////////
/**
* Метод повертає строкове представлення об'єкту ApfloatPoint
* у фіксованій нотації
* @return строкове представлення об'єкту ApfloatPoint
*/
@Override
public String toString() { return toString(true); }
///////////////////////////////////////////////////////////////////////////////
/**
* Метод повертає строкове представлення об'єкту ApfloatPoint у
* фіксованій або експоненційній нотації
* @param pretty якщо true, то використовується фіксована нотація
* @return строкове представлення об'єкту ApfloatPoint
*/
public String toString (boolean pretty)
{ return String.format("ApfloatPoint(%s, %s)",
x.toString(pretty), y.toString(pretty)); }
///////////////////////////////////////////////////////////////////////////////
}
|
//InitEchoWebApp initialize the echo web framework for serving a web application
func InitEchoWebApp(appEnv *env.AppEnv) *echo.Echo {
e := echo.New()
e.HideBanner = true
if config.IsServerDebug() {
e.Debug = true
}
e.Renderer = template.NewRenderer(appEnv.TStore)
e.HTTPErrorHandler = common.LoggingDefaultHTTPErrorHandler
assetHandler := http.FileServer(appEnv.Assets)
e.GET(env.AssetHandlerPattern, apphandler.AssetHandlerFunc(http.StripPrefix(env.AssetPattern, assetHandler)))
e.GET("/health", apphandler.HandleHealth)
e.POST("/loginuser", apphandler.HandleLogin)
e.GET("/logout", apphandler.HandleLogout)
e.GET("/favicon.ico", common.HandleFavicon)
e.Match([]string{"GET", "POST"}, "/entitylist:entity", apphandler.HandleEntityList)
e.Match([]string{"OPTIONS", "POST"}, "/entitylist:entity", apphandler.HandleEntityListAjax)
e.Match([]string{"OPTIONS", "POST"}, "/optionlist:entity", apphandler.HandleOptionListAjax)
e.POST("/entityedit:entity", apphandler.HandleEntityEdit)
e.POST("/entitynew:entity", apphandler.HandleEntityNew)
e.POST("/entitydelete:entity", apphandler.HandleEntityDelete)
e.Match([]string{"GET", "POST"}, "/", apphandler.HandleStartApp)
e.Match([]string{"GET", "POST"}, "/page1", apphandler.HandlePage1)
e.Match([]string{"GET", "POST"}, "/:page", apphandler.HandlePageDefault)
e.Use(apphandler.AppEnvContextMiddleware)
e.Use(common.RequestLoggingMiddleware)
e.Use(apphandler.CookieAuthMiddleware)
return e
}
|
t = int(input())
for _ in range(t):
n = int(input())
bracket_arr = list(input())
#print(bracket_arr)
balance_arr = [False]*n
balancing_dict = {}#unbalanced_val:index
curr = 0
for i in range(n):
if bracket_arr[i] == "(":
curr += 1
balancing_dict[curr] = i
else:
curr -= 1
if curr == -1:
curr = 0
else:
balance_arr[balancing_dict[curr+1]] = True
balance_arr[i] = True
del balancing_dict[curr+1]
#print(curr,i,balance_arr[i])
#print(balancing_dict)
#print(balance_arr)
number_opening_after = [0]*n
number_closing_before = [0]*n
curr = 0
val= 0
for i in range(n-1,-1,-1):
if bracket_arr[i] == "(" and balance_arr[i] == False:
curr += 1
val += 1
number_opening_after[i] = val
curr = 0
val = 0
for i in range(n):
if bracket_arr[i] == ")" and balance_arr[i] == False:
curr += 1
val += 1
number_closing_before[i] = val
#print(number_opening_after,number_closing_before)
opening_used = 0
closing_used = 0
moves = 0
for i in range(n):
#print(bracket_arr[i],number_opening_after[i] - opening_used,number_closing_before[i] - closing_used)
if bracket_arr[i] == "(" and number_closing_before[i] - closing_used > 0:
moves += 1
opening_used += 1
closing_used += 1
if balance_arr[i] == ")" and number_opening_after[i] - opening_used > 0:
moves += 1
opening_used += 1
closing_used += 1
print(moves)
|
/*************************************************************
*
* Copyright (c) 2021-2021 The MathJax Consortium
*
* 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.
*/
/**
* @fileoverview Mappings for the textcomp package.
*
* @author <EMAIL> (<NAME>)
*/
import {CommandMap} from '../SymbolMap.js';
import {TexConstant} from '../TexConstants.js';
import {TextMacrosMethods} from '../textmacros/TextMacrosMethods.js';
import TexParser from '../TexParser.js';
import ParseUtil from '../ParseUtil.js';
import {TextParser} from '../textmacros/TextParser.js';
/**
* Identifiers from the Textcomp package.
*/
new CommandMap('textcomp-macros', {
// Table 3: Predefined LATEX 2ε Text-Mode Commands
'textasciicircum': ['Insert', '\u005E'],
'textasciitilde': ['Insert', '\u007E'],
'textasteriskcentered': ['Insert', '\u002A'],
'textbackslash': ['Insert', '\u005C'],
'textbar': ['Insert', '\u007C'],
'textbraceleft': ['Insert', '\u007B'],
'textbraceright': ['Insert', '\u007D'],
'textbullet': ['Insert', '\u2022'],
'textdagger': ['Insert', '\u2020'],
'textdaggerdbl': ['Insert', '\u2021'],
'textellipsis': ['Insert', '\u2026'],
'textemdash': ['Insert', '\u2014'],
'textendash': ['Insert', '\u2013'],
'textexclamdown': ['Insert', '\u00A1'],
'textgreater': ['Insert', '\u003E'],
'textless': ['Insert', '\u003C'],
'textordfeminine': ['Insert', '\u00AA'],
'textordmasculine': ['Insert', '\u00BA'],
'textparagraph': ['Insert', '\u00B6'],
'textperiodcentered': ['Insert', '\u00B7'],
'textquestiondown': ['Insert', '\u00BF'],
'textquotedblleft': ['Insert', '\u201C'],
'textquotedblright': ['Insert', '\u201D'],
'textquoteleft': ['Insert', '\u2018'],
'textquoteright': ['Insert', '\u2019'],
'textsection': ['Insert', '\u00A7'],
'textunderscore': ['Insert', '\u005F'],
'textvisiblespace': ['Insert', '\u2423'],
// Table 12: textcomp Diacritics
'textacutedbl': ['Insert', '\u02DD'],
'textasciiacute': ['Insert', '\u00B4'],
'textasciibreve': ['Insert', '\u02D8'],
'textasciicaron': ['Insert', '\u02C7'],
'textasciidieresis': ['Insert', '\u00A8'],
'textasciimacron': ['Insert', '\u00AF'],
'textgravedbl': ['Insert', '\u02F5'],
'texttildelow': ['Insert', '\u02F7'],
// Table 13: textcomp Currency Symbols
'textbaht': ['Insert', '\u0E3F'],
'textcent': ['Insert', '\u00A2'],
'textcolonmonetary': ['Insert', '\u20A1'],
'textcurrency': ['Insert', '\u00A4'],
'textdollar': ['Insert', '\u0024'],
'textdong': ['Insert', '\u20AB'],
'texteuro': ['Insert', '\u20AC'],
'textflorin': ['Insert', '\u0192'],
'textguarani': ['Insert', '\u20B2'],
'textlira': ['Insert', '\u20A4'],
'textnaira': ['Insert', '\u20A6'],
'textpeso': ['Insert', '\u20B1'],
'textsterling': ['Insert', '\u00A3'],
'textwon': ['Insert', '\u20A9'],
'textyen': ['Insert', '\u00A5'],
// Table 15: textcomp Legal Symbols
'textcircledP': ['Insert', '\u2117'],
'textcompwordmark': ['Insert', '\u200C'],
'textcopyleft': ['Insert', '\u{1F12F}'],
'textcopyright': ['Insert', '\u00A9'],
'textregistered': ['Insert', '\u00AE'],
'textservicemark': ['Insert', '\u2120'],
'texttrademark': ['Insert', '\u2122'],
// Table 20: Miscellaneous textcomp Symbol
'textbardbl': ['Insert', '\u2016'],
'textbigcircle': ['Insert', '\u25EF'],
'textblank': ['Insert', '\u2422'],
'textbrokenbar': ['Insert', '\u00A6'],
'textdiscount': ['Insert', '\u2052'],
'textestimated': ['Insert', '\u212E'],
'textinterrobang': ['Insert', '\u203D'],
'textinterrobangdown': ['Insert', '\u2E18'],
'textmusicalnote': ['Insert', '\u266A'],
'textnumero': ['Insert', '\u2116'],
'textopenbullet': ['Insert', '\u25E6'],
'textpertenthousand': ['Insert', '\u2031'],
'textperthousand': ['Insert', '\u2030'],
'textrecipe': ['Insert', '\u211E'],
'textreferencemark': ['Insert', '\u203B'],
// 'textthreequartersemdash'
// 'texttwelveudash'
// Table 51: textcomp Text-Mode Delimiters
'textlangle': ['Insert', '\u2329'],
'textrangle': ['Insert', '\u232A'],
'textlbrackdbl': ['Insert', '\u27E6'],
'textrbrackdbl': ['Insert', '\u27E7'],
'textlquill': ['Insert', '\u2045'],
'textrquill': ['Insert', '\u2046'],
// Table 62: textcomp Text-Mode Math and Science Symbols
'textcelsius': ['Insert', '\u2103'],
'textdegree': ['Insert', '\u00B0'],
'textdiv': ['Insert', '\u00F7'],
'textdownarrow': ['Insert', '\u2193'],
'textfractionsolidus': ['Insert', '\u2044'],
'textleftarrow': ['Insert', '\u2190'],
'textlnot': ['Insert', '\u00AC'],
'textmho': ['Insert', '\u2127'],
'textminus': ['Insert', '\u2212'],
'textmu': ['Insert', '\u00B5'],
'textohm': ['Insert', '\u2126'],
'textonehalf': ['Insert', '\u00BD'],
'textonequarter': ['Insert', '\u00BC'],
'textonesuperior': ['Insert', '\u00B9'],
'textpm': ['Insert', '\u00B1'],
'textrightarrow': ['Insert', '\u2192'],
'textsurd': ['Insert', '\u221A'],
'textthreequarters': ['Insert', '\u00BE'],
'textthreesuperior': ['Insert', '\u00B3'],
'texttimes': ['Insert', '\u00D7'],
'texttwosuperior': ['Insert', '\u00B2'],
'textuparrow': ['Insert', '\u2191'],
// Table 110: textcomp Genealogical Symbols
'textborn': ['Insert', '\u002A'],
'textdied': ['Insert', '\u2020'],
'textdivorced': ['Insert', '\u26AE'],
// 'textleaf'
'textmarried': ['Insert', '\u26AD'],
// This is not the correct glyph
'textcentoldstyle': ['Insert', '\u00A2', TexConstant.Variant.OLDSTYLE],
// This is not the correct glyph
'textdollaroldstyle': ['Insert', '\u0024', TexConstant.Variant.OLDSTYLE],
// Table 16: textcomp Old-Style Numerals
'textzerooldstyle': ['Insert', '0', TexConstant.Variant.OLDSTYLE],
'textoneoldstyle': ['Insert', '1', TexConstant.Variant.OLDSTYLE],
'texttwooldstyle': ['Insert', '2', TexConstant.Variant.OLDSTYLE],
'textthreeoldstyle': ['Insert', '3', TexConstant.Variant.OLDSTYLE],
'textfouroldstyle': ['Insert', '4', TexConstant.Variant.OLDSTYLE],
'textfiveoldstyle': ['Insert', '5', TexConstant.Variant.OLDSTYLE],
'textsixoldstyle': ['Insert', '6', TexConstant.Variant.OLDSTYLE],
'textsevenoldstyle': ['Insert', '7', TexConstant.Variant.OLDSTYLE],
'texteightoldstyle': ['Insert', '8', TexConstant.Variant.OLDSTYLE],
'textnineoldstyle': ['Insert', '9', TexConstant.Variant.OLDSTYLE]
}, {
Insert: function(parser: TexParser, name: string, c: string, font: string) {
if (parser instanceof TextParser) {
if (!font) {
TextMacrosMethods.Insert(parser, name, c);
return;
}
parser.saveText();
}
parser.Push(ParseUtil.internalText(
parser, c, font ? {mathvariant: font} : {}));
}
});
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib.pyplot as plt
import sys
import tensorflow as tf
import numpy as np
# Fix Python 2.x.
try: input = raw_input
except NameError: pass
from utils.tfrecordfeatures import *
from preprocess import decode_image, raw_images_to_array
try:
import ipdb as pdb
except Exception:
import pdb
def display_data(file):
gen = tf.python_io.tf_record_iterator(file)
for data_i, string_record in enumerate(gen):
result = tf.train.Example.FromString(string_record)
features = result.features.feature
# maps are np.uint8 arrays. each has a different size.
# wall map: 0 for free space, 255 for walls
map_wall = decode_image(features['map_wall'].bytes_list.value[0])
# door map: 0 for free space, 255 for doors
map_door = decode_image(features['map_door'].bytes_list.value[0])
# roomtype map: binary encoding of 8 possible room categories
# one state may belong to multiple room categories
map_roomtype = decode_image(features['map_roomtype'].bytes_list.value[0])
# roomid map: pixels correspond to unique room ids.
# for overlapping rooms the higher ids overwrite lower ids
map_roomid = decode_image(features['map_roomid'].bytes_list.value[0])
# true states
# (x, y, theta). x,y: pixel coordinates; theta: radians
# coordinates index the map as a numpy array: map[x, y]
true_states = features['states'].bytes_list.value[0]
true_states = np.frombuffer(true_states, np.float32).reshape((-1, 3))
# odometry
# each entry is true_states[i+1]-true_states[i].
# last row is always [0,0,0]
odometry = features['odometry'].bytes_list.value[0]
odometry = np.frombuffer(odometry, np.float32).reshape((-1, 3))
# observations are enceded as a list of png images
rgb = raw_images_to_array(list(features['rgb'].bytes_list.value))
depth = raw_images_to_array(list(features['depth'].bytes_list.value))
print ("True states (first three)")
print (true_states[:3])
print ("Odometry (first three)")
print (odometry[:3])
print("Plot map and first observation")
# note: when printed as an image, map should be transposed
plt.figure()
plt.imshow(map_wall.transpose())
plt.figure()
plt.imshow(rgb[0])
plt.show()
if input("proceed?") != 'y':
break
if __name__ == '__main__':
if len(sys.argv) < 2:
print ("Usage: display_data.py xxx.tfrecords")
exit()
display_data(sys.argv[1])
|
Computational Fluid Dynamic Analysis of Notched Canard Arrangement in Cruise Missiles at Supersonic Flows
This paper tells about the CFD analysis of 2D Canard arrangement in supersonic cruise missiles. High heat dissipation rate causes the Canards to reduce its primary work of providing rotational stability to missile. This paper discusses about the criteria of choosing notched canard model against the present model. The models were designed in GAMBIT and analysed using FLUENT. Various pressure, temperature, velocity vector and XY plots were taken and studied as results. From the results it was clear that the new notched canard arrangement shows less heat dissipation rate against the existing models. This study would be helpful in designing new canard models for missiles esp. for Supersonic cases.
|
def handle_input():
userChoice = input()
if userChoice == "1":
clear()
menus.select_paths_menu()
clear()
menus.specify_client_matter_menu()
print(msg)
get_json_and_pdfs()
elif userChoice == "2":
clear()
menus.select_paths_menu(pdfOption=False)
menus.specify_client_matter_menu()
print(msg)
get_json.thread_download_json()
elif userChoice == "3":
clear()
menus.select_paths_menu()
menus.specify_client_matter_menu()
print(msg)
link_list = get_pdfs.get_urls("json-output")
get_pdfs.thread_download_pdfs(link_list)
elif userChoice == "4":
clear()
menus.other_options_menu()
else:
print("Please Enter Valid input (1, 2 or 3)")
return handle_input()
|
///<reference path='..\..\..\src\compiler\core\environment.ts'/>
///<reference path='..\..\..\src\compiler\io.ts'/>
///<reference path='..\..\..\src\compiler\tsc.ts'/>
module TypeScript.WebTsc {
declare var RealActiveXObject: { new (s: string): any };
function getBrowserIO(env: IEnvironment, fso: any, currentDir: string, stdOut: ITextWriter, stdErr: ITextWriter): IIO {
return {
appendFile: function (path: string, content: string) {
var txtFile = fso.OpenTextFile(path, 8 /* append */, true /* create if file doesn't exist */);
txtFile.Write(content);
txtFile.Close();
},
readFile: function (path: string, codepage: number): FileInformation {
return env.readFile(path, codepage);
},
writeFile: function (path: string, contents: string, writeByteOrderMark: boolean) {
env.writeFile(path, contents, writeByteOrderMark);
},
fileExists: function (path: string): boolean {
return fso.FileExists(path);
},
resolvePath: function (path: string): string {
return fso.GetAbsolutePathName(path);
},
dirName: function (path: string): string {
return fso.GetParentFolderName(path);
},
findFile: function (rootPath: string, partialFilePath: string): IFindFileResult {
var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath;
while (true) {
if (fso.FileExists(path)) {
return { fileInformation: this.readFile(path), path: path };
}
else {
rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath));
if (rootPath == "") {
return null;
}
else {
path = fso.BuildPath(rootPath, partialFilePath);
}
}
}
},
deleteFile: function (path: string): void {
try {
if (fso.FileExists(path)) {
fso.DeleteFile(path, true); // true: delete read-only files
}
} catch (e) {
IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_delete_file_0, [path]), e);
}
},
directoryExists: function (path) {
return <boolean>fso.FolderExists(path);
},
createDirectory: function (path) {
try {
if (!this.directoryExists(path)) {
fso.CreateFolder(path);
}
} catch (e) {
IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_create_directory_0, [path]), e);
}
},
dir: function (path, spec?, options?) {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: any, root: string): string[] {
var paths: string[] = [];
var fc: Enumerator;
if (options.recursive) {
fc = new Enumerator(folder.subfolders);
for (; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for (; !fc.atEnd(); fc.moveNext()) {
if (!spec || fc.item().Name.match(spec)) {
paths.push(root + "/" + fc.item().Name);
}
}
return paths;
}
var folder = fso.GetFolder(path);
var paths: string[] = [];
return filesInFolder(folder, path);
},
print: function (str) {
WScript.StdOut.Write(str);
},
printLine: function (str) {
WScript.Echo(str);
},
arguments: [],
stderr: stdErr,
stdout: stdOut,
watchFile: null,
run: function (source: any, fileName: any) {
try {
eval(source);
} catch (e) {
IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Error_while_executing_file_0, [fileName]), e);
}
},
getExecutingFilePath: function () {
return currentDir + "\\tsc.js";
},
quit: function (exitCode: number = 0) {
}
};
};
function getBrowserEnv(currentDir: string, fso: any): IEnvironment {
return {
// On windows, the newline sequence is always "\r\n";
newLine: "\r\n",
currentDirectory: (): string => {
return currentDir;
},
supportsCodePage: () => {
return false;//(<any>WScript).ReadFile;
},
readFile: function (path: string, codepage: number): FileInformation {
try {
var file = fso.OpenTextFile(path, 1);
var contents: string = file.ReadAll();
return new FileInformation(contents, ByteOrderMark.None);
}
catch (err) {
// -2147024809 is the javascript value for 0x80070057 which is the HRESULT for
// "the parameter is incorrect".
var message: string;
if (err.number === -2147024809) {
message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unsupported_file_encoding, null);
}
else {
message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Cannot_read_file_0_1, [path, err.message]);
}
throw new Error(message);
}
},
writeFile: function (path: string, contents: string, writeByteOrderMark: boolean) {
var file = fso.CreateTextFile(path, true); // overwrite
file.Write(contents);
},
fileExists: function (path: string): boolean {
return fso.FileExists(path);
},
deleteFile: function (path: string): void {
if (fso.FileExists(path)) {
fso.DeleteFile(path, true); // true: delete read-only files
}
},
directoryExists: function (path) {
return <boolean>fso.FolderExists(path);
},
listFiles: function (path, spec?, options?) {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: any, root: string): string[] {
var paths: string[] = [];
var fc: Enumerator;
if (options.recursive) {
fc = new Enumerator(folder.subfolders);
for (; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "\\" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for (; !fc.atEnd(); fc.moveNext()) {
if (!spec || fc.item().Name.match(spec)) {
paths.push(root + "\\" + fc.item().Name);
}
}
return paths;
}
var folder: any = fso.GetFolder(path);
var paths: string[] = [];
return filesInFolder(folder, path);
},
arguments: [],
standardOut: WScript.StdOut,
};
};
class CommandLineParser extends OptionsParser {
public arguments: string[];
public constructor(io: IIO) {
super(io, "");
}
public parse(arguments: string[]) {
this.arguments = arguments;
}
}
export function prepareCompiler(currentDir: string, stdOut: ITextWriter, stdErr: ITextWriter) {
var fso = new RealActiveXObject("Scripting.FileSystemObject");
var shell = new RealActiveXObject("WScript.Shell");
shell.CurrentDirectory = currentDir;
var env = getBrowserEnv(currentDir, fso);
var io = getBrowserIO(env, fso, currentDir, stdOut, stdErr);
return function (commandLine: string) {
var parser = new CommandLineParser(io);
parser.parseString(commandLine);
io.arguments = parser.arguments;
env.arguments = parser.arguments;
var batchCompiler = new BatchCompiler(io);
batchCompiler.batchCompile();
}
}
}
|
Mechanisms underlying T-lymphocyte activation: mitogen initiates and IL-2 amplifies the expression of transferrin receptors via intracellular iron level.
Peripheral blood mononuclear cells (PBM) pulsed with lectin (PHA or Con A for 0.25-3 hr) show a low expression of interleukin-2 and transferrin receptors (IL-2Rs, TfRs) and a mild decline of intracellular ferritin level, compared to control cultures grown in continuous presence of mitogen. Interestingly, lectin-pulsed PBM do not release detectable amounts of IL-2 in the medium. Furthermore, expression of TfRs in these lymphocytes is not inhibited by addition of excess anti-IL-2 neutralizing monoclonal antibody, but is significantly inhibited by treatment with iron salts. These observations suggest that mitogen triggers an IL-2-independent expression of TfRs, at least in part via a decrease of intracellular iron level. Addition of either recombinant IL-2 (rIL-2) or an iron chelator (picolinic acid) to lectin-pulsed PBM induces both a marked enhancement of TfR synthesis and a sharp decline of intracellular ferritin level, which are comparable to the corresponding pattern observed in control cultures. Conversely, addition of iron salts fully inhibits the increase of TfR expression induced by rIL-2. These observations strongly suggest that the enhanced TfR synthesis elicited by rIL-2 is mediated by depletion of a regulatory intracellular iron pool. In line with these studies, greater than 99% purified T lymphocytes stimulated by lectin show a low expression of TfRs, which is markedly enhanced by addition of exogenous rIL-2. Altogether, we postulate that: (i) in resting T lymphocytes the gene encoding TfR is apparently in a 'closed' configuration; (ii) even in the absence of IL-2 activity, a mitogen pulse is sufficient to initiate the expression of TfRs, at least in part via a decline of intracellular iron level; and (iii) TfR synthesis is then largely amplified by IL-2, again via a decrease of the size of a regulatory intracellular iron pool.
|
Ocular perforation and phthisis bulbi secondary to strabismus surgery.
We present our ocular clinicopathologic findings of a child who suffered bilateral perforation of the globe during medial rectus recession bilaterally for congenital esotropia. The right eye progressed to a painful phthisis bulbi and subsequently required enucleation. Penetration or perforation of the sclera during extraocular muscle surgery is not rare; however, serious sequelae such as visual loss or loss of the eye are unusual. Such complications can be avoided if the surgeon is aware of the causes, as well as the dangers, of such perforation, and, in particular, if modern spatula-type needles are used.
|
<gh_stars>10-100
package org.openstack.android.summit.common;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openstack.android.summit.common.utils.HtmlTextParser;
@RunWith(AndroidJUnit4.class)
public class UtilTest {
@Test
public void htmlParserTest(){
String input = "<p><span>Project Onboarding gives attendees a chance to meet some of the project team and get to know the project. Attendees will learn about the project itself, the code structure/ overall architecture, etc, and places where contribution is needed. Attendees will also get to know some of the core contributors and other established community members. Ideally, attendees will know/ have completed the basics of contribution (i.e. irc, gerrit, Launchpad, StoryBoard, Foundation Membership) BEFORE attending the session. All of this can be done through our Contributor Guide[1]. [1] https://docs.openstack.org/contributors/code-and-documentation/index.html</span></p>";
String desiredOutput = "<p><span>Project Onboarding gives attendees a chance to meet some of the project team and get to know the project. Attendees will learn about the project itself, the code structure/ overall architecture, etc, and places where contribution is needed. Attendees will also get to know some of the core contributors and other established community members. Ideally, attendees will know/ have completed the basics of contribution (i.e. irc, gerrit, Launchpad, StoryBoard, Foundation Membership) BEFORE attending the session. All of this can be done through our Contributor Guide[1]. [1] <a href=\"https://docs.openstack.org/contributors/code-and-documentation/index.html\">https://docs.openstack.org/contributors/code-and-documentation/index.html</a></span></p>";
String output = HtmlTextParser.convertLinksToAnchorTags(input);
Assert.assertTrue(desiredOutput.contentEquals(output));
}
}
|
<gh_stars>0
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "syscfg/syscfg.h"
#if MYNEWT_VAL(IMGMGR_CLI)
#include <string.h>
#include <flash_map/flash_map.h>
#include <hal/hal_bsp.h>
#include <shell/shell.h>
#include <console/console.h>
#include <bootutil/image.h>
#include <bootutil/bootutil.h>
#include <base64/hex.h>
#include "imgmgr/imgmgr.h"
#include "imgmgr_priv.h"
static int imgr_cli_cmd(int argc, char **argv);
static struct shell_cmd shell_imgr_cmd = {
.sc_cmd = "imgr",
.sc_cmd_func = imgr_cli_cmd
};
static void
imgr_cli_show_slot(int slot)
{
uint8_t hash[IMGMGR_HASH_LEN]; /* SHA256 hash */
char hash_str[IMGMGR_HASH_LEN * 2 + 1];
struct image_version ver;
char ver_str[IMGMGR_NMGR_MAX_VER];
uint32_t flags;
if (imgr_read_info(slot, &ver, hash, &flags)) {
return;
}
(void)imgr_ver_str(&ver, ver_str);
console_printf("%8s: %s %c\n",
ver_str, hex_format(hash, IMGMGR_HASH_LEN, hash_str, sizeof(hash_str)),
flags & IMAGE_F_NON_BOOTABLE ? ' ' : 'b');
}
static void
imgr_cli_boot_get(void)
{
int rc;
int slot;
/*
* Display test image (if set)
*/
rc = boot_vect_read_test(&slot);
if (rc == 0) {
imgr_cli_show_slot(slot);
} else {
console_printf("No test img set\n");
return;
}
}
static void
imgr_cli_boot_set(char *hash_str)
{
uint8_t hash[IMGMGR_HASH_LEN];
struct image_version ver;
int slot;
int rc;
if (hex_parse(hash_str, strlen(hash_str), hash, sizeof(hash)) !=
sizeof(hash)) {
console_printf("Invalid hash %s\n", hash_str);
return;
}
slot = imgr_find_by_hash(hash, &ver);
if (slot == -1) {
console_printf("Unknown img\n");
return;
}
rc = imgmgr_state_test_slot(slot);
if (rc) {
console_printf("Error setting image to pending; rc=%d\n", rc);
return;
}
}
static int
imgr_cli_cmd(int argc, char **argv)
{
int i;
if (argc < 2) {
console_printf("Too few args\n");
return 0;
}
if (!strcmp(argv[1], "list")) {
for (i = 0; i < 2; i++) {
imgr_cli_show_slot(i);
}
} else if (!strcmp(argv[1], "boot")) {
if (argc > 2) {
imgr_cli_boot_set(argv[2]);
} else {
imgr_cli_boot_get();
}
} else if (!strcmp(argv[1], "ver")) {
imgr_cli_show_slot(boot_current_slot);
} else {
console_printf("Unknown cmd\n");
}
return 0;
}
int
imgr_cli_register(void)
{
return shell_cmd_register(&shell_imgr_cmd);
}
#endif /* MYNEWT_VAL(IMGMGR_CLI) */
|
// Conf returns a copy of the Config used by the proxy.
// Any modifications will not affect the original Config.
func Conf() Config {
configMu.RLock()
defer configMu.RUnlock()
return config
}
|
def start_job(job, hal_id, refGenome, opts):
hal = hal_id
newick_string = get_hal_tree(hal)
job.fileStore.logToMaster("Newick string: %s" % (newick_string))
tree = newick.loads(newick_string)[0]
rerooted = reroot_tree(tree, refGenome)
job.fileStore.logToMaster("Rerooted newick string: %s" % (newick.dumps([rerooted])))
if opts.targetGenomes is not None:
prune_tree(rerooted, opts.targetGenomes)
job.fileStore.logToMaster("Pruned newick string: %s" % newick.dumps(rerooted))
def setup_jobs(node):
prev_data = [setup_jobs(child) for child in node.descendants]
lifted_data = [prev_lifted for _, prev_lifted in prev_data]
merge_job = job.wrapJobFn(merge_blocks_job, node.name, [n.name for n in node.descendants], lifted_data, hal_id, opts)
for prev_job, _ in prev_data:
prev_job.addFollowOn(merge_job)
if node.is_leaf:
job.addChild(merge_job)
if node.ancestor is None:
return merge_job.rv()
else:
original_node = find_node_by_name(tree, node.name)
if original_node.ancestor is None or node.ancestor.name != original_node.ancestor.name:
lift_down_job = merge_job.addFollowOnJobFn(lift_job, 'down', node.name, node.ancestor.name, merge_job.rv(), hal_id, opts)
return lift_down_job, lift_down_job.rv()
else:
lift_up_job = merge_job.addFollowOnJobFn(lift_job, 'up', node.name, node.ancestor.name, merge_job.rv(), hal_id, opts)
return lift_up_job, lift_up_job.rv()
blocks_on_ref = setup_jobs(rerooted)
all_genomes = [node.name for node in tree.walk()]
return job.addFollowOnJobFn(maf_export_job, hal, all_genomes, blocks_on_ref, opts).rv()
|
"Instead of agitating for reform to outlaw certain tactics, why can't employers just say no?" He made the speech at the Gallipoli Club, but those words will be ringing in his ears as he delves into his own difficult and drawn out campaign. Private sector bosses sit on the sidelines egging him but on with grins that say, 'it's not so easy now, is it Eric'. His enemy in the upcoming battle is, primarily, the Community and Public Sector Union which will be joined by other workers collectives he would like to see transported in the Doctor Who Tardis to the middle of last century, such as the Australian Services Union. As his past words show, there is zero chance Senator Abetz can soften his approach on public servants.
Forget about the fact the senate has blocked savings measures ensuring cutbacks in the bureaucracy are even more vital to the Coalition's plans. Forget about the fact public sector cuts can go down pretty well with constituents outside Canberra. The senator must now show the jelly-kneed suits in the private sector how it's done. For anything else to happen would be utter humiliation. Remember, just say 'no'. It's that easy. Now, who wants to go and grab a soft drink? But before the sound of ice cubes hitting lemon, lime and bitters breaks the reverie, there is the issue of 160,000 public servants to deal with and they have stolen a page from Senator Abetz's playbook. They're planning to say 'no' too. This would have been no surprise to the senator and public service workers know this and consequently plan for a long fight in which they intend to tell every half-interested customer ringing Centrelink, Medicare and the Department of Veterans' Affairs for starters - in carefully crafted union messages - just how this government is hurting service delivery by not offering them wages increases to offset inflation.
The Australian Services Union has already been priming its members at the Tax Office with industrial action rhetoric too and these are the people who collect revenue to keep the budget manageable. In the senator's favour is the back-pay issue. There is none. So every month this drags on public servants will feel their current wage being eroded, if only psychologically, by inflation and the lack of any offset in wages, even if it is a less than 1.5 per cent annual increase. Industrial action at the Department of Human Services, if approved, will be watched closely because it is heavily unionised and has contact with almost all Australians through Centrelink and Medicare. Unions will be looking at every disruptive option which avoids loss of pay for members. Strikes will not be high on the agenda. Temporarily shutting down forms of communications within departments in an attempt to confuse management is likely. One thing is certain. Senator Abetz's belief about the threats of "wages explosion" is deeply held and he has a favoured quote which he gave at the January speech.
Like most of his favourites it comes from Labor, this time former treasurer Frank Crean, who once said "one man's pay rise is another man's job".
|
def make_region_beds(normal_bams, seq_method, fasta, baits, annotation,
exclude_access, antitarget_avg_size, target_avg_size):
if seq_method != 'amplicon':
fa_fname = maybe_gunzip(download_link(fasta), "ref", "fa")
access_bed = safe_fname("access", "bed")
cmd = ['access', fa_fname, '--output', access_bed]
if exclude_access:
if isinstance(exclude_access, (list, tuple)):
for excl in exclude_access:
excl_fname = download_link(excl)
cmd.extend(['--exclude', excl_fname])
else:
raise dxpy.AppError("Unexpected type: %r" % exclude_access)
if seq_method == 'wgs':
cmd.extend(['--min-gap-size', '100'])
cnvkit(*cmd)
else:
access_bed = None
if annotation:
annot_fname = maybe_gunzip(download_link(annotation), "annot", "txt")
else:
annot_fname = None
if baits:
bait_bed = download_link(baits)
elif seq_method == 'wgs':
bait_bed = filter_bed_chroms(access_bed)
else:
bait_bed = None
if target_avg_size or not normal_bams:
tgt_bed = safe_fname('targets', 'bed')
cmd_tgt = ['target', bait_bed, '--short-names', '--output', tgt_bed]
if target_avg_size:
cmd_tgt.extend(['--avg-size', target_avg_size])
if annotation:
cmd_tgt.extend(['--annotate', annot_fname])
cnvkit(*cmd_tgt)
if seq_method == 'hybrid':
anti_bed = safe_fname('antitargets', 'bed')
cmd_anti = ['antitarget', bait_bed, '--access', access_bed,
'--output', anti_bed]
if antitarget_avg_size:
cmd_anti.extend(['--avg-size', antitarget_avg_size])
cnvkit(*cmd_anti)
else:
anti_bed = None
else:
def midsize_dxfile(refs):
dxfiles = [dxpy.DXFile(ref) for ref in refs]
if len(dxfiles) == 1:
return dxfiles[0]
def dxsize(dxfile):
return dxfile.describe()['size']
return sorted(dxfiles, key=dxsize)[len(dxfiles) // 2 - 1]
bam_fname = download_link(midsize_dxfile(normal_bams))
cmd_autobin = ['autobin', bam_fname,
'--method', seq_method, '--short-names']
if annotation:
cmd_autobin.extend(['--annotate', annot_fname])
if baits:
cmd_autobin.extend(['--targets', bait_bed])
out_fname_base = fbase(bait_bed)
if access_bed:
cmd_autobin.extend(['--access', access_bed])
if not baits:
out_fname_base = fbase(bam_fname)
tgt_bed = out_fname_base + '.target.bed'
if seq_method == 'hybrid':
anti_bed = out_fname_base + '.antitarget.bed'
else:
anti_bed = None
print("** About to run 'autobin' in docker")
cnvkit(*cmd_autobin)
print("** Ran 'autobin' in docker")
print("** About to upload links to", tgt_bed, "and", anti_bed)
return upload_link(tgt_bed), upload_link(anti_bed)
|
/**
* Stock chart class.<br/>
<b>Note:</b> Use {@link anychart#stock} method to get an instance of this class.
*/
public class ChartsStock extends Chart {
protected ChartsStock(String name) {
super(name);
js.setLength(0);
js.append(String.format(Locale.US, "chart = %s();", name));
jsBase = "chart";
}
public void setOnClickListener(ListenersInterface.OnClickListener listener) {
if (isChain) {
js.append(";");
isChain = false;
}
js.append("chart.listen('pointClick', function(e) {");
if (listener.getFields() != null) {
js.append("var result = ");
for (String field : listener.getFields()) {
js.append(String.format(Locale.US, "'%1$s' + ':' + e.point.get('%1$s') + ',' +", field));
}
js.setLength(js.length() - 8);
js.append(";");
js.append("android.onClick(result);");
} else {
js.append("android.onClick(null);");
}
js.append("});");
ListenersInterface.getInstance().setOnClickListener(listener);
}
private Crosshair getCrosshair;
/**
* Getter for crosshair settings.
*/
public Crosshair getCrosshair() {
if (getCrosshair == null)
getCrosshair = new Crosshair(jsBase + ".crosshair()");
return getCrosshair;
}
private String crosshair;
private Boolean crosshair1;
/**
* Setter for crosshair settings.<br/>
The plot crosshair settings have a higher priority than the chart crosshair settings.
*/
public ChartsStock setCrosshair(String crosshair) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".crosshair(%s)", wrapQuotes(crosshair)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".crosshair(%s)", wrapQuotes(crosshair)));
js.setLength(0);
}
return this;
}
/**
* Setter for crosshair settings.<br/>
The plot crosshair settings have a higher priority than the chart crosshair settings.
*/
public ChartsStock setCrosshair(Boolean crosshair1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".crosshair(%b)", crosshair1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".crosshair(%b)", crosshair1));
js.setLength(0);
}
return this;
}
private Controller getEventMarkers;
/**
* Getter for the event markers controller.
*/
public Controller getEventMarkers() {
if (getEventMarkers == null)
getEventMarkers = new Controller(jsBase + ".eventMarkers()");
return getEventMarkers;
}
private String eventMarkers;
private Boolean eventMarkers1;
/**
* Setter for the event markers controller.
*/
public ChartsStock setEventMarkers(String eventMarkers) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".eventMarkers(%s)", wrapQuotes(eventMarkers)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".eventMarkers(%s)", wrapQuotes(eventMarkers)));
js.setLength(0);
}
return this;
}
/**
* Setter for the event markers controller.
*/
public ChartsStock setEventMarkers(Boolean eventMarkers1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".eventMarkers(%b)", eventMarkers1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".eventMarkers(%b)", eventMarkers1));
js.setLength(0);
}
return this;
}
private Grouping getGrouping;
/**
* Getter for the current data grouping settings.
*/
public Grouping getGrouping() {
if (getGrouping == null)
getGrouping = new Grouping(jsBase + ".grouping()");
return getGrouping;
}
private Boolean grouping;
private String[] grouping1;
private String grouping2;
/**
* Setter for the data grouping settings.
*/
public ChartsStock setGrouping(Boolean grouping) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".grouping(%b)", grouping));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".grouping(%b)", grouping));
js.setLength(0);
}
return this;
}
/**
* Setter for the data grouping settings.
*/
public ChartsStock setGrouping(String[] grouping1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".grouping(%s)", arrayToStringWrapQuotes(grouping1)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".grouping(%s)", arrayToStringWrapQuotes(grouping1)));
js.setLength(0);
}
return this;
}
/**
* Setter for the data grouping settings.
*/
public ChartsStock setGrouping(String grouping2) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".grouping(%s)", wrapQuotes(grouping2)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".grouping(%s)", wrapQuotes(grouping2)));
js.setLength(0);
}
return this;
}
private StockInteractivity getInteractivity;
/**
* Getter for interactivity settings.
*/
public StockInteractivity getInteractivity() {
if (getInteractivity == null)
getInteractivity = new StockInteractivity(jsBase + ".interactivity()");
return getInteractivity;
}
private String interactivity;
private HoverMode interactivity1;
private String interactivity2;
private List<SeparateChart> setInteractivity = new ArrayList<>();
/**
* Setter for interactivity settings.
*/
public SeparateChart setInteractivity(String interactivity) {
if (isChain) {
js.append(";");
isChain = false;
}
js.append(String.format(Locale.US, "var setInteractivity" + ++variableIndex + " = " + jsBase + ".interactivity(%s);", wrapQuotes(interactivity)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, jsBase + ".interactivity(%s)", wrapQuotes(interactivity)));
js.setLength(0);
}
SeparateChart item = new SeparateChart("setInteractivity" + variableIndex);
setInteractivity.add(item);
return item;
}
private String generateJSsetInteractivity() {
if (!setInteractivity.isEmpty()) {
StringBuilder resultJs = new StringBuilder();
for (SeparateChart item : setInteractivity) {
resultJs.append(item.generateJs());
}
return resultJs.toString();
}
return "";
}
private List<SeparateChart> setInteractivity1 = new ArrayList<>();
/**
* Setter for interactivity settings.
*/
public SeparateChart setInteractivity(HoverMode interactivity1) {
if (isChain) {
js.append(";");
isChain = false;
}
js.append(String.format(Locale.US, "var setInteractivity1" + ++variableIndex + " = " + jsBase + ".interactivity(%s);", ((interactivity1 != null) ? interactivity1.generateJs() : "null")));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, jsBase + ".interactivity(%s)", ((interactivity1 != null) ? interactivity1.generateJs() : "null")));
js.setLength(0);
}
SeparateChart item = new SeparateChart("setInteractivity1" + variableIndex);
setInteractivity1.add(item);
return item;
}
private String generateJSsetInteractivity1() {
if (!setInteractivity1.isEmpty()) {
StringBuilder resultJs = new StringBuilder();
for (SeparateChart item : setInteractivity1) {
resultJs.append(item.generateJs());
}
return resultJs.toString();
}
return "";
}
private Plot getPlot;
/**
* Getter for the current plots.
*/
public Plot getPlot() {
if (getPlot == null)
getPlot = new Plot(jsBase + ".plot()");
return getPlot;
}
private List<Plot> getPlot1 = new ArrayList<>();
/**
* Getter for the current plots.
*/
public Plot getPlot(Number index) {
Plot item = new Plot(jsBase + ".plot("+ index+")");
getPlot1.add(item);
return item;
}
private String plot;
private Boolean plot1;
/**
* Setter for the plots.
*/
public ChartsStock setPlot(String plot) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".plot(%s)", wrapQuotes(plot)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".plot(%s)", wrapQuotes(plot)));
js.setLength(0);
}
return this;
}
/**
* Setter for the plots.
*/
public ChartsStock setPlot(Boolean plot1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".plot(%b)", plot1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".plot(%b)", plot1));
js.setLength(0);
}
return this;
}
private Number index1;
private String plot2;
private Boolean plot3;
/**
* Setter for the plots by index.
*/
public ChartsStock setPlot(String plot2, Number index1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".plot(%s, %s)", wrapQuotes(plot2), index1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".plot(%s, %s)", wrapQuotes(plot2), index1));
js.setLength(0);
}
return this;
}
/**
* Setter for the plots by index.
*/
public ChartsStock setPlot(Boolean plot3, Number index1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".plot(%b, %s)", plot3, index1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".plot(%b, %s)", plot3, index1));
js.setLength(0);
}
return this;
}
private Boolean preserveSelectedRangeOnDataUpdate;
/**
* Setter for the Selected Range Change Behaviour.
*/
public ChartsStock setPreserveSelectedRangeOnDataUpdate(Boolean preserveSelectedRangeOnDataUpdate) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".preserveSelectedRangeOnDataUpdate(%b)", preserveSelectedRangeOnDataUpdate));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".preserveSelectedRangeOnDataUpdate(%b)", preserveSelectedRangeOnDataUpdate));
js.setLength(0);
}
return this;
}
private StockScroller getScroller;
/**
* Getter for the current scroller.
*/
public StockScroller getScroller() {
if (getScroller == null)
getScroller = new StockScroller(jsBase + ".scroller()");
return getScroller;
}
private String scroller;
private Boolean scroller1;
/**
* Setter for the scroller.
*/
public ChartsStock setScroller(String scroller) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".scroller(%s)", wrapQuotes(scroller)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".scroller(%s)", wrapQuotes(scroller)));
js.setLength(0);
}
return this;
}
/**
* Setter for the scroller.
*/
public ChartsStock setScroller(Boolean scroller1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".scroller(%b)", scroller1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".scroller(%b)", scroller1));
js.setLength(0);
}
return this;
}
private Grouping getScrollerGrouping;
/**
* Getter for the current scroller data grouping settings.
*/
public Grouping getScrollerGrouping() {
if (getScrollerGrouping == null)
getScrollerGrouping = new Grouping(jsBase + ".scrollerGrouping()");
return getScrollerGrouping;
}
private Boolean scrollerGrouping;
private String[] scrollerGrouping1;
private String scrollerGrouping2;
/**
* Setter for the scroller data grouping settings.
*/
public ChartsStock setScrollerGrouping(Boolean scrollerGrouping) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".scrollerGrouping(%b)", scrollerGrouping));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".scrollerGrouping(%b)", scrollerGrouping));
js.setLength(0);
}
return this;
}
/**
* Setter for the scroller data grouping settings.
*/
public ChartsStock setScrollerGrouping(String[] scrollerGrouping1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".scrollerGrouping(%s)", arrayToStringWrapQuotes(scrollerGrouping1)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".scrollerGrouping(%s)", arrayToStringWrapQuotes(scrollerGrouping1)));
js.setLength(0);
}
return this;
}
/**
* Setter for the scroller data grouping settings.
*/
public ChartsStock setScrollerGrouping(String scrollerGrouping2) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".scrollerGrouping(%s)", wrapQuotes(scrollerGrouping2)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".scrollerGrouping(%s)", wrapQuotes(scrollerGrouping2)));
js.setLength(0);
}
return this;
}
private Number typeOrUnitOrStart;
private String typeOrUnitOrStart1;
private StockRangeType typeOrUnitOrStart2;
private String typeOrUnitOrStart3;
private Interval typeOrUnitOrStart4;
private Number endOrCountOrDispatchEvent;
private String endOrCountOrDispatchEvent1;
private Boolean endOrCountOrDispatchEvent2;
private StockRangeAnchor anchorOrDispatchEvent;
private String anchorOrDispatchEvent1;
private Boolean anchorOrDispatchEvent2;
private Boolean dispatchEvent;
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, Number endOrCountOrDispatchEvent, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, Number endOrCountOrDispatchEvent, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, Number endOrCountOrDispatchEvent, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, String endOrCountOrDispatchEvent1, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, String endOrCountOrDispatchEvent1, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", typeOrUnitOrStart, wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, String endOrCountOrDispatchEvent1, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", typeOrUnitOrStart, wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", typeOrUnitOrStart, wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, Boolean endOrCountOrDispatchEvent2, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, Boolean endOrCountOrDispatchEvent2, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Number typeOrUnitOrStart, Boolean endOrCountOrDispatchEvent2, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", typeOrUnitOrStart, endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, Number endOrCountOrDispatchEvent, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, Number endOrCountOrDispatchEvent, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, Number endOrCountOrDispatchEvent, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, String endOrCountOrDispatchEvent1, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, String endOrCountOrDispatchEvent1, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", wrapQuotes(typeOrUnitOrStart1), wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, String endOrCountOrDispatchEvent1, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", wrapQuotes(typeOrUnitOrStart1), wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", wrapQuotes(typeOrUnitOrStart1), wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, Boolean endOrCountOrDispatchEvent2, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, Boolean endOrCountOrDispatchEvent2, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(String typeOrUnitOrStart1, Boolean endOrCountOrDispatchEvent2, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", wrapQuotes(typeOrUnitOrStart1), endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, Number endOrCountOrDispatchEvent, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, Number endOrCountOrDispatchEvent, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, Number endOrCountOrDispatchEvent, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, String endOrCountOrDispatchEvent1, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, String endOrCountOrDispatchEvent1, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, String endOrCountOrDispatchEvent1, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, Boolean endOrCountOrDispatchEvent2, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, Boolean endOrCountOrDispatchEvent2, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(StockRangeType typeOrUnitOrStart2, Boolean endOrCountOrDispatchEvent2, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", ((typeOrUnitOrStart2 != null) ? typeOrUnitOrStart2.generateJs() : "null"), endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, Number endOrCountOrDispatchEvent, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, Number endOrCountOrDispatchEvent, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, Number endOrCountOrDispatchEvent, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, String endOrCountOrDispatchEvent1, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, String endOrCountOrDispatchEvent1, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, String endOrCountOrDispatchEvent1, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %s, %b, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), wrapQuotes(endOrCountOrDispatchEvent1), anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, Boolean endOrCountOrDispatchEvent2, StockRangeAnchor anchorOrDispatchEvent, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent2, ((anchorOrDispatchEvent != null) ? anchorOrDispatchEvent.generateJs() : "null"), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, Boolean endOrCountOrDispatchEvent2, String anchorOrDispatchEvent1, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %s, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent2, wrapQuotes(anchorOrDispatchEvent1), dispatchEvent));
js.setLength(0);
}
return this;
}
/**
* Selects passed range and initiates data redraw.
*/
public ChartsStock selectRange(Interval typeOrUnitOrStart4, Boolean endOrCountOrDispatchEvent2, Boolean anchorOrDispatchEvent2, Boolean dispatchEvent) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".selectRange(%s, %b, %b, %b)", ((typeOrUnitOrStart4 != null) ? typeOrUnitOrStart4.generateJs() : "null"), endOrCountOrDispatchEvent2, anchorOrDispatchEvent2, dispatchEvent));
js.setLength(0);
}
return this;
}
private Boolean repeat;
private Boolean asRect;
/**
* Starts zoom marquee.
*/
public ChartsStock startZoomMarquee(Boolean repeat, Boolean asRect) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".startZoomMarquee(%b, %b)", repeat, asRect));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".startZoomMarquee(%b, %b)", repeat, asRect));
js.setLength(0);
}
return this;
}
private StockScatterDateTime getXScale;
/**
* Getter for the current stock chart X-scale.
*/
public StockScatterDateTime getXScale() {
if (getXScale == null)
getXScale = new StockScatterDateTime(jsBase + ".xScale()");
return getXScale;
}
private String xScale;
private String xScale1;
/**
* Setter for stock chart X-scale.
*/
public ChartsStock setXScale(String xScale) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".xScale(%s)", wrapQuotes(xScale)));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".xScale(%s)", wrapQuotes(xScale)));
js.setLength(0);
}
return this;
}
private Fill zoomMarqueeFill;
/**
* Setter for fill settings using an array or a string.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock setZoomMarqueeFill(Fill zoomMarqueeFill) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s)", ((zoomMarqueeFill != null) ? zoomMarqueeFill.generateJs() : "null")));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s)", ((zoomMarqueeFill != null) ? zoomMarqueeFill.generateJs() : "null")));
js.setLength(0);
}
return this;
}
private String color;
private Number opacity;
/**
* Fill color with opacity. Fill as a string or an object.
*/
public ChartsStock zoomMarqueeFill(String color, Number opacity) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %s)", wrapQuotes(color), opacity));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %s)", wrapQuotes(color), opacity));
js.setLength(0);
}
return this;
}
private GradientKey[] keys;
private String[] keys1;
private Number angle;
private Boolean mode;
private VectorRect mode1;
private String mode2;
private Number opacity1;
/**
* Linear gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(GradientKey[] keys, Boolean mode, Number angle, Number opacity1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %b, %s, %s)", arrayToString(keys), mode, angle, opacity1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %b, %s, %s)", arrayToString(keys), mode, angle, opacity1));
js.setLength(0);
}
return this;
}
/**
* Linear gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(GradientKey[] keys, VectorRect mode1, Number angle, Number opacity1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToString(keys), ((mode1 != null) ? mode1.generateJs() : "null"), angle, opacity1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToString(keys), ((mode1 != null) ? mode1.generateJs() : "null"), angle, opacity1));
js.setLength(0);
}
return this;
}
/**
* Linear gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(GradientKey[] keys, String mode2, Number angle, Number opacity1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToString(keys), wrapQuotes(mode2), angle, opacity1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToString(keys), wrapQuotes(mode2), angle, opacity1));
js.setLength(0);
}
return this;
}
/**
* Linear gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(String[] keys1, Boolean mode, Number angle, Number opacity1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %b, %s, %s)", arrayToStringWrapQuotes(keys1), mode, angle, opacity1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %b, %s, %s)", arrayToStringWrapQuotes(keys1), mode, angle, opacity1));
js.setLength(0);
}
return this;
}
/**
* Linear gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(String[] keys1, VectorRect mode1, Number angle, Number opacity1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToStringWrapQuotes(keys1), ((mode1 != null) ? mode1.generateJs() : "null"), angle, opacity1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToStringWrapQuotes(keys1), ((mode1 != null) ? mode1.generateJs() : "null"), angle, opacity1));
js.setLength(0);
}
return this;
}
/**
* Linear gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(String[] keys1, String mode2, Number angle, Number opacity1) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToStringWrapQuotes(keys1), wrapQuotes(mode2), angle, opacity1));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s)", arrayToStringWrapQuotes(keys1), wrapQuotes(mode2), angle, opacity1));
js.setLength(0);
}
return this;
}
private GradientKey[] keys2;
private String[] keys3;
private Number cx;
private Number cy;
private GraphicsMathRect mode3;
private Number opacity2;
private Number fx;
private Number fy;
/**
* Radial gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(GradientKey[] keys2, Number cx, Number cy, GraphicsMathRect mode3, Number opacity2, Number fx, Number fy) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s, %s, %s, %s)", arrayToString(keys2), cx, cy, ((mode3 != null) ? mode3.generateJs() : "null"), opacity2, fx, fy));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s, %s, %s, %s)", arrayToString(keys2), cx, cy, ((mode3 != null) ? mode3.generateJs() : "null"), opacity2, fx, fy));
js.setLength(0);
}
return this;
}
/**
* Radial gradient fill.
{docs:Graphics/Fill_Settings}Learn more about coloring.{docs}
*/
public ChartsStock zoomMarqueeFill(String[] keys3, Number cx, Number cy, GraphicsMathRect mode3, Number opacity2, Number fx, Number fy) {
if (!isChain) {
js.append(jsBase);
isChain = true;
}
js.append(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s, %s, %s, %s)", arrayToStringWrapQuotes(keys3), cx, cy, ((mode3 != null) ? mode3.generateJs() : "null"), opacity2, fx, fy));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, ".zoomMarqueeFill(%s, %s, %s, %s, %s, %s, %s)", arrayToStringWrapQuotes(keys3), cx, cy, ((mode3 != null) ? mode3.generateJs() : "null"), opacity2, fx, fy));
js.setLength(0);
}
return this;
}
private Fill imageSettings;
private Stroke color1;
private ColoredFill color2;
private String color3;
private Number thickness;
private String dashpattern;
private StrokeLineJoin lineJoin;
private StrokeLineCap lineCap;
private List<Chart> setZoomMarqueeStroke = new ArrayList<>();
/**
* Setter for the zoom marquee stroke.
{docs:Graphics/Stroke_Settings}Learn more about stroke settings.{docs}
*/
public Chart setZoomMarqueeStroke(Stroke color1, Number thickness, String dashpattern, StrokeLineJoin lineJoin, StrokeLineCap lineCap) {
if (isChain) {
js.append(";");
isChain = false;
}
js.append(String.format(Locale.US, "var setZoomMarqueeStroke" + ++variableIndex + " = " + jsBase + ".zoomMarqueeStroke(%s, %s, %s, %s, %s);", ((color1 != null) ? color1.generateJs() : "null"), thickness, wrapQuotes(dashpattern), ((lineJoin != null) ? lineJoin.generateJs() : "null"), ((lineCap != null) ? lineCap.generateJs() : "null")));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, jsBase + ".zoomMarqueeStroke(%s, %s, %s, %s, %s)", ((color1 != null) ? color1.generateJs() : "null"), thickness, wrapQuotes(dashpattern), ((lineJoin != null) ? lineJoin.generateJs() : "null"), ((lineCap != null) ? lineCap.generateJs() : "null")));
js.setLength(0);
}
Chart item = new Chart("setZoomMarqueeStroke" + variableIndex);
setZoomMarqueeStroke.add(item);
return item;
}
private String generateJSsetZoomMarqueeStroke() {
if (!setZoomMarqueeStroke.isEmpty()) {
StringBuilder resultJs = new StringBuilder();
for (Chart item : setZoomMarqueeStroke) {
resultJs.append(item.generateJs());
}
return resultJs.toString();
}
return "";
}
private List<Chart> setZoomMarqueeStroke1 = new ArrayList<>();
/**
* Setter for the zoom marquee stroke.
{docs:Graphics/Stroke_Settings}Learn more about stroke settings.{docs}
*/
public Chart setZoomMarqueeStroke(ColoredFill color2, Number thickness, String dashpattern, StrokeLineJoin lineJoin, StrokeLineCap lineCap) {
if (isChain) {
js.append(";");
isChain = false;
}
js.append(String.format(Locale.US, "var setZoomMarqueeStroke1" + ++variableIndex + " = " + jsBase + ".zoomMarqueeStroke(%s, %s, %s, %s, %s);", ((color2 != null) ? color2.generateJs() : "null"), thickness, wrapQuotes(dashpattern), ((lineJoin != null) ? lineJoin.generateJs() : "null"), ((lineCap != null) ? lineCap.generateJs() : "null")));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, jsBase + ".zoomMarqueeStroke(%s, %s, %s, %s, %s)", ((color2 != null) ? color2.generateJs() : "null"), thickness, wrapQuotes(dashpattern), ((lineJoin != null) ? lineJoin.generateJs() : "null"), ((lineCap != null) ? lineCap.generateJs() : "null")));
js.setLength(0);
}
Chart item = new Chart("setZoomMarqueeStroke1" + variableIndex);
setZoomMarqueeStroke1.add(item);
return item;
}
private String generateJSsetZoomMarqueeStroke1() {
if (!setZoomMarqueeStroke1.isEmpty()) {
StringBuilder resultJs = new StringBuilder();
for (Chart item : setZoomMarqueeStroke1) {
resultJs.append(item.generateJs());
}
return resultJs.toString();
}
return "";
}
private List<Chart> setZoomMarqueeStroke2 = new ArrayList<>();
/**
* Setter for the zoom marquee stroke.
{docs:Graphics/Stroke_Settings}Learn more about stroke settings.{docs}
*/
public Chart setZoomMarqueeStroke(String color3, Number thickness, String dashpattern, StrokeLineJoin lineJoin, StrokeLineCap lineCap) {
if (isChain) {
js.append(";");
isChain = false;
}
js.append(String.format(Locale.US, "var setZoomMarqueeStroke2" + ++variableIndex + " = " + jsBase + ".zoomMarqueeStroke(%s, %s, %s, %s, %s);", wrapQuotes(color3), thickness, wrapQuotes(dashpattern), ((lineJoin != null) ? lineJoin.generateJs() : "null"), ((lineCap != null) ? lineCap.generateJs() : "null")));
if (isRendered) {
onChangeListener.onChange(String.format(Locale.US, jsBase + ".zoomMarqueeStroke(%s, %s, %s, %s, %s)", wrapQuotes(color3), thickness, wrapQuotes(dashpattern), ((lineJoin != null) ? lineJoin.generateJs() : "null"), ((lineCap != null) ? lineCap.generateJs() : "null")));
js.setLength(0);
}
Chart item = new Chart("setZoomMarqueeStroke2" + variableIndex);
setZoomMarqueeStroke2.add(item);
return item;
}
private String generateJSsetZoomMarqueeStroke2() {
if (!setZoomMarqueeStroke2.isEmpty()) {
StringBuilder resultJs = new StringBuilder();
for (Chart item : setZoomMarqueeStroke2) {
resultJs.append(item.generateJs());
}
return resultJs.toString();
}
return "";
}
private String generateJSgetCrosshair() {
if (getCrosshair != null) {
return getCrosshair.generateJs();
}
return "";
}
private String generateJSgetEventMarkers() {
if (getEventMarkers != null) {
return getEventMarkers.generateJs();
}
return "";
}
private String generateJSgetGrouping() {
if (getGrouping != null) {
return getGrouping.generateJs();
}
return "";
}
private String generateJSgetInteractivity() {
if (getInteractivity != null) {
return getInteractivity.generateJs();
}
return "";
}
private String generateJSgetPlot() {
if (getPlot != null) {
return getPlot.generateJs();
}
return "";
}
private String generateJSgetPlot1() {
if (!getPlot1.isEmpty()) {
StringBuilder resultJs = new StringBuilder();
for (Plot item : getPlot1) {
resultJs.append(item.generateJs());
}
return resultJs.toString();
}
return "";
}
private String generateJSgetScroller() {
if (getScroller != null) {
return getScroller.generateJs();
}
return "";
}
private String generateJSgetScrollerGrouping() {
if (getScrollerGrouping != null) {
return getScrollerGrouping.generateJs();
}
return "";
}
private String generateJSgetXScale() {
if (getXScale != null) {
return getXScale.generateJs();
}
return "";
}
@Override
protected String generateJs() {
if (isChain) {
js.append(";");
isChain = false;
}
js.append(generateJSgetCrosshair());
js.append(generateJSgetEventMarkers());
js.append(generateJSgetGrouping());
js.append(generateJSgetInteractivity());
js.append(generateJSgetPlot());
js.append(generateJSgetPlot1());
js.append(generateJSgetScroller());
js.append(generateJSgetScrollerGrouping());
js.append(generateJSgetXScale());
js.append(generateJSsetInteractivity());
js.append(generateJSsetInteractivity1());
js.append(generateJSsetZoomMarqueeStroke());
js.append(generateJSsetZoomMarqueeStroke1());
js.append(generateJSsetZoomMarqueeStroke2());
js.append(super.generateJsGetters());
js.append(super.generateJs());
String result = js.toString();
js.setLength(0);
return result;
}
}
|
def errBarPlot(
dataFrame,
meanKey="mean",
sDevKey="sDev",
xKey="nBinSize",
rowKey="observable",
colKey="nX",
colorKey="nSamples",
errBarKwargs=None,
shareY=False,
):
for key in [rowKey, colKey, xKey, meanKey, sDevKey, colorKey]:
if not key in dataFrame.columns:
raise KeyError("Key %s not found in input frame" % key)
errBarStyle = {
"linestyle":"None",
"marker":".",
"ms":3,
"lw":1,
"elinewidth":0.5,
"capthick":0.5,
"capsize":0.5,
}
if errBarKwargs:
for key, val in errBarKwargs.items():
errBarStyle[key] = val
colorEntries = dataFrame[colorKey].unique()
nColors = len(colorEntries)
xRange = dataFrame[xKey].unique()
dXmin = max(abs(xRange[-1] - xRange[0]), 0.1)
for nx1, x1 in enumerate(xRange[:-1]):
for x2 in xRange[nx1+1:]:
if abs(x2-x1) < dXmin:
dXmin = abs(x2-x1)
dXmin /= 3
dX = {}
for nEntry, entry in enumerate(colorEntries):
dX[entry] = dXmin*(2*nEntry-nColors+1)*1./nColors
df = dataFrame.copy()
df[xKey] += df.apply(lambda col: dX[col[colorKey]], axis=1)
graph = sns.FacetGrid(
data=df,
row=rowKey,
col=colKey,
hue=colorKey,
palette="Blues",
sharex=True,
sharey="row" if shareY else False,
)
graph.map(plt.errorbar, xKey, meanKey, sDevKey, **errBarStyle)
graph.fig.set(
dpi=500,
figheight=2,
figwidth=len(dataFrame[colKey].unique())*1./2
)
for nax, ax in enumerate(graph.axes.flat):
if not shareY:
ax.set_yticks([])
ax.set_xticks(np.linspace(
dataFrame[xKey].min(), dataFrame[xKey].max(), 3, dtype=int
))
ax.set_xlim(dataFrame[xKey].min()-1, dataFrame[xKey].max()+1)
ax.tick_params(
axis="both",
direction='inout',
width=0.5,
length=2.5,
)
for pos in ["left", "top", "right"]:
ax.spines[pos].set_linewidth(0)
if shareY and nax % len(graph.axes[0]) == 0:
ax.spines["left"].set_linewidth(0.5)
else:
ax.tick_params(
axis="y",
direction='inout',
width=0.0,
length=0.0,
)
ax.spines["bottom"].set_linewidth(0.5)
graph.set_titles("")
means = dataFrame.groupby([rowKey, colKey])[meanKey].mean()
for nCorr, (corrName, axRow) in enumerate(
zip(dataFrame[rowKey].unique(), graph.axes)
):
for nt, ax in zip(dataFrame[colKey].unique(), axRow):
if nCorr == 0:
ax.set_title("{colKey}$ = {nt}$".format(nt=nt, colKey=colKey))
ax.axhline(means[corrName, nt], color="black", ls="--", lw=0.5)
graph.set_ylabels(meanKey)
for corrName, ax in zip(dataFrame[rowKey].unique(), graph.axes[:, -1]):
ax.yaxis.set_label_position("right")
ax.set_ylabel(corrName)
graph.set_xlabels(xKey)
graph.add_legend()
plt.subplots_adjust(wspace=0.1, hspace=0.05)
return graph
|
//! Benchmarking setup for pallet-faucet
use super::*;
use crate::Pallet as Faucet;
use frame_benchmarking::{Box, benchmarks, impl_benchmark_test_suite, whitelisted_caller, account};
use frame_system::RawOrigin;
use scale_info::prelude::format;
use scale_info::prelude::string::String;
const UNIT: u128 = 1_000_000_000_000_000_000u128;
fn string_to_static_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn new_funded_account<T: Config>(index: u32, seed: u32, amount: u128) -> T::AccountId {
let balance_amount = amount.try_into().ok().unwrap();
let name: String = format!("{}{}", index, seed);
let user = account(string_to_static_str(name), index, seed);
<T as pallet::Config>::Currency::make_free_balance_be(&user, balance_amount);
<T as pallet::Config>::Currency::issue(balance_amount);
return user;
}
benchmarks!{
faucet {
let b in 0 .. 1;
let caller = whitelisted_caller();
}: _(RawOrigin::Signed(caller))
donate {
let b in 1 .. 10 ;
let caller = new_funded_account::<T>(b,b, (1000_u128 * UNIT));
}: _(RawOrigin::Signed(caller), (10_u128 * UNIT).try_into().ok().unwrap())
}
|
package com.arif.hibernet.demo;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.arif.hibernet.entity.Instructor;
import com.arif.hibernet.entity.InstructorDetails;
import com.arif.hibernet.entity.Student;
public class DeleteDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetails.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// start a transaction
session.beginTransaction();
//get the instructor by primary key / id
int theID = 1;
Instructor tempInstructor = session.get(Instructor.class, theID);
System.out.println("Found Instructor: " +tempInstructor);
//delete the instructor
if (tempInstructor != null) {
System.out.println("Deleting: " + tempInstructor);
//Note: will also delete "details" object
//because of cascadeAll
session.delete(tempInstructor);
}
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
factory.close();
}
}
}
|
/**
* @file algol.ts
*
* Constant determining the algorithm
*/
/**
* Number of sentences which are not used
*/
export const Cutoff_Sentences = 120;
export const RANKING_EPSILON = 0.000000001;
/*
try 4, 1.2
instead of 8, 1.5
*/
export const calcDist = {
lengthDelta1 : 15,
}
/**
* levenshtein distances above this will not be considered valid
*/
export const Cutoff_LevenShtein : number = 150;
export const Cutoff_WordMatch = 0.935;// 0.85 // 0.98
export const Cutoff_rangeCloseMatch = 0.98;
/**
* Maximum amount of spaces permitted in a combined word
*
* Note that quoted words are never combined, and may exceed this limit,
* e.g. A "q u o t e d" entry.
*/
export const MaxSpacesPerCombinedWord : number = 3;
/**
* Weight factor to use on the a given word distance
* of 0, 1, 2, 3 ....
*/
export const aReinforceDistWeight: Array<number> = [0.1, 0.1, 0.05, 0.02];
/**
* only the top n words are considered
*/
export const Top_N_WordCategorizations = 5;
export const DescribeValueListMinCountValueList = 3;
export const DescribeValueListLengthCharLimit = 60;
|
New Mix: Real Estate, Actress, Wax Fang, More
toggle caption Courtesy of the artists
On any given day, All Songs Considered host Bob Boilen bombards co-host Robin Hilton with a running list of new ideas for the show. Most of them never see the light of day. But on this week's program Bob explains his latest idea, one that everyone will want to see happen. It's called "The Sole Of A Band" and involves matching photos of the shoes worn by bands with their music. You can hear more about how it works at the top of this week's edition of All Songs Considered.
As if that weren't enough, we've also got a great new mix of discoveries for you, including the euphoric Columbus, Ohio band Saintseneca; the joyful, yet otherworldly music of Thumpers; the unforgettable voice of Israeli singer-songwriter Asaf Avidan, and the mesmerizing sounds of producer and electronic musician Darren Cunningham, otherwise known as Actress. Plus sunny new pop from Real Estate, and the epic, conceptual rock of Wax Fang.
|
/// Implementation of the Opus range encoder.
pub mod opus {
/// A c2rust-ified version of the Opus range decoder.
mod imported_decode;
mod imported_encode;
mod decode;
mod encode;
pub use self::decode::Reader;
pub use self::encode::Writer;
}
|
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// IpcAgent implementation that uses a pipe to transfer data.
//
#include "nscon/ipc_agent.h"
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <fcntl.h>
#include "file/base/path.h"
#include "global_utils/time_utils.h"
#include "util/errors.h"
#include "system_api/libc_fs_api.h"
#include "system_api/libc_net_api.h"
#include "system_api/libc_process_api.h"
#include "strings/substitute.h"
using ::util::GlobalTimeUtils;
using ::system_api::GlobalLibcFsApi;
using ::system_api::GlobalLibcNetApi;
using ::system_api::GlobalLibcProcessApi;
using ::system_api::ScopedFileCloser;
using ::std::pair;
using ::std::unique_ptr;
using ::strings::Substitute;
using ::util::Status;
using ::util::StatusOr;
namespace containers {
namespace nscon {
static Status InitSockAddr(struct sockaddr_un *addr, const string &sun_path) {
if (sun_path.length() >= sizeof(addr->sun_path)) {
return Status(::util::error::INTERNAL, "unix-domain-socket path too long");
}
memset(addr, 0, sizeof(struct sockaddr_un));
addr->sun_family = AF_UNIX;
snprintf(addr->sun_path, sizeof(addr->sun_path), "%s", sun_path.c_str());
return Status::OK;
}
// Returns the implementation of the IpcAgent class.
StatusOr<IpcAgent *> IpcAgentFactory::Create() const {
int sock_fd =
GlobalLibcNetApi()->Socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (sock_fd < 0) {
return Status(::util::error::INTERNAL,
Substitute("socket() failed: $0", StrError(errno)));
}
// Auto-close the valid fd in case of errors.
ScopedFileCloser fd_closer(sock_fd);
// TODO(adityakali): Instead of "/tmp", we should create the file under
// rootfs of the job so that it is accessible after pivot_root/chroot.
const string uds_path = ::file::JoinPath(
"/tmp/", Substitute("nscon.uds_$0_$1", GlobalLibcProcessApi()->GetPid(),
GlobalTimeUtils()->MicrosecondsSinceEpoch().value()));
struct sockaddr_un addr;
RETURN_IF_ERROR(InitSockAddr(&addr, uds_path));
if (GlobalLibcNetApi()->Bind(sock_fd, (struct sockaddr *)&addr,
sizeof(addr)) < 0) {
return Status(::util::error::INTERNAL,
Substitute("bind() failed: $0", StrError(errno)));
}
// chmod() the UDS file to 0777 so that the child process can connect to it
// even after changing its uid.
if (GlobalLibcFsApi()->ChMod(uds_path.c_str(), 0777) < 0) {
return Status(::util::error::INTERNAL,
Substitute("chmod('$0', 0777) failed: $1",
uds_path.c_str(), StrError(errno)));
}
if (GlobalLibcNetApi()->Listen(sock_fd, 1) < 0) {
return Status(::util::error::INTERNAL,
Substitute("listen() failed: $0", StrError(errno)));
}
// Now initialize the pipe.
int pipefd[2];
if (GlobalLibcFsApi()->Pipe2(pipefd, O_CLOEXEC) < 0) {
return Status(::util::error::INTERNAL,
Substitute("pipe2() failed: $0", StrError(errno)));
}
fd_closer.Cancel();
return new IpcAgent(sock_fd, uds_path, pipefd);
}
IpcAgent::~IpcAgent() {
if (sock_fd_ >= 0) {
GlobalLibcFsApi()->Close(sock_fd_);
}
if (pipefd_read_ >= 0) {
GlobalLibcFsApi()->Close(pipefd_read_);
}
if (pipefd_write_ >= 0) {
GlobalLibcFsApi()->Close(pipefd_write_);
}
}
Status IpcAgent::Destroy() {
if (GlobalLibcFsApi()->Unlink(uds_path_.c_str()) < 0) {
return Status(
::util::error::INTERNAL,
Substitute("unlink($0) failed: $1", uds_path_, StrError(errno)));
}
delete this;
return Status::OK;
}
// Creates a new socket and connects it to the unix-domain-path for
// communication. We need to take care that we call only basic system calls here
// as this gets invoked from between fork() and exec(). Using ScopedCleanup too
// resulted in a hang.
Status IpcAgent::WriteData(const string &data) {
int fd = GlobalLibcNetApi()->Socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
return Status(::util::error::INTERNAL,
Substitute("socket() failed: $0", StrError(errno)));
}
struct sockaddr_un addr;
Status status = InitSockAddr(&addr, uds_path_);
if (!status.ok()) {
GlobalLibcFsApi()->Close(fd);
return status;
}
if (GlobalLibcNetApi()->Connect(fd, (struct sockaddr *)&addr, sizeof(addr)) <
0) {
GlobalLibcFsApi()->Close(fd);
return Status(::util::error::INTERNAL,
Substitute("connect() failed: $0", StrError(errno)));
}
ssize_t sent = GlobalLibcNetApi()->Send(fd, data.c_str(), data.size(), 0);
if (sent < 0) {
GlobalLibcFsApi()->Close(fd);
return Status(::util::error::INTERNAL,
Substitute("send() failed: $0", StrError(errno)));
}
GlobalLibcFsApi()->Close(fd);
return Status::OK;
}
StatusOr<pair<string, pid_t>> IpcAgent::ReadData() {
int fd;
do {
fd = GlobalLibcNetApi()->Accept(sock_fd_, 0, 0);
if (fd >= 0) {
break;
}
if (errno == EINTR) {
continue;
}
return Status(::util::error::INTERNAL,
Substitute("accept() failed: $0", StrError(errno)));
// TODO(adityakali): Use SOCK_NONBLOCK above and wait for only few seconds.
} while (1);
// Auto-close the valid fd in case of errors.
ScopedFileCloser fd_closer(fd);
struct ucred credential;
socklen_t len = sizeof(credential);
if (GlobalLibcNetApi()->GetSockOpt(fd, SOL_SOCKET, SO_PEERCRED, &credential,
&len) < 0) {
return Status(::util::error::INTERNAL,
Substitute("getsockopt() failed: $0", StrError(errno)));
}
pid_t sender = credential.pid;
// Read data from socket.
char buf[4096];
memset(buf, 0, sizeof(buf));
ssize_t recvd = GlobalLibcNetApi()->Recv(fd, buf, sizeof(buf), 0);
if (recvd < 0) {
return Status(::util::error::INTERNAL,
Substitute("recv() failed: $0", StrError(errno)));
}
return pair<string, pid_t>(buf, sender);
}
Status IpcAgent::WaitForChild() {
CHECK_GE(pipefd_read_, 0);
// Close write end of the pipe. Wait on read end.
if (pipefd_write_ >= 0) {
GlobalLibcFsApi()->Close(pipefd_write_);
pipefd_write_ = -1;
}
char x;
// The remote process will always send us 1 byte data.
int ret = GlobalLibcFsApi()->Read(pipefd_read_, &x, 1);
if (ret < 0) {
return Status(::util::error::INTERNAL,
Substitute("read() failed: $0", StrError(errno)));
} else if (ret == 0) {
// Connection closed at the other end.
return Status(::util::error::CANCELLED,
Substitute("Remote ended the connection."));
}
return Status::OK;
}
Status IpcAgent::SignalParent() {
CHECK_GE(pipefd_write_, 0);
// Close read end of the pipe. Signal using the write end.
if (pipefd_read_ >= 0) {
GlobalLibcFsApi()->Close(pipefd_read_);
pipefd_read_ = -1;
}
if (GlobalLibcFsApi()->Write(pipefd_write_, "x", 1) != 1) {
return Status(::util::error::INTERNAL,
Substitute("write() failed: $0", StrError(errno)));
}
return Status::OK;
}
} // namespace nscon
} // namespace containers
|
/**
* Information about adverse reactions and/or propensity to adverse reaction of
* the patient (including allergies and intolerances), and any relevant reaction
* details.
*
*/
public class AdverseReactionImpl implements AdverseReaction {
private List<? extends Manifestation> mfsts;
private Coded agent;
private UniqueIdentifier id = UniqueIdentifierImpl.random();
/**
* @param manifestations - Clinical manifestation of the adverse reaction expressed as a single
* word, phrase or brief description. VOCAB is SNOMED CT AU codes.
*
*
* @param substanceAgent - Identification of a substance, agent, or a class of substance, that is
* considered to be responsible for the adverse reaction.
*/
public AdverseReactionImpl( Coded substanceAgent, List<? extends Manifestation> manifestations) {
this.mfsts = manifestations;
this.agent = substanceAgent;
}
/**
* Identification of a substance, agent, or a class of substance, that is
* considered to be responsible for the adverse reaction.
*/
@Override
public Coded getSubstanceAgent() {
return agent;
}
/**
*
*
* Details about each adverse reaction event.
*
* Clinical manifestation of the adverse reaction expressed as a single
* word, phrase or brief description
*
* These should be SNOMED CT-AU Clinical Manifestation Values
*/
@Override
public List<? extends Manifestation> getManifestations() {
return mfsts;
}
/**
* This is a technical identifier that is used for system purposes such as
* matching. If a suitable internal key is not available, a UUID may be
* used.
*
*
* Random UUID if not explicitly set
*
*/
@Override
public UniqueIdentifier getID() {
return id;
}
public void setID(UniqueIdentifier id) {
this.id = id;
}
}
|
// TODO(todd): this is an obvious spot to add codegen - there's a ton of branching
// and such around the comparisons. A simple experiment indicated there's some
// 2x to be gained.
Status MergeIterator::MaterializeBlock(RowBlock *dst) {
dst->selection_vector()->SetAllTrue();
for (size_t dst_row_idx = 0; dst_row_idx < dst->nrows(); dst_row_idx++) {
RowBlockRow dst_row = dst->row(dst_row_idx);
MergeIterState *smallest = nullptr;
ssize_t smallest_idx = -1;
for (size_t i = 0; i < states_.size(); i++) {
unique_ptr<MergeIterState> &state = states_[i];
if (PREDICT_FALSE(smallest == nullptr)) {
smallest = state.get();
smallest_idx = i;
} else {
num_comparisons_++;
if (schema_->Compare(state->next_row(), smallest->next_row()) < 0) {
smallest = state.get();
smallest_idx = i;
}
}
}
if (PREDICT_FALSE(smallest == nullptr)) break;
RETURN_NOT_OK(CopyRow(smallest->next_row(), &dst_row, dst->arena()));
RETURN_NOT_OK(smallest->Advance());
if (smallest->IsFullyExhausted()) {
std::lock_guard<rw_spinlock> l(states_lock_);
smallest->AddStats(&finished_iter_stats_by_col_);
states_.erase(states_.begin() + smallest_idx);
}
}
return Status::OK();
}
|
package notification
import (
"fmt"
"io/ioutil"
"time"
"github.com/authelia/authelia/internal/configuration/schema"
)
// FileNotifier a notifier to send emails to SMTP servers.
type FileNotifier struct {
path string
}
// NewFileNotifier create an FileNotifier writing the notification into a file.
func NewFileNotifier(configuration schema.FileSystemNotifierConfiguration) *FileNotifier {
return &FileNotifier{
path: configuration.Filename,
}
}
// Send send a identity verification link to a user.
func (n *FileNotifier) Send(recipient string, subject string, body string) error {
content := fmt.Sprintf("Date: %s\nRecipient: %s\nSubject: %s\nBody: %s", time.Now(), recipient, subject, body)
err := ioutil.WriteFile(n.path, []byte(content), 0755)
if err != nil {
return err
}
return nil
}
|
<reponame>darmstrong1/filecopier<filename>filecopier-gui/src/main/java/net/sf/fc/gui/factory/MVCFactory.java<gh_stars>0
package net.sf.fc.gui.factory;
import javax.swing.undo.UndoManager;
import javax.xml.bind.JAXBException;
import net.sf.fc.cfg.AppFactory;
import net.sf.fc.cfg.DirPath;
import net.sf.fc.gui.c.options.OptionsController;
import net.sf.fc.gui.c.settings.SettingsController;
import net.sf.fc.gui.m.options.OptionsModel;
import net.sf.fc.gui.m.settings.SettingsModel;
import net.sf.fc.gui.v.options.OptionsDialog;
import net.sf.fc.gui.v.settings.SettingsDialog;
import net.sf.fc.gui.v.settings.SettingsPanel;
import net.sf.fc.script.OptionsScriptProxy;
import net.sf.fc.script.SettingsProxy;
import net.sf.fc.script.gen.options.OptionsScript;
import net.sf.fc.script.gen.settings.Settings;
/**
* MVCFactory creates singleton objects. Any object that depends on one of the objects created in MVCFactory should
* take that object as an argument in its constructor. Any object that depends on more than one object created in
* AppFactory should take AppFactory as an argument in its constructor. It contains an AppFactory that has the same
* principles.
*
* @author <NAME>
*
*/
public final class MVCFactory {
// Settings objects
private final SettingsController settingsController;
private final SettingsModel settingsModel;
private final SettingsDialog settingsDialog;
// Default Options Controller
private final OptionsController defaultOptionsController;
// Default Options model
private final OptionsModel defaultOptionsModel;
// Default Options Dialog
private final OptionsDialog defaultOptionsDialog;
private final MVCRequestFactory mvcRequestFactory;
public static final int FILE_COPY_FILTER_IDX = 0;
public static final int DIR_COPY_FILTER_IDX = 1;
public static final int FLATTEN_FILTER_IDX = 2;
public static final int MERGE_FILTER_IDX = 3;
public MVCFactory(AppFactory appFactory) throws JAXBException {
SettingsProxy settingsProxy = appFactory.getSettingsProxy();
settingsController = new SettingsController();
settingsModel = new SettingsModel(settingsProxy);
settingsDialog = createSettingsDialog(settingsProxy.getSettings(), settingsController);
initSettings();
defaultOptionsController = new OptionsController();
DirPath optionsPath = new DirPath(settingsProxy.getSettings().getPaths().getOptionsPath());
OptionsScriptProxy optionsScriptProxy = appFactory.getDiskDefaultOptionsScriptProxy();
defaultOptionsModel = MVCOptionsFactory.createOptionsModel(optionsScriptProxy,
appFactory.getCachedDefaultOptionsScriptProxy().getOptions(),
appFactory.getRequestFactory());
defaultOptionsDialog = createDefaultOptionsDialog(optionsScriptProxy.getOptions(),
defaultOptionsController, optionsPath);
initOptions();
mvcRequestFactory = new MVCRequestFactory(appFactory.getRequestFactory(),
appFactory.getCachedDefaultOptionsScriptProxy().getOptions(),
settingsProxy);
}
private void initSettings() {
settingsController.addModel(settingsModel);
}
private void initOptions() {
defaultOptionsController.addModel(defaultOptionsModel);
}
private OptionsDialog createDefaultOptionsDialog(OptionsScript optionsScript, OptionsController optionsController, DirPath optionsPath) {
UndoManager undoManager = new UndoManager();
return new OptionsDialog("Default Options", optionsController,
MVCOptionsFactory.createOptionsPanel(optionsScript, optionsController, undoManager),
optionsPath, undoManager, true);
}
private SettingsDialog createSettingsDialog(Settings settings, SettingsController settingsController) {
UndoManager undoManager = new UndoManager();
return new SettingsDialog(new SettingsPanel(settings, settingsController, undoManager), settingsController, undoManager);
}
public SettingsController getSettingsController() {
return settingsController;
}
public SettingsModel getSettingsModel() {
return settingsModel;
}
public OptionsController getDefaultOptionsController() {
return defaultOptionsController;
}
public OptionsModel getDefaultOptionsModel() {
return defaultOptionsModel;
}
public OptionsDialog getDefaultOptionsDialog() {
return defaultOptionsDialog;
}
public SettingsDialog getSettingsDialog() {
return settingsDialog;
}
public MVCRequestFactory getMVCRequestFactory() {
return mvcRequestFactory;
}
}
|
n = int(raw_input())
string = list(raw_input().lower())
check = len(list(set(string)))
if check < 26:
print "NO"
else:
print "YES"
|
blade55555 Profile Blog Joined March 2009 United States 17354 Posts Last Edited: 2012-08-21 07:22:45 #1 and the timings I use are probably very similar).
This guide will have plenty of replays (5 to start out with more being added within the week) and will show many different scenarios, roach/ling/bane aggression, roach pressure, 2 base roach attacks, etc. So there will be many scenarios that you can see how I defend vs certain builds!
For those curious on my other guides you can locate them here:
+ Show Spoiler +
Zerg vs Zerg Muta play:
Zerg vs Terran guide:
Zerg vs Protoss guide:
Zerg vs Protoss Delayed Lair guide:
Zerg vs Protoss Tier 2 aggression:
Zerg vs protoss Banelings: Zerg vs Zerg hatch first vs 14/14: http://www.teamliquid.net/forum/viewmessage.php?topic_id=199583 Zerg vs Zerg Muta play: http://www.teamliquid.net/forum/viewmessage.php?topic_id=282954 Zerg vs Terran guide: http://www.teamliquid.net/forum/viewmessage.php?topic_id=211960 Zerg vs Protoss guide: http://www.teamliquid.net/forum/viewmessage.php?topic_id=210354 Zerg vs Protoss Delayed Lair guide: http://www.teamliquid.net/forum/viewmessage.php?topic_id=259629 Zerg vs Protoss Tier 2 aggression: http://www.teamliquid.net/forum/viewmessage.php?topic_id=318129 Zerg vs protoss Banelings: http://www.teamliquid.net/forum/viewmessage.php?topic_id=338403
Hello guys and yes I am writing another guide! Now that I have so much free time I have been able to play a bit more with styles that I don't use or new styles and this one is a new style that I imagine is getting pretty popular but I could be wrong. This is ling/infestor double upgrades into ultra the build stephano has been using and yes this build is that except my own timings (I don't know stephano's timingsand the timings I use are probably very similar).This guide will have plenty of replays (5 to start out with more being added within the week) and will show many different scenarios, roach/ling/bane aggression, roach pressure, 2 base roach attacks, etc. So there will be many scenarios that you can see how I defend vs certain builds!For those curious on my other guides you can locate them here: --------Introduction--------
Ok so I am going to explain the concept of the build and your overall game plan. The basic way to explain is it go mass ling with upgrades into infestors into hive into ultralisks. Simple way to explain it. I saw stephano do this style and have been messing around with it for about 2 weeks I think? Maybe a week in a half but I have literally only done this style so that I can perfect it and add it to my zvz arsenal of builds. I have found this build insanely strong and have been having fun doing this.
I can't remember what zerg stephano did this to in a tournament, but I heard about it and watched him stream and do the build and I found I liked it. It's a zvt concept in zvz. That is when I decided I was going to start learning it and I am very confident in my ability to do this build now.
The replays will showcase zvz at high masters on both na/kr server. Now this build doesn't matter if you 14/14 or hatch first so I am not really going to go into huge detail on going either.
So now to the build order!
Ok so I am going to explain the concept of the build and your overall game plan. The basic way to explain is it go mass ling with upgrades into infestors into hive into ultralisks. Simple way to explain it. I saw stephano do this style and have been messing around with it for about 2 weeks I think? Maybe a week in a half but I have literally only done this style so that I can perfect it and add it to my zvz arsenal of builds. I have found this build insanely strong and have been having fun doing this.I can't remember what zerg stephano did this to in a tournament, but I heard about it and watched him stream and do the build and I found I liked it. It's a zvt concept in zvz. That is when I decided I was going to start learning it and I am very confident in my ability to do this build now.The replays will showcase zvz at high masters on both na/kr server. Now this build doesn't matter if you 14/14 or hatch first so I am not really going to go into huge detail on going either.So now to the build order! --------Build order--------
9 - overlord
9 - drone scout (I only do this on 2 player maps to block their hatch if they go hatch first and go hatch first myself)
15 - hatchery
14-16 - gas/spawning pool (if other player hatch firsts 16 gas then pool, if 14/14 15 pool 15 gas)
16 or 17 (your preference) - overlord
1st 100 gas - metabolic boost (speedling upgrade)
5:00 - 5:25 - baneling nest(defensive purpose)
5:30 - 6:00 - spine (I would recommend a spine but don't have to)
6:45 - 7:00 - 2 evo chambers
7:10 - add 2nd and third gas
start lair after starting +1 melee/carapace with next 100 gas. No time on this because any sorts of aggression can happen in zvz
after lair starts - fourth gas (or right before)
infestation pit and get 2/2 as soon as lair finishes
add spines to third/natural as needed (more in explanation section)
4 or so infestors then hive
hive finishes - start 3/3, ultra cavern
--------explanation and anaylsis--------
+ Show Spoiler +
The drone scout is just what I like to do, you do not have to do this and won't change the game other then playing blind (which I hate).
Now again the hatch first 14/14 is up to you, this doesn't change the timings to much on what you need. I didn't add 2 queens when hatcheries finish because that is common knowledge I hope now of days .
So the spawning pool is very dependant or you do it blindly. Not much needed to explain this as I said it in there. The baneling nest is defensive, although you can be aggressive if you choose to be. I get this to defend vs possible ling/bane all ins or any sort of mass ling play.
The spine is good because you need defenses vs roach anyway and it helps vs ling/bane all ins, most zergs get 1 spine so this isn't anything new.
Now the 2 evo chambers I have found that 6:45-7 minutes is a good timing. You will probably see replays where I get it earlier, but I believe this is the best timing from doing this build many, many times.
I have found getting the 2nd and third gas later is better as you should have a stockpiled gas off of the 1 gas unelss you have been making a ton of banelings. Now if you have been doing mass ling/bane because that's what you had to do to defend then I would get a 2nd gas so you can start 1/1 once you stabalize or whatever.
Now the third base timing can be up to you completely and can be situational as well. I would try to get it before starting lair. You can just stay on 2 base as it does make it easier to hold off all ins, but I would try to get that third before lair so that you can get spines there as spines are very crucial with this build. You will die if you don't get spines to mass roach play as mass roach/ling attacks will hit before infestors.
Now you should get your 5th and 6th gases once you drone up a little bit, once your third is getting drones is when I would start getting those gases. Your hive should start fairly quickly, literally after you start 2/2 and get some infestors your hive should be going.
Upgrades are very crucial with this build so you should make sure to start 3/3 and ultra armor upgrade before ultra production. Upgrades are very strong, especially since the player going roach/infestor, roach/hydra, etc won't be going fast lair and won't have 3/3 anywhere near as fast as you do.
Now if your opponent is doing the same build as you, you don't need as many spines. You should only make a couple at natural/third/etc as you don't need to many since youb otha re getting the same unit composition. Now to explain it in a little more detail. That's the basic build order but now to explain this in more detail.The drone scout is just what I like to do, you do not have to do this and won't change the game other then playing blind (which I hate).Now again the hatch first 14/14 is up to you, this doesn't change the timings to much on what you need. I didn't add 2 queens when hatcheries finish because that is common knowledge I hope now of daysSo the spawning pool is very dependant or you do it blindly. Not much needed to explain this as I said it in there. The baneling nest is defensive, although you can be aggressive if you choose to be. I get this to defend vs possible ling/bane all ins or any sort of mass ling play.The spine is good because you need defenses vs roach anyway and it helps vs ling/bane all ins, most zergs get 1 spine so this isn't anything new.Now the 2 evo chambers I have found that 6:45-7 minutes is a good timing. You will probably see replays where I get it earlier, but I believe this is the best timing from doing this build many, many times.I have found getting the 2nd and third gas later is better as you should have a stockpiled gas off of the 1 gas unelss you have been making a ton of banelings. Now if you have been doing mass ling/bane because that's what you had to do to defend then I would get a 2nd gas so you can start 1/1 once you stabalize or whatever.Now the third base timing can be up to you completely and can be situational as well. I would try to get it before starting lair. You can just stay on 2 base as it does make it easier to hold off all ins, but I would try to get that third before lair so that you can get spines there as spines are very crucial with this build. You will die if you don't get spines to mass roach play as mass roach/ling attacks will hit before infestors.Now you should get your 5th and 6th gases once you drone up a little bit, once your third is getting drones is when I would start getting those gases. Your hive should start fairly quickly, literally after you start 2/2 and get some infestors your hive should be going.Upgrades are very crucial with this build so you should make sure to start 3/3 and ultra armor upgrade before ultra production. Upgrades are very strong, especially since the player going roach/infestor, roach/hydra, etc won't be going fast lair and won't have 3/3 anywhere near as fast as you do.Now if your opponent is doing the same build as you, you don't need as many spines. You should only make a couple at natural/third/etc as you don't need to many since youb otha re getting the same unit composition.
--------Holding off roach aggression--------
+ Show Spoiler +
What I would recommend is having 3-5 spines at third + natural. This is a good amount and with mass ling/infestor you should be able to hold unless you are very behind or something then you shouldn't do this.
You should be doing counter attacks with some lings as well when he attacks. There will be times when you can't defend your third, so make sure you can kill his. Remember lings are incredibly fast, you can kill his third and with spine + infestor support keep your natural safe to. Losing your third if you supply block, forget to make spines, etc you can lose the third to early roach/ling aggression. This is not the end of the world, but it is avoidable. There will be a few replays showcasing me losing my third . Now when you do this build and your opponent realizes it there is a good chance he will do a timing with roach/ling. Again you need spine crawlers. You should also try to engage in a good spot with your lings. You want to go for a surround, if you can't surround him and are only hitting 5-6 of his roaches with your mass ling you are going to lose, pull back and wait for a opening. Do not engage stupidly, this is very crucial. Another way you can do this is go roach/ling yourself but I don't really recommend this as that will take a lot of gas and hurt your upgrade timing or ultra/infestor count.What I would recommend is having 3-5 spines at third + natural. This is a good amount and with mass ling/infestor you should be able to hold unless you are very behind or something then you shouldn't do this.You should be doing counter attacks with some lings as well when he attacks. There will be times when you can't defend your third, so make sure you can kill his. Remember lings are incredibly fast, you can kill his third and with spine + infestor support keep your natural safe to. Losing your third if you supply block, forget to make spines, etc you can lose the third to early roach/ling aggression. This is not the end of the world, but it is avoidable. There will be a few replays showcasing me losing my third
--------Holding off Mutalisks--------
+ Show Spoiler + Now ling/infestor is actually a good counter to mutalisks. You should put 1-2 spores at all bases and make sure to get infestors, you will want more then 4 and you will most likely be delaying your hive by about a minute which is fine. You should either have a third before his mutalisks pop, if not you will have to wait until infestors. Try to sneak some lings to deny/kill his third if possible as you should have a decent amount of lings.
There is not much else to really say about this sort of aggression.
--------Holding off roach/speed bane attacks--------
+ Show Spoiler +
So there is a replay down below if you want an example of beating the roach/speedbane especially before infestors pop. The best way to beat this style is to have at least 2-3 spines and some banelings of your own.
The reason you want banelings of your own is so that the banelings that get past can be taken down with your banelings (and you will have upgrades for them and he won't). Do not get speed bane, slow banes will do just fine. When you see his banelings coming up pre-infestor timing make sure you have some banelings to intercept. This is the real threat is the first pre-infestor timing roach/speed bane attack. If you hold it, you should be just fine because infestors should be out any second.
You have to be very careful vs speed bane play as you do not want to lose all your lings to them, this is very critical and you will want to baby sit your lings a little bit and split them so that if speed banes are going to hit them they won't kill them all. Since you will have upgrades your lings should be able to take a hit without dying (not recommended still). But this makes it not as bad if only one hits compared to 2 and they all die.
This is probably going to be people's biggest problem is beating this after they figure out the infestor timing, if you can remember to make banelings of your own and spines you should be just fine. don't forget to watch your mineral line to!
--------The Advantages--------
+ Show Spoiler + Good upgrades, overall ling/infestor is strong vs almost any composition
Has a great transition into late game with upgrades intact which if you can get to hive and to ultras and he isn't doing the same build you are going to be in a great position.
Very defensive style, you counter attack with some lings, but overall defensive. For players who like a strong build that can get them into late game this is a good style for them.
Ultralisks are incredibly strong with 5/3 upgrades vs all ground army especially with infestor support.
--------The Disadvantages--------
+ Show Spoiler +
Your opponent will have map control over you if he is going roach play or mutalisk play. This is fine but is a disadvantage.
Your opponent should be able to secure a fourth a little faster then you with roach play. This gives him a slight eco advantage, but you won't be to far behind him as you will be getting utralisks with good upgrades, but a disadvantage non the less.
Defensive style. This is both disadvantage and advantage because some people don't like defensive, even if it's for 15 minutes of the game. You don't want to be to aggressive and you really can't vs roach/infestor until ultralisks are out.
If there are more I'll be sure to note it.
--------FAQ--------
+ Show Spoiler +
I played vs roach/speedbane and it hit before infestors and I died. How can I defend this?
To defend vs a roach/speedbane, you should have at least 3 spines at this point which will help a lot vs this, but you also will want some banelings on your own. Not speed banelings obviously, but you will want a few of your own to connect with his to kill them before they can touch your lings. This timing is really only worrisome before infestors come out, once infestors pop you should be fine.
--------Replays--------
These replays will be both from the NA and korean server. Both will be high masters from the server, so this isn't me vs low or bad players, this will showcase it vs high masters players. This will showcase some muta play, roach, etc. I will be adding more within the week!
http://www.mediafire.com/?qtsybe1q3wzk1bg
(both of these games showcase early heavy ling/bane pressure but I still continue doing the build while dealing with it)
(this game showcases this style vs mutalisks)
(2 replays show casing roach/ling/infestor into ultralisks an easier way to execute this build)
These replays will be both from the NA and korean server. Both will be high masters from the server, so this isn't me vs low or bad players, this will showcase it vs high masters players. This will showcase some muta play, roach, etc. I will be adding more within the week! http://www.mediafire.com/?aipawnb51ko2p15 (both of these games showcase early heavy ling/bane pressure but I still continue doing the build while dealing with it) http://www.mediafire.com/?hph80ghbgo48f8i (this game showcases this style vs mutalisks) http://www.mediafire.com/?vf666vq4aw4l5n4 (2 replays show casing roach/ling/infestor into ultralisks an easier way to execute this build) --------Commentated ling/infestor into ultra vs roach/speedbane--------
+ Show Spoiler +
+ Show Spoiler +
+ Show Spoiler + When I think of something else, something will go here
ArcticRaven Profile Joined August 2011 France 1238 Posts #2 Thank you so much for this, i was just typing a thread asking for this when i saw it :D
I have a question though, probably because of my horrible understanding of zvz : why not drop a spire with the hive and directly go to broodlords ? Aren't they better than ultras, and also faster to get thanks to morphing already existing units ? [Govie] Wierd shit, on a 6 game AP winning streak with KOTL in the trench. I searched gandalf quotes and spammed them all game long, trenchwarfare247, whateva it takes!
Aocowns Profile Blog Joined February 2011 Norway 5988 Posts Last Edited: 2012-06-14 21:05:25 #3 bookmarked, definetly interested in trying this out. Great guide, as always I'm a salt-lord and hater of mech and ForGG, don't take me seriously, it's just my salt-humour speaking i swear. |KadaverBB best TL gaoler| |~IdrA's #1 fan~| SetGuitarsToKill and Duckk are my martyr heroes |
blade55555 Profile Blog Joined March 2009 United States 17354 Posts #4 On June 15 2012 05:57 ArcticRaven wrote:
Thank you so much for this, i was just typing a thread asking for this when i saw it :D
I have a question though, probably because of my horrible understanding of zvz : why not drop a spire with the hive and directly go to broodlords ? Aren't they better than ultras, and also faster to get thanks to morphing already existing units ?
Hmm broodlords are a slow unit and while they are better in fights due to only hydra/infested terrans able to hit them the other zerg can go for a base trade style. Also you spend more gas as you have to get the spire 200/200, start greater spire 150/150 (I think), then you have to get corruptors 100/150 and then morph them which is 150/150? (can't remember bl cost).
If going ultra's you just get armor upgrade 200/200, then start making ultras. That is why I find it superior to broodlords and again base trade styles and all that. Hmm broodlords are a slow unit and while they are better in fights due to only hydra/infested terrans able to hit them the other zerg can go for a base trade style. Also you spend more gas as you have to get the spire 200/200, start greater spire 150/150 (I think), then you have to get corruptors 100/150 and then morph them which is 150/150? (can't remember bl cost).If going ultra's you just get armor upgrade 200/200, then start making ultras. That is why I find it superior to broodlords and again base trade styles and all that. When I think of something else, something will go here
ArcticRaven Profile Joined August 2011 France 1238 Posts #5
Spire + Greater Spire => 350/350
In the end the infrastructure costs the same so there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.
But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things. Ultra cavern + armor upgrade => 450/350Spire + Greater Spire => 350/350In the end the infrastructure costs the sameso there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things. [Govie] Wierd shit, on a 6 game AP winning streak with KOTL in the trench. I searched gandalf quotes and spammed them all game long, trenchwarfare247, whateva it takes!
Thraundil Profile Joined August 2010 Denmark 278 Posts #6
And @ the brood lord tech option from the opponent; imo this is a giveaway. If he stays on roach only or roach with few infestors, you KNOW he is getting T3 (or some dodgy muta play). You know it aint ultras cos their synergy with roaches is terrible. If he makes many many infestors, or adds many hydras too, he wont be able to afford broods. But if you spot the giveaway of few gas intense units, simply pop down a spire and stay active on the map? Its not a huge investment, and if you see broods while attacking his base, you pull back, queue 10 corrupters and laugh as you spread out to avoid fungals, and whack his super expensive broods while they do no damage.
One question on the actual build though. How does this handle a very defensive roach/infestor mass eco player? If you wanna be agressive before ultralisks it costs a lot of larvae and he will probably be ahead in economy. If he can afford to make half and half roach/hydra with just some 4-5 early infestors to lock down many zerglings with fungal... With better econ surely this will give you a hard time - assuming he opts for turtle rather than timing attack when/if he sees what you are doing. Very interesting style. I've been tired of SCII as of late, trolling around in the very low end of master league doing weird builds that sometimes work only because the opponent must be going "the HELL???". This could be what gets me back in the gameAnd @ the brood lord tech option from the opponent; imo this is a giveaway. If he stays on roach only or roach with few infestors, you KNOW he is getting T3 (or some dodgy muta play). You know it aint ultras cos their synergy with roaches is terrible. If he makes many many infestors, or adds many hydras too, he wont be able to afford broods. But if you spot the giveaway of few gas intense units, simply pop down a spire and stay active on the map? Its not a huge investment, and if you see broods while attacking his base, you pull back, queue 10 corrupters and laugh as you spread out to avoid fungals, and whack his super expensive broods while they do no damage.One question on the actual build though. How does this handle a very defensive roach/infestor mass eco player? If you wanna be agressive before ultralisks it costs a lot of larvae and he will probably be ahead in economy. If he can afford to make half and half roach/hydra with just some 4-5 early infestors to lock down many zerglings with fungal... With better econ surely this will give you a hard time - assuming he opts for turtle rather than timing attack when/if he sees what you are doing. Hivemind! Just like IRL...
Aocowns Profile Blog Joined February 2011 Norway 5988 Posts #7 Was this what Idra tried doing against Monster in the recent clan war? Monster did some weird speed bane runbyes, and Idra lost pretty badly. A one off, or is speed bane something that can work against this unless you are prepared for it? I'm a salt-lord and hater of mech and ForGG, don't take me seriously, it's just my salt-humour speaking i swear. |KadaverBB best TL gaoler| |~IdrA's #1 fan~| SetGuitarsToKill and Duckk are my martyr heroes |
Chaosvuistje Profile Joined April 2010 Netherlands 2560 Posts #8
Thanks for writing and testing Interesting. I will still stick to my spire style, but I will read up on this to maybe get a new techswitch option should I scout something from my opponent.Thanks for writing and testing Follow me on @raamedia, updates on good TL threads and SC2 news. And also webdevelopment ^^
galtdunn Profile Joined March 2011 United States 799 Posts #9 I have been being beaten by this build all day so I'm adopting it! First game was an easy win against a similar ling/infestor style. Thanks for the write up! I've bookmarked it. Currently editing items in the DotA 2 wiki. PM for questions/suggestions.
galtdunn Profile Joined March 2011 United States 799 Posts #10 On June 15 2012 06:54 Aocowns wrote:
Was this what Idra tried doing against Monster in the recent clan war? Monster did some weird speed bane runbyes, and Idra lost pretty badly. A one off, or is speed bane something that can work against this unless you are prepared for it?
I saw that game, that was a very strange style and one i don't think idra was prepared for.
You have to have really good control and reaction speed to hold that off with this style I expect. Maybe use small groups of lings to attack the banes while running your drones away? Or maybe just counterattack, because the banes+research for speed banes might put him behind in actual army. I saw that game, that was a very strange style and one i don't think idra was prepared for.You have to have really good control and reaction speed to hold that off with this style I expect. Maybe use small groups of lings to attack the banes while running your drones away? Or maybe just counterattack, because the banes+research for speed banes might put him behind in actual army. Currently editing items in the DotA 2 wiki. PM for questions/suggestions.
Icarox Profile Joined January 2011 Sweden 78 Posts #11 I faced this build on the ladder the other day, it really confused me, locked down my roach-timing and then just humiliated me with the ultras. I was puzzled to say the least.
But it really feels like a far too turtlish build, it will be interesting when this strategy has been tested more.
blade55555 Profile Blog Joined March 2009 United States 17354 Posts #12 On June 15 2012 06:54 Aocowns wrote:
Was this what Idra tried doing against Monster in the recent clan war? Monster did some weird speed bane runbyes, and Idra lost pretty badly. A one off, or is speed bane something that can work against this unless you are prepared for it?
Don't know but one of the replays I uploaded show cases a guy going roach/speed bane and tries to kill me (this was played today to).
On June 15 2012 06:30 ArcticRaven wrote:
Ultra cavern + armor upgrade => 450/350
Spire + Greater Spire => 350/350
In the end the infrastructure costs the same so there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.
But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things. Ultra cavern + armor upgrade => 450/350Spire + Greater Spire => 350/350In the end the infrastructure costs the sameso there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things.
Don't forget - corruptors - broodlords. You have to make the corruptors and then morph them so it costs more gas .
But I mean it really is super easy to counter broodlords which is why ultras are better ^^.
On June 15 2012 06:31 Thraundil wrote:
Very interesting style. I've been tired of SCII as of late, trolling around in the very low end of master league doing weird builds that sometimes work only because the opponent must be going "the HELL???". This could be what gets me back in the game
And @ the brood lord tech option from the opponent; imo this is a giveaway. If he stays on roach only or roach with few infestors, you KNOW he is getting T3 (or some dodgy muta play). You know it aint ultras cos their synergy with roaches is terrible. If he makes many many infestors, or adds many hydras too, he wont be able to afford broods. But if you spot the giveaway of few gas intense units, simply pop down a spire and stay active on the map? Its not a huge investment, and if you see broods while attacking his base, you pull back, queue 10 corrupters and laugh as you spread out to avoid fungals, and whack his super expensive broods while they do no damage.
One question on the actual build though. How does this handle a very defensive roach/infestor mass eco player? If you wanna be agressive before ultralisks it costs a lot of larvae and he will probably be ahead in economy. If he can afford to make half and half roach/hydra with just some 4-5 early infestors to lock down many zerglings with fungal... With better econ surely this will give you a hard time - assuming he opts for turtle rather than timing attack when/if he sees what you are doing. Very interesting style. I've been tired of SCII as of late, trolling around in the very low end of master league doing weird builds that sometimes work only because the opponent must be going "the HELL???". This could be what gets me back in the gameAnd @ the brood lord tech option from the opponent; imo this is a giveaway. If he stays on roach only or roach with few infestors, you KNOW he is getting T3 (or some dodgy muta play). You know it aint ultras cos their synergy with roaches is terrible. If he makes many many infestors, or adds many hydras too, he wont be able to afford broods. But if you spot the giveaway of few gas intense units, simply pop down a spire and stay active on the map? Its not a huge investment, and if you see broods while attacking his base, you pull back, queue 10 corrupters and laugh as you spread out to avoid fungals, and whack his super expensive broods while they do no damage.One question on the actual build though. How does this handle a very defensive roach/infestor mass eco player? If you wanna be agressive before ultralisks it costs a lot of larvae and he will probably be ahead in economy. If he can afford to make half and half roach/hydra with just some 4-5 early infestors to lock down many zerglings with fungal... With better econ surely this will give you a hard time - assuming he opts for turtle rather than timing attack when/if he sees what you are doing.
With this build you aren't trying to be aggressive until ultralisks are out. You want to do ling runby's and stuff but no all out aggression as it won't work unless he is out of position or something. Don't know but one of the replays I uploaded show cases a guy going roach/speed bane and tries to kill me (this was played today to).Don't forget - corruptors - broodlords. You have to make the corruptors and then morph them so it costs more gasBut I mean it really is super easy to counter broodlords which is why ultras are better ^^.With this build you aren't trying to be aggressive until ultralisks are out. You want to do ling runby's and stuff but no all out aggression as it won't work unless he is out of position or something. When I think of something else, something will go here
Sapp Profile Joined March 2011 Poland 173 Posts #13 On June 15 2012 06:30 ArcticRaven wrote:
Ultra cavern + armor upgrade => 450/350
Spire + Greater Spire => 350/350
In the end the infrastructure costs the same so there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.
But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things. Ultra cavern + armor upgrade => 450/350Spire + Greater Spire => 350/350In the end the infrastructure costs the sameso there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things.
In ZvT zergs stoped useing broods because marines can outrun you on the map ---> Zerg units are faster than terran bio, equals Broodlords are bad ZvZ. just like that. better stay roach/hydra/infestor In ZvT zergs stoped useing broods because marines can outrun you on the map ---> Zerg units are faster than terran bio, equals Broodlords are bad ZvZ. just like that. better stay roach/hydra/infestor Quote? O.o?
blade55555 Profile Blog Joined March 2009 United States 17354 Posts #14 On June 15 2012 08:11 Sapp wrote:
Show nested quote +
On June 15 2012 06:30 ArcticRaven wrote:
Ultra cavern + armor upgrade => 450/350
Spire + Greater Spire => 350/350
In the end the infrastructure costs the same so there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.
But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things. Ultra cavern + armor upgrade => 450/350Spire + Greater Spire => 350/350In the end the infrastructure costs the sameso there's only the basetrade problem ? If so i think that going broodlords first to repel anything he might throw at you then switching to ultras as he gets his spire up might be more effective - especially since a heavily upgraded ling army with plenty of spare minerals to keep building proxy hatches & extractors should have the edge i feel.But then this is only theorycraft - i'll try to do it your way as well as possible before trying to change things.
In ZvT zergs stoped useing broods because marines can outrun you on the map ---> Zerg units are faster than terran bio, equals Broodlords are bad ZvZ. just like that. better stay roach/hydra/infestor In ZvT zergs stoped useing broods because marines can outrun you on the map ---> Zerg units are faster than terran bio, equals Broodlords are bad ZvZ. just like that. better stay roach/hydra/infestor
I wouldn't say broodlords are bad zvt at all, they are still incredibly strong. I just think going ultras first then going into bl's is stronger though now of days. I wouldn't say broodlords are bad zvt at all, they are still incredibly strong. I just think going ultras first then going into bl's is stronger though now of days. When I think of something else, something will go here
theBIGdog Profile Joined February 2011 United States 41 Posts #15
great write up nooooo! now everyone is gonna be doing thisgreat write up ULTRASTOMP
StarBrift Profile Joined January 2008 Sweden 1720 Posts Last Edited: 2012-06-14 23:50:50 #16 I worked out almost an identical build to this today too based on the style I saw at MLG. I gotta say that you really feel the strenght of this build once you get a hang of it. After infestors are out there is nothing that can bust you if you have a spine wall unless you fell behind early. Also any time you see him going for one of your bases you can pretty much get a guarranteed snipe on one of his bases unless he has them littered with banes. You can really force a roach player to stay defensive with just continuous counters and runbys.
Excellent potential in this build imo. As an example I ran by with 12 lings when he was going for my third with all his units. Those 12 lings killed all his 3 queens since they were 2-2 and he only had 1 armor. Then I got some drones and an evo. This happens all the time. It forces the roach player to realise that his attack will be an all in.
The only problem I faced was roach/bane all ins before infestors pop. You need a lot of spread spines to defend this but you also need the spines somewhat close together to kill the roaches as they are going to be your main source of dps while the lings soak damage. The problem comes when the banes get close to your spines. They will blow up your spines if you let them get too close. But if you try and run after them with banes of your own then he will back off and snipe them with roaches. A neat trick I found that is really hard but worked sometimes for me is that you manually detonate your own banes to catch his banes right outside of spines range. This is tricky but if you succeed you will have used the range of bane explosion to save the lives of your spines and you'll win the battle.
Belial88 Profile Blog Joined November 2010 United States 5217 Posts Last Edited: 2012-06-15 00:48:07 #17 On June 15 2012 05:57 ArcticRaven wrote:
Thank you so much for this, i was just typing a thread asking for this when i saw it :D
I have a question though, probably because of my horrible understanding of zvz : why not drop a spire with the hive and directly go to broodlords ? Aren't they better than ultras, and also faster to get thanks to morphing already existing units ?
Broodlords take longer and cost more, there is no way you can get broodlords off of only 3 bases. However, you can get ultras, as long as you didn't make roaches or hydras. If you do this style, of getting 3 base ultra, vs someone going broodlords, you just snipe all his bases, broodlords are too slow and don't kill ultras fast enough. If he's doing something like roach/hydra/bl, then you just add a few corruptors into your army. It's literally just a superior unit composition of ling/ultra/infestor. it's the zvz deathball, just turtle on 3 base, get ultras, gg.
i really don't think anything can beat this, and that this will be the new standard in zvz. 2 base lair infestor blind counters 2 base muta, and before no one did that because it was assumed your third being so late, you would be screwed with your roach/hydra transition, but seeing as you never go to roach/hydra, it doesn't matter...
I think this build is a ton of fun, I've even won a game where I hadn't even gotten infestors, and I had totally droned up my 2 bases, I wasn't aggressive or anything, and I was playing someone who went standard fast third before lair roach on condemned ridge (where the 3 bases were far apart), and I literally just focused down all 3 of his bases at the exact same time just with the amount of lings I made off 2 base 3 hatch, and then my infestors popped when he did his desperate roach all-in with his bases being revealed lol.
It's also pretty... lame, imo. I really think it's kind of lame that it doesn't matter how good or bad the early or mid-game goes, you just turtle on 2 bases with ling/infestor, and eventually take your third with mass spines, infestors, and lings and get hive and ultras, and any sort of roach based play will get owned because broodlords suck against this (and you can't get nearly enough out in time against this fast hive style), and mass roach gets owned by ling/infestor/spine. The upgrades are incredible too, just putting 5 banelings on your ramp doesnt work if 1 baneling doesnt kill a ling anymore. You can focus down people's bases so quickly with this style.
It's literally just turtle on 2 base with spine/infestor so no sort of aggression can hurt you, then you move up your spines to protect you taking a third. Eventually, 6+ infestors with mass spines will secure a third, and then you get ultras and it's gg.
I've started doing this after being extremely frustrated by playing against this style, I found nothing worked and the advice everyone gives of "just roach bust" or "just nydus" or "just drop" solely relies on the ling/infestor player simply being bad or not making enough spines. Now that I've started doing this, I haven't lost a single game yet (out of about 8 games played).
Here's some reps where I did it, and badly.
(i eventually transitioned into broodlords, to bust his mass spine wall, so I had a pure bl/ultra/infestor crazy army. but once I had ultras out, I denied the opponent's 5th base, and even killed his 4th. it was only as close as it was because he got a clutch double fg and killed like 12 of my infestors all at once. he was a better player than me for sure though)
(didnt make enough spines. epic base trade where my ultra/ling army was just way more mobile than roach/hydra. i screwed up by not making enough spines and losing too many infestors though, and not enough ultras because i had to remake infestors)
(vs mutas, he had a lead but this style is just so epic i dont give a fuck how far ahead you are, bitch i get 3 bases and then its ultras gg)
(focused 3 hatches down) Broodlords take longer and cost more, there is no way you can get broodlords off of only 3 bases. However, you can get ultras, as long as you didn't make roaches or hydras. If you do this style, of getting 3 base ultra, vs someone going broodlords, you just snipe all his bases, broodlords are too slow and don't kill ultras fast enough. If he's doing something like roach/hydra/bl, then you just add a few corruptors into your army. It's literally just a superior unit composition of ling/ultra/infestor. it's the zvz deathball, just turtle on 3 base, get ultras, gg.i really don't think anything can beat this, and that this will be the new standard in zvz. 2 base lair infestor blind counters 2 base muta, and before no one did that because it was assumed your third being so late, you would be screwed with your roach/hydra transition, but seeing as you never go to roach/hydra, it doesn't matter...I think this build is a ton of fun, I've even won a game where I hadn't even gotten infestors, and I had totally droned up my 2 bases, I wasn't aggressive or anything, and I was playing someone who went standard fast third before lair roach on condemned ridge (where the 3 bases were far apart), and I literally just focused down all 3 of his bases at the exact same time just with the amount of lings I made off 2 base 3 hatch, and then my infestors popped when he did his desperate roach all-in with his bases being revealed lol.It's also pretty... lame, imo. I really think it's kind of lame that it doesn't matter how good or bad the early or mid-game goes, you just turtle on 2 bases with ling/infestor, and eventually take your third with mass spines, infestors, and lings and get hive and ultras, and any sort of roach based play will get owned because broodlords suck against this (and you can't get nearly enough out in time against this fast hive style), and mass roach gets owned by ling/infestor/spine. The upgrades are incredible too, just putting 5 banelings on your ramp doesnt work if 1 baneling doesnt kill a ling anymore. You can focus down people's bases so quickly with this style.It's literally just turtle on 2 base with spine/infestor so no sort of aggression can hurt you, then you move up your spines to protect you taking a third. Eventually, 6+ infestors with mass spines will secure a third, and then you get ultras and it's gg.I've started doing this after being extremely frustrated by playing against this style, I found nothing worked and the advice everyone gives of "just roach bust" or "just nydus" or "just drop" solely relies on the ling/infestor player simply being bad or not making enough spines. Now that I've started doing this, I haven't lost a single game yet (out of about 8 games played).Here's some reps where I did it, and badly. http://drop.sc/197897 (i eventually transitioned into broodlords, to bust his mass spine wall, so I had a pure bl/ultra/infestor crazy army. but once I had ultras out, I denied the opponent's 5th base, and even killed his 4th. it was only as close as it was because he got a clutch double fg and killed like 12 of my infestors all at once. he was a better player than me for sure though) http://drop.sc/197898 (didnt make enough spines. epic base trade where my ultra/ling army was just way more mobile than roach/hydra. i screwed up by not making enough spines and losing too many infestors though, and not enough ultras because i had to remake infestors) http://drop.sc/197899 (vs mutas, he had a lead but this style is just so epic i dont give a fuck how far ahead you are, bitch i get 3 bases and then its ultras gg) http://drop.sc/197900 (focused 3 hatches down) How to build a $500 i7-3770K Ultimate Computer:http://www.teamliquid.net/blogs/viewblog.php?topic_id=392709 ******** 100% Safe Razorless Delid Method! http://www.overclock.net/t/1376206/how-to-delid-your-ivy-bridge-cpu-with-out-a-razor-blade/0_100
Belial88 Profile Blog Joined November 2010 United States 5217 Posts Last Edited: 2012-06-15 01:01:30 #18 In ZvT zergs stoped useing broods because marines can outrun you on the map ---> Zerg units are faster than terran bio, equals Broodlords are bad ZvZ. just like that. better stay roach/hydra/infestor
That's not true, broodlord/corruptor/infestor/queen is still the dream composition in ZvT, and if you stay on lair tech a long time (like the classic ling/bane/muta style) it's still a better idea to skip ultras.
, ultras are better seen as a sort of tier 2.5 unit - you make them when teching to broodlords would get you killed because they take so long (ultras are cheaper and come about a minute quicker than broodlords, and are good as support units in small numbers with a large t2 army whereas just 1-3 broodlords is not really helpful at all), but staying on lair tech against the ~160 terran push is uncomfortable.
As blade5555 said, ultras are really good to cover that vulnerable timing against terrans who take a quick third (going ultras is not that great against terrans who stay on 2 base longer though, like they did a few months to a year ago) so you can transition into broodlords. it's a really nice way to play if you prefer a quick hive, ultras, macro passive play, against fast third terrans, instead of an aggressive late hive, longer lair stage play. eg, the 8-12 mutas double ups into quick hive or recent infestor play, as opposed to the classic ling/bane/muta, leenock/line/suhosin style ling/muta double ups, double spire style, etc.
Broodlords are amazing in standard/classic ZvZ, you just have to know how to use them (most people don't). Standard ZvZ right now is fast third, roach/hydra, max out and aggression into roach/hydra/infestor (anyone who goes straight to infestors dies, if not goes roach/hydra/infestor even before maxing out). Then, when both players are maxed on roach/hydra, you go towards 4 base roach/hydra/infestor, and it's a very back and forth game that usually ends with a clutch FG or bad positioning or over aggressiveness or good multi-pronged attacks, but if it doesn't, it then goes to 3/3 roach/hydra/infestor, and then if it still doesn't end, both players slowly start to incorporate a couple broodlords (just maxing on broods will die to mass corruptors, so you need the roach/hydra/infestor to support small numbers of broods that allow you to siege defensive positions). Eventually, the game turns into broodlord/infestor (keyword infestor to stop mass roach attacks), and then eventually, pure broodlord/corruptor (12+ broodlords owns any numbers of infestors, and FG is not that good against 10+ corruptors, and roaches no longer work when both players have split the map on 6+ bases with 30+ spines).
You don't see games go like this often, I dont think any GSL game has gotten to that stage, but that IS how the game is 'supposed' to go. But with this new style of play, you will lose your entire roach army to ultra/ling/infestor deathball, and you can't afford to get 10+ broodlords in near enough time. Standard play gets broodlords in a VERY slow, VERY gradual process (first it's ling/bane, then roach/ling, then mass roach, then roach/hydra, then roach/hydra max out, then roach/hydra/infestor, then 3/3, then just a very, very few number of broodlords, then roach/broodlord/infestor, then bl/infestor, then bl/corruptor/infestor, then pure bl/corruptor, and if you tech too quickly at any given time you just flat out die in whats a very, very aggressive match-up in the first place) so this sort of play just dominates it.
Anyways, nice guide. I was wondering why my upgrades were so late, so you go 1/1 then lair. nice to know, especially the gas timings. That's not true, broodlord/corruptor/infestor/queen is still the dream composition in ZvT, and if you stay on lair tech a long time (like the classic ling/bane/muta style) it's still a better idea to skip ultras. As I state in my ZvT guide , ultras are better seen as a sort of tier 2.5 unit - you make them when teching to broodlords would get you killed because they take so long (ultras are cheaper and come about a minute quicker than broodlords, and are good as support units in small numbers with a large t2 army whereas just 1-3 broodlords is not really helpful at all), but staying on lair tech against the ~160 terran push is uncomfortable.As blade5555 said, ultras are really good to cover that vulnerable timing against terrans who take a quick third (going ultras is not that great against terrans who stay on 2 base longer though, like they did a few months to a year ago) so you can transition into broodlords. it's a really nice way to play if you prefer a quick hive, ultras, macro passive play, against fast third terrans, instead of an aggressive late hive, longer lair stage play. eg, the 8-12 mutas double ups into quick hive or recent infestor play, as opposed to the classic ling/bane/muta, leenock/line/suhosin style ling/muta double ups, double spire style, etc.Broodlords are amazing in standard/classic ZvZ, you just have to know how to use them (most people don't). Standard ZvZ right now is fast third, roach/hydra, max out and aggression into roach/hydra/infestor (anyone who goes straight to infestors dies, if not goes roach/hydra/infestor even before maxing out). Then, when both players are maxed on roach/hydra, you go towards 4 base roach/hydra/infestor, and it's a very back and forth game that usually ends with a clutch FG or bad positioning or over aggressiveness or good multi-pronged attacks, but if it doesn't, it then goes to 3/3 roach/hydra/infestor, and then if it still doesn't end, both players slowly start to incorporate a couple broodlords (just maxing on broods will die to mass corruptors, so you need the roach/hydra/infestor to support small numbers of broods that allow you to siege defensive positions). Eventually, the game turns into broodlord/infestor (keyword infestor to stop mass roach attacks), and then eventually, pure broodlord/corruptor (12+ broodlords owns any numbers of infestors, and FG is not that good against 10+ corruptors, and roaches no longer work when both players have split the map on 6+ bases with 30+ spines).You don't see games go like this often, I dont think any GSL game has gotten to that stage, but that IS how the game is 'supposed' to go. But with this new style of play, you will lose your entire roach army to ultra/ling/infestor deathball, and you can't afford to get 10+ broodlords in near enough time. Standard play gets broodlords in a VERY slow, VERY gradual process (first it's ling/bane, then roach/ling, then mass roach, then roach/hydra, then roach/hydra max out, then roach/hydra/infestor, then 3/3, then just a very, very few number of broodlords, then roach/broodlord/infestor, then bl/infestor, then bl/corruptor/infestor, then pure bl/corruptor, and if you tech too quickly at any given time you just flat out die in whats a very, very aggressive match-up in the first place) so this sort of play just dominates it.Anyways, nice guide. I was wondering why my upgrades were so late, so you go 1/1 then lair. nice to know, especially the gas timings. How to build a $500 i7-3770K Ultimate Computer:http://www.teamliquid.net/blogs/viewblog.php?topic_id=392709 ******** 100% Safe Razorless Delid Method! http://www.overclock.net/t/1376206/how-to-delid-your-ivy-bridge-cpu-with-out-a-razor-blade/0_100
Indrium Profile Joined November 2010 United States 2222 Posts #19 Hmm cool. I'd been trying to replicate this on my own so this is going to be very helpful. Thanks again Blade.
gongshow41 Profile Joined May 2011 Korea (South) 49 Posts Last Edited: 2012-06-15 02:08:46 #20 NHSFreaky showed this style in both of his opening ZvZ's early on in this seasons GSTL. The two games he does this are free as they are the first games of the match, for anyone else looking for more games to watch of this style. One of the best things these games show is his ability to fungal roaches within range of spine crawlers, while the roaches are not able to fire back, so cost efficient it hurts, and softens them up enough that lings can omnom threw them at a better rate and with better cost of trade.
1 2 3 4 5 15 16 17 Next All
|
def output_story(self):
is_succeeded = True
options = self._options
filename = self._filename
pri_filter = options.pri
formattype = options.format
is_debug = options.debug
is_comment = options.comment
story_converted = story_tag_replaced(
description_connected(
story_pronoun_replaced(
story_layer_replaced(
story_filtered_by_priority(self._story, pri_filter)
))), self._words)
analyzer = Analyzer(self._mecabdictdir)
if options.outline:
is_succeeded = self.to_outline(story_converted, filename, is_debug)
if not is_succeeded:
print("ERROR: output a outline failed!!")
return is_succeeded
if options.scenario:
is_succeeded = self.to_scenario(story_converted, filename, is_comment, is_debug)
if not is_succeeded:
print("ERROR: output a scenario failed!!")
return is_succeeded
if options.description:
is_succeeded = self.to_description(story_converted, filename, formattype,
is_comment, is_debug)
if not is_succeeded:
print("ERROR: output a description failed!!")
return is_succeeded
if options.action:
pass
if options.info:
is_succeeded = self.to_detail_info(story_converted, analyzer, filename,
is_debug)
if not is_succeeded:
print("ERROR: output a detail info failed!!")
return is_succeeded
if options.analyze:
is_succeeded = self.to_analyzed_info(story_converted, analyzer, filename,
is_debug)
if not is_succeeded:
print("ERROR: output an analyzed info failed!!")
return is_succeeded
if options.layer:
is_succeeded = self.to_layer(story_converted, filename, is_debug)
if not is_succeeded:
print("ERROR: output a description failed!!")
return is_succeeded
if options.person:
pass
if options.dialogue:
is_succeeded = self.to_dialogue_info(story_converted, analyzer, filename,
is_debug)
if not is_succeeded:
print("ERROR: output a dialogue info failed!!")
return is_succeeded
if options.version:
pass
is_succeeded = self.to_total_info(story_converted, analyzer)
return is_succeeded
|
GUY Sebastian has come a long way since winning Australian Idol in 2003.
Then, he was the country's most talked-about virgin and a devout Christian. Now, Sebastian is a happily married dad and yesterday revealed his religious beliefs had also changed.
A song on Sebastian's new Armageddon album, called Get Along, highlights the fear and ignorance inherent in many faith groups.
The singer, 30,said he still believed in God, but is more informed about religion than he was in his youth.
"My views are more based on life and discovery and research than just what I'm told," he said.
"Because what I was told in regards to so many things was so wrong. I've gone from a place where I was told there was one way and only one way, to being more in a place where I don't think anyone has the right to say what they believe is more important or more significant."
Sebastian also spoke out in favour of gay marriage.
"I don't think anyone has the right to tell someone who they can and can't be in love with," he said.
"You look back at the unfair things that happen in history and this will be looked back on as one of those things.
"People will think 'Oh my gosh I can't believe the world was in that state, that they held those views'.
"It's pretty unfair for people to not be able to claim the same benefits, that's ridiculous."
Another new song, Died And Gone To Heaven, is an ode to love-making.
"It was definitely a world that opened up for me and it was great," Sebastian said. "I'm very lucky to still be in love and still have a wife I'm very attracted to. It was worth the wait."
Sebastian also revealed his No.1 hit, Battle Scars, was almost the victim of record company politics.
The track features US rapper Lupe Fiasco, whose Australian record label tried to stop the song being released. "They thought if Lupe Fiasco worked with Guy Sebastian, Triple J would never play him again," he said.
"The head of Warner in Australia rang up Atlantic, Lupe's label in the US... and said `If you do this it'll be the end of Lupe's career in Australia, he's an idiot for wanting to do this'. They actually put a block on it."
Warner Music in Australia declined to comment on Sebastian's statements.
Battle Scars has gone triple platinum in Australia and Fiasco included the song on the American version of his album. It has become Sebastian's first US Top 100 hit.
Armageddon will be released tomorrow.
Listen to more of Guy's hits here.
|
// See documentation for RollCLImpl.
func (r *TestRollCLImpl) RetryCQ(ctx context.Context) error {
r.isDryRun = false
r.normalResult = ""
r.attempt++
return nil
}
|
/**
* Simple RN native module to modify some functionality of Mapbox to better support Forest Watcher requirements
*/
public class FWMapboxPackage implements ReactPackage
{
@Override
public @NotNull List<NativeModule> createNativeModules(@NotNull ReactApplicationContext reactContext)
{
return Arrays.<NativeModule>asList(new FWMapboxModule(reactContext));
}
@Override
public @NotNull List<ViewManager> createViewManagers(@NotNull ReactApplicationContext reactContext)
{
return Collections.emptyList();
}
}
|
Study of the Mechanical Properties of a CMDB Propellant Over a Wide Range of Strain Rates Using a Group Interaction Model
Composite modified double base (CMDB) propellants are heterogeneous propellants in which properties are significantly improved by adding solid particles into the polymer matrix. A molecular group interaction model that can predict the mechanical properties of polymers through a molecular structure is used to predict the viscoelastic behavior of the CMDB propellant. Considering that the addition of solid particles will improve the crosslinking degree between polymer molecules and reduce its secondary loss peak, the input parameters of the model are modified through dynamic mechanical analysis (DMA) experimental data. By introducing the strain rate into the expression of model glass transition temperature, the mechanical properties of propellant over a wide strain range (
1.7
×
10
−
4
s-1 ~ 3000 s-1) are obtained. The reliability of the model is verified by comparison with uniaxial compression test data. By modifying the input parameters of the model, the effects of different mass ratios of nitrocellulose (NC)/nitroglycerin (NG) on the mechanical properties of the CMDB propellant were analyzed. The results show that the glass transition loss increases with increasing mass ratio of NC/NG, while Young’s modulus and yield stress decrease.
|
<gh_stars>1-10
// expose all existing models
export * from './user.model';
export * from './info-graph.model';
export * from './info-graph-category.model';
export * from './info-graph-meta.model';
export * from './node.model';
export * from './edge.model';
|
export interface IBook {
id: number
name: string
price: number
}
|
/**
* This is basic FTS configuration. It acts as PoC for how Lucene is working and shows several concepts and
* pitfalls that should be taken into account.
*
* User: denispavlov
* Date: 31/03/2017
* Time: 17:34
*/
public class FTSLuceneImplTest {
private LuceneIndexProviderImpl provider;
private GenericFTSLuceneImpl genericFTSLucene;
private MapLuceneDocumentAdapter documentAdapter;
private MapIndexBuilderLucene indexBuilderLucene;
@Before
public void setUp() throws Exception {
provider = new LuceneIndexProviderImpl("test");
provider.setUri("ram");
provider.afterPropertiesSet();
genericFTSLucene = new GenericFTSLuceneImpl();
genericFTSLucene.setLuceneIndexProvider(provider);
documentAdapter = new MapLuceneDocumentAdapter();
indexBuilderLucene = new MapIndexBuilderLucene(documentAdapter, provider);
}
private static class MapLuceneDocumentAdapter implements LuceneDocumentAdapter<Map<String, Object>, Long> {
private List<String> facets = Collections.emptyList();
private FacetsConfig facetsConfig = new FacetsConfig();
private List<String> numeric = Collections.singletonList("_PK");
@Override
public Pair<Long, Document[]> toDocument(final Map<String, Object> entity) {
final Document ldoc = new Document();
LuceneDocumentAdapterUtils.addObjectDefaultField(ldoc, entity);
Long pk = null;
for (final Map.Entry<String, Object> field : entity.entrySet()) {
final String fieldName = field.getKey();
final Object values = field.getValue();
final List<String> strValues = values instanceof String ? Collections.singletonList((String) values) : (List) values;
final boolean multi = strValues.size() > 1;
final boolean numeric = this.numeric.contains(fieldName);
for (final String strValue : strValues) {
if (AdapterUtils.FIELD_PK.equals(fieldName)) {
pk = NumberUtils.toLong(strValue);
LuceneDocumentAdapterUtils.addPkField(ldoc, Object.class, strValue);
}
if (numeric) {
LuceneDocumentAdapterUtils.addNumericField(ldoc, fieldName + "_range", NumberUtils.toLong(strValue), false);
} else {
LuceneDocumentAdapterUtils.addStemField(ldoc, fieldName, strValue);
}
if (!multi) {
if (numeric) {
LuceneDocumentAdapterUtils.addSortField(ldoc, fieldName + "_sort", NumberUtils.toLong(strValue), true);
} else {
LuceneDocumentAdapterUtils.addSortField(ldoc, fieldName + "_sort", strValue);
}
}
if (facets.contains(field.getKey())) {
if (numeric) {
LuceneDocumentAdapterUtils.addFacetField(ldoc, fieldName + "_facet", NumberUtils.toLong(strValue));
} else {
LuceneDocumentAdapterUtils.addFacetField(ldoc, fieldName + "_facet", strValue);
}
}
}
}
return new Pair<>(pk, new Document[]{ldoc});
}
public void setFacets(final List<String> facets) {
this.facets = facets;
if (!facets.isEmpty()) {
/*
Facets need to be mapped in config. The basic solution is to map them to same name.
Note that for multi value fields (i.e. when multiple fields with same name are added to
document) need to set true for #facetsConfig.setMultiValued()
*/
for (final String facet : facets) {
facetsConfig.setIndexFieldName(facet + "_facet", facet + "_facet");
facetsConfig.setMultiValued(facet + "_facet", true);
}
}
}
public void setNumeric(final List<String> numeric) {
this.numeric = numeric;
}
}
private static class MapIndexBuilderLucene extends IndexBuilderLuceneImpl<Map<String, Object>, Long> {
private List<Map<String, Object>> docs = null;
public MapIndexBuilderLucene(final LuceneDocumentAdapter<Map<String, Object>, Long> documentAdapter,
final LuceneIndexProvider indexProvider) {
super(documentAdapter, indexProvider);
}
public void setDocs(final List<Map<String, Object>> docs) {
this.docs = docs;
}
@Override
protected Map<String, Object> findById(final Long primaryKey) {
for (final Map<String, Object> doc : this.docs) {
if (doc.get(AdapterUtils.FIELD_PK).equals(String.valueOf(primaryKey))) {
return doc;
}
}
return null;
}
@Override
protected Object startTx() {
return new Object();
}
@Override
protected ResultsIterator<Map<String, Object>> findAllIterator() {
final Iterator<Map<String, Object>> it = this.docs.iterator();
return new ResultsIterator<Map<String, Object>>() {
@Override
public void remove() {
it.remove();
}
@Override
public void close() {
}
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public Map<String, Object> next() {
return it.next();
}
};
}
@Override
protected Map<String, Object> unproxyEntity(final Map<String, Object> entity) {
return entity;
}
@Override
protected void endBatch(final Object tx) {
}
@Override
protected void endTx(final Object tx) {
}
}
@After
public void tearDown() throws Exception {
provider.destroy();
}
@Test
public void testFullTextSearch() throws Exception {
indexBuilderLucene.setDocs(
(List) Arrays.asList(
new HashMap<String, String>() {{
put("_PK", "100000");
put("name", "item one");
put("desc", "some desc");
}},
new HashMap<String, String>() {{
put("_PK", "100001");
put("name", "item two");
put("desc", "other desc");
}},
new HashMap<String, String>() {{
put("_PK", "111111");
put("name", "element three");
put("desc", "other desc");
}}
)
);
indexBuilderLucene.fullTextSearchReindex(false, 2);
List<Long> pks;
Pair<List<Object[]>, Integer> rez;
// All documents
assertEquals(3, genericFTSLucene.fullTextSearchCount(new MatchAllDocsQuery()));
pks = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery());
assertNotNull(pks);
assertEquals(3, pks.size());
assertTrue(pks.contains(100000L));
assertTrue(pks.contains(100001L));
assertTrue(pks.contains(111111L));
// Simple Criteria
assertEquals(1, genericFTSLucene.fullTextSearchCount(new TermQuery(new Term("_PK", "100000"))));
pks = genericFTSLucene.fullTextSearch(new TermQuery(new Term("_PK", "100000")));
assertNotNull(pks);
assertEquals(1, pks.size());
assertTrue(pks.contains(100000L));
// Range Criteria
assertEquals(2, genericFTSLucene.fullTextSearchCount(LongPoint.newRangeQuery("_PK_range", 100001L, Math.addExact(999999L, -1))));
pks = genericFTSLucene.fullTextSearch(LongPoint.newRangeQuery("_PK_range", 100001L, Math.addExact(999999L, -1)));
assertNotNull(pks);
assertEquals(2, pks.size());
assertTrue(pks.contains(100001L));
assertTrue(pks.contains(111111L));
// Term Criteria single term
assertEquals(2, genericFTSLucene.fullTextSearchCount(new TermQuery(new Term("name", "item"))));
pks = genericFTSLucene.fullTextSearch(new TermQuery(new Term("name", "item")));
assertNotNull(pks);
assertEquals(2, pks.size());
assertTrue(pks.contains(100000L));
assertTrue(pks.contains(100001L));
// Term Criteria single term not found
assertEquals(0, genericFTSLucene.fullTextSearchCount(new TermQuery(new Term("name", "ite"))));
pks = genericFTSLucene.fullTextSearch(new TermQuery(new Term("name", "ite")));
assertNotNull(pks);
assertEquals(0, pks.size());
// Fuzzy Criteria
assertEquals(2, genericFTSLucene.fullTextSearchCount(new FuzzyQuery(new Term("_PK", "100000"))));
pks = genericFTSLucene.fullTextSearch(new FuzzyQuery(new Term("_PK", "100000")));
assertNotNull(pks);
assertEquals(2, pks.size());
assertTrue(pks.contains(100000L));
assertTrue(pks.contains(100001L));
// Fuzzy Criteria mis-spell
assertEquals(2, genericFTSLucene.fullTextSearchCount(new FuzzyQuery(new Term("name", "utem"))));
pks = genericFTSLucene.fullTextSearch(new FuzzyQuery(new Term("name", "utem")));
assertNotNull(pks);
assertEquals(2, pks.size());
assertTrue(pks.contains(100000L));
assertTrue(pks.contains(100001L));
// All documents pagination
pks = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery(), 0, 1, null, false);
assertNotNull(pks);
assertEquals(1, pks.size());
assertTrue(pks.contains(100000L));
pks = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery(), 1, 1, null, false);
assertNotNull(pks);
assertEquals(1, pks.size());
assertTrue(pks.contains(100001L));
pks = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery(), 2, 1, null, false);
assertNotNull(pks);
assertEquals(1, pks.size());
assertTrue(pks.contains(111111L));
// All documents pagination, sorted
pks = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery(), 0, 1, "_PK_sort", true);
assertNotNull(pks);
assertEquals(1, pks.size());
assertTrue(pks.contains(111111L));
pks = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery(), 1, 1, "_PK_sort", true);
assertNotNull(pks);
assertEquals(1, pks.size());
assertTrue(pks.contains(100001L));
pks = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery(), 2, 1, "_PK_sort", true);
assertNotNull(pks);
assertEquals(1, pks.size());
assertTrue(pks.contains(100000L));
// Specific field, page 2, sorted
rez = genericFTSLucene.fullTextSearch(new MatchAllDocsQuery(), 1, 1, "_PK_sort", true, "_PK", "_OBJECT");
assertNotNull(rez);
assertEquals(Integer.valueOf(3), rez.getSecond());
final List<Object[]> vals = rez.getFirst();
assertNotNull(vals);
assertEquals(1, vals.size());
assertEquals("100001", vals.get(0)[0]);
assertEquals("{\"name\":\"item two\",\"_PK\":\"100001\",\"desc\":\"other desc\"}", vals.get(0)[1]);
}
@Test
public void testFullTextSearchNavigation() throws Exception {
indexBuilderLucene.setDocs(
(List) Arrays.asList(
new HashMap<String, String>() {{
put("_PK", "100000");
put("name", "item one");
put("desc", "some desc");
put("attr1", "A1");
}},
new HashMap<String, Object>() {{
put("_PK", "100001");
put("name", "item two");
put("desc", Arrays.asList("some desc", "other desc"));
put("attr1", "A1");
}},
new HashMap<String, String>() {{
put("_PK", "111111");
put("name", "element");
put("desc", "other desc");
put("attr1", "A1");
}},
new HashMap<String, String>() {{
put("_PK", "111112");
put("name", "element");
put("desc", "other desc");
put("attr1", "A2");
}},
new HashMap<String, String>() {{
put("_PK", "111113");
put("name", "element");
put("desc", "desc");
put("attr1", "A2");
}},
new HashMap<String, String>() {{
put("_PK", "111114");
put("name", "element");
put("desc", "desc");
put("attr1", "A3");
}}
)
);
documentAdapter.setFacets(Arrays.asList("_PK", "name", "desc"));
indexBuilderLucene.fullTextSearchReindex(false, 2);
Map<String, List<Pair<Pair<String, I18NModel>, Integer>>> rez;
List<Pair<Pair<String, I18NModel>, Integer>> facets;
final FilteredNavigationRecordRequest r1 = new FilteredNavigationRecordRequestImpl("PK Range", "_PK_facet", Arrays.asList(new Pair<>("000000", "100001"), new Pair<>("100001", "999999")));
final FilteredNavigationRecordRequest f1 = new FilteredNavigationRecordRequestImpl("Names", "name_facet", false);
final FilteredNavigationRecordRequest f2 = new FilteredNavigationRecordRequestImpl("Descriptions", "desc_facet", true);
final List<FilteredNavigationRecordRequest> fr = Arrays.asList(r1, f1, f2);
// Global facets, with range and multi-values
rez = genericFTSLucene.fullTextSearchNavigation(new MatchAllDocsQuery(), fr);
assertNotNull(rez);
assertEquals(3, rez.size());
facets = rez.get("PK Range");
assertEquals(2, facets.size());
checkFacetValue(facets, "000000-_-100001", 1);
checkFacetValue(facets, "100001-_-999999", 5);
facets = rez.get("Names");
assertEquals(3, facets.size());
checkFacetValue(facets, "item one", 1);
checkFacetValue(facets, "item two", 1);
checkFacetValue(facets, "element", 4);
facets = rez.get("Descriptions");
assertEquals(3, facets.size());
checkFacetValue(facets, "some desc", 2);
checkFacetValue(facets, "other desc", 3);
checkFacetValue(facets, "desc", 2);
// Global facets, drill-down by non faceted value
rez = genericFTSLucene.fullTextSearchNavigation(new TermQuery(new Term("attr1", "a2")), fr);
assertNotNull(rez);
assertEquals(3, rez.size());
facets = rez.get("PK Range");
assertEquals(2, facets.size());
checkFacetValue(facets, "000000-_-100001", 0);
checkFacetValue(facets, "100001-_-999999", 2);
facets = rez.get("Names");
assertEquals(1, facets.size());
checkFacetValue(facets, "element", 2);
facets = rez.get("Descriptions");
assertEquals(2, facets.size());
checkFacetValue(facets, "other desc", 1);
checkFacetValue(facets, "desc", 1);
// Global facets, drill-down by faceted value
rez = genericFTSLucene.fullTextSearchNavigation(LongPoint.newRangeQuery("_PK_range", 100001L, Math.addExact(999999L, -1)), fr);
assertNotNull(rez);
assertEquals(3, rez.size());
facets = rez.get("PK Range");
assertEquals(2, facets.size());
checkFacetValue(facets, "000000-_-100001", 0);
checkFacetValue(facets, "100001-_-999999", 5);
facets = rez.get("Names");
assertEquals(2, facets.size());
checkFacetValue(facets, "item two", 1);
checkFacetValue(facets, "element", 4);
facets = rez.get("Descriptions");
assertEquals(3, facets.size());
checkFacetValue(facets, "some desc", 1);
checkFacetValue(facets, "other desc", 3);
checkFacetValue(facets, "desc", 2);
}
private void checkFacetValue(List<Pair<Pair<String, I18NModel>, Integer>> facets, String expectedValue, Integer expectedCount) {
for (final Pair<Pair<String, I18NModel>, Integer> facet : facets) {
if (expectedValue.equals(facet.getFirst().getFirst())) {
assertEquals("Unexpected count for " + facet.getFirst(), expectedCount, facet.getSecond());
return;
}
}
fail("Facet value '" + expectedValue + "' with count " + expectedCount + " not found in " + facets);
}
}
|
// Copyright (C) 2014 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au
//! \addtogroup xtrans_mat
//! @{
template<typename eT, bool do_conj>
class xtrans_mat : public Base<eT, xtrans_mat<eT, do_conj> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<elem_type>::result pod_type;
static const bool is_row = false;
static const bool is_col = false;
arma_aligned const Mat<eT>& X;
arma_aligned mutable Mat<eT> Y;
arma_aligned const uword n_rows;
arma_aligned const uword n_cols;
arma_aligned const uword n_elem;
inline explicit xtrans_mat(const Mat<eT>& in_X);
inline void extract(Mat<eT>& out) const;
inline eT operator[](const uword ii) const;
inline eT at_alt (const uword ii) const;
arma_inline eT at(const uword in_row, const uword in_col) const;
};
//! @}
|
/* helper to write a pmic register */
static int qpnp_wled_write_reg(struct qpnp_wled *wled, u16 addr, u8 data)
{
int rc;
mutex_lock(&wled->bus_lock);
rc = regmap_write(wled->regmap, addr, data);
if (rc < 0) {
dev_err(&wled->pdev->dev, "Error writing address: %x(%d)\n",
addr, rc);
goto out;
}
dev_dbg(&wled->pdev->dev, "wrote: WLED_0x%x = 0x%x\n", addr, data);
out:
mutex_unlock(&wled->bus_lock);
return rc;
}
|
def simpleMerge(a, b):
total = len(a) + len(b)
j, k = 0, 0
c = list()
for i in range(total):
if (k == len(b) or (j < len(a) and a[j] < b[k])):
c.append(a[j])
j += 1
else:
c.append(b[k])
k += 1
return(c)
aSize, bSize = map(int, input().split()) # Apenas para acordar com o simple_merge.in
a = list(map(int, input().split())) # Lê uma lista em uma linha
b = list(map(int, input().split())) # Lê uma lista em uma linha
result = simpleMerge(a, b)
for i in result:
print(i)
|
/**
* Unchecked instantiation of a class
* @param clazz the class to instantiate
* @return the instantiated object
*/
public static <T> T newInstance(Class<T> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
|
/// Swap a value at given index with the top value
pub fn swap(&mut self, no_from_top: usize) -> Result<(), ExitError> {
if self.data.len() <= no_from_top {
return Err(ExitError::StackUnderflow);
}
let len = self.data.len();
let a = len - no_from_top - 1;
let b = len - 1;
self.data.swap(a, b);
Ok(())
}
|
/*
* Copyright 2015-2017 the original author or 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 kr.gooroom.gpms.interceptor;
import java.util.Calendar;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import kr.gooroom.gpms.common.service.GpmsCommonService;
import kr.gooroom.gpms.common.utils.LoginInfoHelper;
/**
* Intercepter class for MVC framework.
* <p>
* create global object.
*
* @author HNC
* @version 1.0
* @since 1.8
*/
public class GPMSInterceptor extends HandlerInterceptorAdapter {
// private static final Logger logger =
// LoggerFactory.getLogger(GPMSInterceptor.class);
@Resource(name = "gpmsCommonService")
private GpmsCommonService gpmsCommonService;
/**
* pre handle method.
*
* @param req HttpServletRequest
* @param res HttpServletResponse
* @param handler Object
* @return StatusVO result status
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
String actItem = req.getRequestURI();
if (actItem.indexOf("/") > -1) {
actItem = actItem.substring(actItem.lastIndexOf("/"));
}
String actType = "ETC";
if (actItem.startsWith("/create")) {
actType = "I";
} else if (actItem.startsWith("/delete")) {
actType = "D";
} else if (actItem.startsWith("/is")) {
actType = "B";
} else if (actItem.startsWith("/page")) {
actType = "M";
} else if (actItem.startsWith("/read")) {
actType = "R";
} else if (actItem.startsWith("/update")) {
actType = "U";
}
@SuppressWarnings("unchecked")
Map<String, Object> paramMap = (Map<String, Object>) req.getParameterMap();
String actData = "";
if (paramMap.size() > 0) {
StringBuffer sb = new StringBuffer();
Set<String> keys = paramMap.keySet();
for (String key : keys) {
sb.append("{[").append(key).append("][").append(req.getParameter(key)).append("]}\n");
}
actData = sb.toString();
}
if (LoginInfoHelper.isAuthenticated()) {
gpmsCommonService.createUserActLogHistory(actType, actItem, actData, req.getRemoteAddr(),
LoginInfoHelper.getUserId());
}
return true;
}
/**
* post handle method.
*
* @param req HttpServletRequest
* @param res HttpServletResponse
* @param handler Object
* @return StatusVO result status
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView)
throws Exception {
// for version
if (modelAndView != null) {
// get locale for message
modelAndView.addObject("gpmsLanguage", req.getLocale().getLanguage());
modelAndView.addObject("gpmsVersion", String.valueOf(Calendar.getInstance().getTimeInMillis()));
// modelAndView.addObject("gpmsVersion", "1");
if (req != null && req.getParameter("b") != null) {
String[] menus = req.getParameter("b").split(":");
modelAndView.addObject("GRMENUS", menus);
}
}
}
}
|
import React, { useState, useEffect } from 'react';
import { apiClient } from '../../../api/Client';
import { trackGoal } from '../../../utils';
import { RepositoryResponse, RepositoriesResponse } from '../../../api/openapi';
import { ListItem, ListItemIcon, ListItemText, IconButton, ListItemSecondaryAction, List, Typography, Card, Dialog, DialogTitle, DialogContent, CircularProgress, Button, DialogActions } from '@material-ui/core';
import { Add, GitHub } from '@material-ui/icons';
import { PullDogPricingTable } from './PullDogPricingTable';
import { pullDogSettingsAccessor } from '../../../hooks/pull-dog';
import { useGlobalResource } from '@fluffy-spoon/react-globalize';
import { RouteComponentProps } from '@reach/router';
const PullDogRepositorySettingsDialog = (props: { repository: RepositoryResponse, onDismiss: () => void }) => {
return <>
{!!props.repository && <Dialog open>
<DialogTitle>
Configure repository
</DialogTitle>
<DialogContent>
<Typography variant="body1">
A repository will automatically be installed if you open a pull request for the repository, and a <pre style={{display: 'inline'}}>pull-dog.json</pre> is present in the root directory of the <pre style={{display: 'inline'}}>master</pre> branch.
</Typography>
<Typography variant="body1">
Repository handle: <pre style={{display: 'inline'}}>{props.repository.handle}</pre>
</Typography>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={() => props.onDismiss()} color="primary">
OK
</Button>
</DialogActions>
</Dialog>}
</>;
};
export const PullDogPage = (props: RouteComponentProps) => {
const [settingsResponse] = useGlobalResource(pullDogSettingsAccessor);
const [repositoriesResponse, setRepositoriesResponse] = useState<RepositoriesResponse>(void 0);
const [selectedRepository, setSelectedRepository] = useState<RepositoryResponse>(null);
useEffect(() => {
if(settingsResponse && settingsResponse.isInstalled)
apiClient.apiPullDogRepositoriesGet().then(setRepositoriesResponse);
}, [settingsResponse]);
useEffect(() => {
if(!!selectedRepository)
trackGoal("NotImplementedManualRepositorySetup");
}, [selectedRepository]);
if(!settingsResponse)
return <CircularProgress />;
const areRepositoriesLoading = settingsResponse.isInstalled && !repositoriesResponse;
if(!settingsResponse.isInstalled) {
return <>
<Typography variant="h3">
Pull Dog
</Typography>
<Typography variant="body1" style={{opacity: 0.4}}>
Automatic test environments for your pull requests, based on a Docker Compose file.
</Typography>
<Button
variant="contained"
color="primary"
startIcon={<GitHub />}
style={{ alignSelf: 'flex-start', marginTop: 16 }}
onClick={() => {
if(typeof window === "undefined")
return;
window.location.href = window.location.href.indexOf('://localhost') > -1 ?
'https://github.com/settings/apps/pull-dog-debugging/installations' :
'https://github.com/apps/pull-dog/installations/new'
}}
>
Install
</Button>
</>;
}
const repositories = repositoriesResponse?.repositories;
const managedRepositories = repositories?.filter(x => !!x.pullDogId);
return <>
<PullDogRepositorySettingsDialog
repository={selectedRepository}
onDismiss={() => setSelectedRepository(null)} />
<Typography variant="h3">
Your plan
</Typography>
<PullDogPricingTable />
<Typography variant="h3" style={{marginTop: 24}}>
API key
</Typography>
<Typography variant="body1" style={{opacity: 0.4}}>
The API key is used for certain operations like advanced configuration and lazy provisioning of servers from build environments.
</Typography>
<Typography variant="body1" style={{opacity: 0.4}}>
Your API key is: <span style={{display: 'inline'}}>{settingsResponse.apiKey}</span>
</Typography>
<Typography variant="h3" style={{ marginTop: 24 }}>
Repositories
</Typography>
{areRepositoriesLoading ?
<CircularProgress /> :
<Card style={{
marginTop: 12
}}>
<List>
{managedRepositories.map(value =>
<ListItem
key={value.handle}
button
onClick={() => setSelectedRepository(value)}
>
<ListItemIcon style={{
minWidth: 40
}}>
<GitHub/>
</ListItemIcon>
<ListItemText>
{value.name}
</ListItemText>
</ListItem>)}
</List>
</Card>}
</>
}
|
#include <stdio.h>
#include <stdint.h>
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
typedef long long int LL;
int main()
{
LL num,t,p,q,count=0;
LL a,b;
LL c=0;
cin>>num>>a>>b;
// LL arr[num];
LL i=0;
for(i=0;i<num;i++)
{
cin>>p;
if(p==1)
{
if(a>0)
{
a=a-1;
}
else if(b>0)
{
b=b-1;
c=c+1;
}
else if(c>0)
{
c=c-1;
}
else
{
count++;
}
}
else
{
if(b>0)
{
b=b-1;
}
else
{
count=count+2;
}
}
}
cout<<""<<count;
}
|
async def webserver(loop, view, addr, port, path='/', method='POST'):
app = web.Application(loop=loop)
app.router.add_route(method, path, view)
srv = await loop.create_server(app.make_handler(),
addr, port)
return srv
|
Protesters outside an Apple store in Boston last month. (Steven Senne/AP)
The feud between Apple and the Justice Department took another turn Tuesday, as the technology giant used a new court filing to say that the Founding Fathers “would be appalled” with the government’s stance.
Apple argued that if the government prevails, it could force companies to do a number of other things going forward in the name of surveillance and security, such as seeking software that would use phones to track movements or listen to conversations. Apple added in a particularly acidic footnote: “The government is adept at devising new surveillance techniques.”
While the government has argued this case is about one locked iPhone belonging to one of the attackers who killed 14 people in San Bernardino, Calif., in December, Apple says this argument can only be resolved in the context of the larger debate playing out nationwide over encryption and security.
“This case arises in a difficult context after a terrible tragedy,” Apple wrote. “But it is in just such highly-charged and emotional cases that the courts must zealously guard civil liberties and the rule of law and reject government overreaching.”
[San Bernardino victims and tech groups square off over Apple-FBI fight]
The Justice Department sought and received a judge’s order last month under the All Writs Act of 1789 that would have forced Apple to help them access the contents of the locked phone, but Apple has fought the order.
Under this order, Apple was told to write software that would disable a feature deleting the phone’s data after 10 incorrect password attempts. The FBI says this help is limited to this case, but Apple argues that the government is effectively seeking a back door that would weaken security. In its latest filing, Apple also argued that the 1789 law cannot be used this way.
“The government attempts to rewrite history by portraying the Act as an all-powerful magic wand rather than the limited procedural tool it is,” Apple wrote in a brief filed Tuesday in the U.S. District Court for the Central District of California’s Eastern Division.
The company added: “Forcing Apple to create new software that degrades its security features is unprecedented and unlike any burden ever imposed under the All Writs Act.”
[Justice Dept. says Apple intentionally raised the ‘technological barriers’ in this case]
The Justice Department did not immediately respond to a request for comment Tuesday.
As the argument has played out publicly, it has become increasingly acrimonious, with both sides using court documents and public appearances to snipe at each other. The Justice Department has said that Apple is only looking out for its marketing, while the tech company says the FBI is seeking a “dangerous power.”
An iPhone’s locked screen. (Erik S. Lesser/European Pressphoto Agency)
Last week, the Justice Department had said attempts by Apple and other Silicon Valley giants to link the fight to the broader debate over encryption were a “diversion,” arguing in a court filing that the fight was one of Apple’s own making.
Apple’s general counsel responded to the brief by saying it “reads like an indictment” and was filled with “false accusations and innuendo.”
In recent weeks, Apple has been joined by numerous other major tech firms — a list that includes Google, Facebook, Twitter, Amazon and Microsoft — arguing this case could set a dangerous precedent and endanger the privacy of countless people relying on encrypted devices. Law enforcement groups and some relatives of victims of the San Bernardino attack have sided with the FBI, saying the phone could contain information on possible accomplices or other terrorists.
President Obama said last week that while he would not comment on this case, he said the government must be able to maintain its access to encrypted information, saying that seeking “strong encryption, no matter what … does not strike the kind of balance” he believes is needed.
The case is set to head to a courtroom next week in California for oral arguments, but experts say it could continue to be fought all the way to the U.S. Supreme Court.
Related:
FBI director: Victory in this fight could set a precedent and lead to more requests
U.N. human rights chief: If Apple loses, lives could be in danger
Justice Department appeals ruling involving a locked iPhone in a different case
|
/** TODO: refactor this out into a data access layer */
public void populate(Result result) {
NavigableMap<byte[], byte[]> infoValues = result.getFamilyMap(Constants.INFO_FAM_BYTES);
this.jobId = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.JOBID), infoValues);
this.user = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.USER), infoValues);
this.jobName = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.JOBNAME),infoValues);
this.priority = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.JOB_PRIORITY), infoValues);
this.status = ByteUtil.getValueAsString(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.JOB_STATUS), infoValues);
this.hadoopVersion = getHadoopVersionFromResult(JobHistoryKeys.hadoopversion, infoValues);
this.version = ByteUtil.getValueAsString(Constants.VERSION_COLUMN_BYTES, infoValues);
this.cost = ByteUtil.getValueAsDouble(Constants.JOBCOST_BYTES, infoValues);
this.submitTime = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.SUBMIT_TIME), infoValues);
this.launchTime = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.LAUNCH_TIME), infoValues);
this.finishTime = ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES
.get(JobHistoryKeys.FINISH_TIME), infoValues);
this.megabyteMillis = ByteUtil.getValueAsLong(Constants.MEGABYTEMILLIS_BYTES, infoValues);
this.cost = ByteUtil.getValueAsDouble(Constants.JOBCOST_BYTES, infoValues);
this.totalMaps =
ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_MAPS),
infoValues);
this.totalReduces =
ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_REDUCES),
infoValues);
this.finishedMaps =
ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_MAPS),
infoValues);
this.finishedReduces =
ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FINISHED_REDUCES),
infoValues);
this.failedMaps =
ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_MAPS),
infoValues);
this.failedReduces =
ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.FAILED_REDUCES),
infoValues);
this.config = JobHistoryService.parseConfiguration(infoValues);
this.queue = this.config.get(Constants.HRAVEN_QUEUE);
this.counters = JobHistoryService.parseCounters(Constants.COUNTER_COLUMN_PREFIX_BYTES,
infoValues);
this.mapCounters = JobHistoryService.parseCounters(Constants.MAP_COUNTER_COLUMN_PREFIX_BYTES,
infoValues);
this.reduceCounters = JobHistoryService.parseCounters(Constants.REDUCE_COUNTER_COLUMN_PREFIX_BYTES,
infoValues);
if (this.hadoopVersion == HadoopVersion.TWO) {
this.mapFileBytesRead = getCounterValueAsLong(this.mapCounters,
Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.FILES_BYTES_READ);
this.mapFileBytesWritten = getCounterValueAsLong(this.mapCounters,
Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.FILES_BYTES_WRITTEN);
this.reduceFileBytesRead = getCounterValueAsLong(this.reduceCounters,
Constants.FILESYSTEM_COUNTER_HADOOP2, Constants.FILES_BYTES_READ);
this.hdfsBytesRead = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTER_HADOOP2,
Constants.HDFS_BYTES_READ);
this.hdfsBytesWritten = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTER_HADOOP2,
Constants.HDFS_BYTES_WRITTEN);
this.mapSlotMillis = getCounterValueAsLong(this.counters, Constants.JOB_COUNTER_HADOOP2,
Constants.SLOTS_MILLIS_MAPS);
this.reduceSlotMillis = getCounterValueAsLong(this.counters, Constants.JOB_COUNTER_HADOOP2,
Constants.SLOTS_MILLIS_REDUCES);
this.reduceShuffleBytes = getCounterValueAsLong(this.reduceCounters, Constants.TASK_COUNTER_HADOOP2,
Constants.REDUCE_SHUFFLE_BYTES);
} else {
this.mapFileBytesRead = getCounterValueAsLong(this.mapCounters, Constants.FILESYSTEM_COUNTERS,
Constants.FILES_BYTES_READ);
this.mapFileBytesWritten = getCounterValueAsLong(this.mapCounters, Constants.FILESYSTEM_COUNTERS,
Constants.FILES_BYTES_WRITTEN);
this.reduceFileBytesRead = getCounterValueAsLong(this.reduceCounters, Constants.FILESYSTEM_COUNTERS,
Constants.FILES_BYTES_READ);
this.hdfsBytesRead = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTERS,
Constants.HDFS_BYTES_READ);
this.hdfsBytesWritten = getCounterValueAsLong(this.counters, Constants.FILESYSTEM_COUNTERS,
Constants.HDFS_BYTES_WRITTEN);
this.mapSlotMillis = getCounterValueAsLong(this.counters, Constants.JOBINPROGRESS_COUNTER,
Constants.SLOTS_MILLIS_MAPS);
this.reduceSlotMillis = getCounterValueAsLong(this.counters, Constants.JOBINPROGRESS_COUNTER,
Constants.SLOTS_MILLIS_REDUCES);
this.reduceShuffleBytes = getCounterValueAsLong(this.reduceCounters, Constants.TASK_COUNTER,
Constants.REDUCE_SHUFFLE_BYTES);
}
}
|
/**
* Returns object with the given {@code key} from the storage or {@code null} if object does not exist.
* <br>
* TODO: Consider returning {@code Optional<V>} instead.
* @param key Key of the object. Must not be {@code null}.
* @return See description
* @throws NullPointerException if the {@code key} is {@code null}
*/
public V read(String key) {
Objects.requireNonNull(key, "Key must be non-null");
K k = keyConvertor.fromStringSafe(key);
return store.get(k);
}
|
// Finish signals that the word model is finished and ready to be used.
func (m *WordModel) Finish() {
m.finder = m.builder.Finish()
log.Printf("Model has %v words, %v edges", m.finder.NumAdded(), m.finder.NumEdges())
var sum float64
for _, freq := range m.frequencies {
sum += float64(freq)
}
log.Printf("freq sum is %v", sum)
logT := math.Log2(sum)
for i, freq := range m.frequencies {
m.frequencies[i] = float32(logT - math.Log2(float64(freq)))
}
}
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Api.Response where
import Data.Aeson
import GHC.Generics
import qualified Data.Text as T
import Control.Applicative
data Answer
= Answer { ts :: T.Text,
updates :: [Update] }
| FailAnswer { fail' :: Int }
| FailTSAnswer { fail'' :: Int,
ts'' :: Int }
| ErrorAnswer { error' :: Object } deriving (Generic, Show)
instance FromJSON Answer where
parseJSON (Object v) = (Answer
<$> v .: "ts"
<*> v .: "updates") <|> ( FailAnswer
<$> v .: "fail") <|> ( FailTSAnswer
<$> v .: "fail"
<*> v .: "ts") <|> ( ErrorAnswer
<$> v .: "error")
data Update
= Update {typeUpd :: T.Text,
objectUpd :: AboutObj
}
| UnknownUpdate Object
deriving ( Show)
instance FromJSON Update where
parseJSON (Object v) = (Update
<$> v .: "type"
<*> v .: "object") <|> (UnknownUpdate <$> parseJSON (Object v))
data AboutObj = AboutObj {
from_id :: Int
, id :: Int
, peer_id :: Int
, text :: T.Text
, fwd_messages :: [Object]
, attachments :: [Attachment]
, geo :: Maybe Geo
} deriving (Generic, Show)
instance FromJSON AboutObj
data Attachment
= PhotoAttachment
{ type' :: T.Text
, photoPA :: Photo }
| DocAttachment
{ type' :: T.Text
, docDA :: Doc }
| AudioMesAttachment
{ type' :: T.Text
, audio_message :: Audio }
| VideoAttachment
{ type' :: T.Text
, docVA :: DocInfo }
| StickerAttachment
{ type' :: T.Text
, sticker :: StickerInfo }
| AudioAttachment
{ type' :: T.Text
, audio :: DocInfo }
| MarketAttachment
{ type' :: T.Text
, market :: DocInfo }
| WallAttachment
{ type' :: T.Text
, wall :: WallInfo }
| PollAttachment
{ type' :: T.Text
, poll :: DocInfo }
| UnknownAttachment Object
deriving (Generic, Show)
instance FromJSON Attachment where
parseJSON (Object v) = (PhotoAttachment
<$> v .: "type"
<*> v .: "photo") <|> (DocAttachment
<$> v .: "type"
<*> v .: "doc") <|> (AudioMesAttachment
<$> v .: "type"
<*> v .: "audio_message") <|> (VideoAttachment
<$> v .: "type"
<*> v .: "video") <|> (StickerAttachment
<$> v .: "type"
<*> v .: "sticker") <|> (AudioAttachment
<$> v .: "type"
<*> v .: "audio") <|> (MarketAttachment
<$> v .: "type"
<*> v .: "market") <|> (WallAttachment
<$> v .: "type"
<*> v .: "wall") <|> (PollAttachment
<$> v .: "type"
<*> v .: "poll") <|> (UnknownAttachment <$> parseJSON (Object v))
data Doc
= Doc{
urlD :: T.Text
, ext :: String
, title :: String
} deriving (Show)
instance FromJSON Doc where
parseJSON (Object v) = Doc
<$> v .: "url"
<*> v .: "ext"
<*> v .: "title"
data Audio = Audio {
link_ogg :: T.Text
} deriving (Generic, Show)
instance FromJSON Audio
data Photo = Photo {
sizes :: [Size]
} deriving (Generic, Show)
instance FromJSON Photo
data Size = Size {
height :: Integer
, width :: Integer
, url :: T.Text
} deriving (Generic, Show)
instance FromJSON Size
data LoadDocResp = LoadDocResp {
file :: String
} deriving (Generic, Show)
instance FromJSON LoadDocResp
data LoadPhotoResp = LoadPhotoResp {
server :: Int
, hash :: String
, photo :: String
} deriving (Generic, Show)
instance FromJSON LoadPhotoResp
data SavePhotoResp = SavePhotoResp {responseSPR :: [DocInfo]} deriving (Generic, Show)
instance FromJSON SavePhotoResp where
parseJSON (Object v) = SavePhotoResp
<$> v .: "response"
data PhotoInfo = PhotoInfo {
idPI :: Int
, owner_id :: Int
, access_key :: String
} deriving (Generic, Show)
instance FromJSON PhotoInfo where
parseJSON (Object v) = PhotoInfo
<$> v .: "id"
<*> v .: "owner_id"
<*> v .: "access_key"
data AudioMesInfo = AudioMesInfo {
idAMI :: Int
, owner_idAMI :: Int
, access_keyAMI :: String
} deriving (Generic, Show)
instance FromJSON AudioMesInfo where
parseJSON (Object v) = AudioMesInfo
<$> v .: "id"
<*> v .: "owner_id"
<*> v .: "access_key"
data StickerInfo = StickerInfo {
sticker_id :: Int
} deriving (Generic, Show)
instance FromJSON StickerInfo
data SaveDocResp = SaveDocResp {responseSDR :: ResponseSDR} deriving (Generic, Show)
instance FromJSON SaveDocResp where
parseJSON (Object v) = SaveDocResp
<$> v .: "response"
data ResponseSDR = ResponseSDR {
typeRSDR :: T.Text
, docRSDR :: DocInfo
} deriving (Generic, Show)
instance FromJSON ResponseSDR where
parseJSON (Object v) = ResponseSDR
<$> v .: "type"
<*> v .: "doc"
data DocInfo = DocInfo {
idDI :: Int
, owner_idDI :: Int
} deriving (Generic, Show)
instance FromJSON DocInfo where
parseJSON (Object v) = DocInfo
<$> v .: "id"
<*> v .: "owner_id"
data WallInfo = WallInfo {
idWI :: Int
, from_idWI :: Int
} deriving (Generic, Show)
instance FromJSON WallInfo where
parseJSON (Object v) = WallInfo
<$> v .: "id"
<*> v .: "from_id"
data SaveDocAuMesResp = SaveDocAuMesResp {responseSDAMR :: ResponseSDAMR} deriving (Generic, Show)
instance FromJSON SaveDocAuMesResp where
parseJSON (Object v) = SaveDocAuMesResp
<$> v .: "response"
data ResponseSDAMR = ResponseSDAMR {
typeSDAMR :: T.Text
, docSDAMR :: DocInfo
} deriving (Generic, Show)
instance FromJSON ResponseSDAMR where
parseJSON (Object v) = ResponseSDAMR
<$> v .: "type"
<*> v .: "audio_message"
data GetPollServerJSONBody
= GetPollServerJSONBody { response :: ServerInfo}
| ErrorAnswerServ { error'' :: Object } deriving (Generic, Show)
instance FromJSON GetPollServerJSONBody where
parseJSON (Object v) = (GetPollServerJSONBody
<$> v .: "response") <|> ( ErrorAnswerServ
<$> v .: "error")
data ServerInfo
= ServerInfo { key :: T.Text,
serverSI :: T.Text,
tsSI :: T.Text} deriving (Generic, Show)
instance FromJSON ServerInfo where
parseJSON (Object v) = ServerInfo
<$> v .: "key"
<*> v .: "server"
<*> v .: "ts"
data Response
= Response { response' :: Int }
| ErrorAnswerMsg { error''' :: Object } deriving (Generic, Show)
instance FromJSON Response where
parseJSON (Object v) = (Response
<$> v .: "response") <|> ( ErrorAnswerMsg
<$> v .: "error")
data ErrorInfo = ErrorInfo { error_code :: Int} deriving (Generic, Show)
instance FromJSON ErrorInfo
data UploadServerResponse = UploadServerResponse {responsePSR :: UploadUrl} deriving (Generic, Show)
instance FromJSON UploadServerResponse where
parseJSON (Object v) = UploadServerResponse
<$> v .: "response"
data UploadUrl = UploadUrl {upload_url :: T.Text} deriving (Generic, Show)
instance FromJSON UploadUrl
data Geo = Geo {
typeG :: T.Text
, coordinates :: Coordinates
} deriving (Eq, Generic, Show)
instance FromJSON Geo where
parseJSON (Object v) = Geo
<$> v .: "type"
<*> v .: "coordinates"
data Coordinates = Coordinates {
latitude :: Double
, longitude :: Double
} deriving (Eq, Generic, Show)
instance FromJSON Coordinates
|
A Brief History of Chinese DotA, Part 1 February 17th, 2013 22:11 GMT Text by Kupon3ss Graphics by shiroiusagi
A Brief History of Chinese DotA: Part 1 Table of Contents
Victory Above All Else
An Introduction to Chinese DotA
The Rise of a Great Power
Chinese DotA Emerges
Dominion over Heaven and Earth
The Romance of the Three Kingdoms
That which is Long Divided
The Sundering of the Triumvirate
An Introduction to Chinese DotAChinese DotA EmergesThe Romance of the Three KingdomsThe Sundering of the Triumvirate
Victory Above All Else
"The entire scene is just much more professional. They train all the time, and that's their job!"
– Loda
Chinese DotA is not about ganking, Chinese DotA is not about pushing, Chinese DotA isn’t even about farming; Chinese DotA is about winning. From the pressure of 三核 (the three core) to the 冲脸 (facerush) of today, the consummate that ties the disparate styles of Chinese DotA together is the desire for victory. If the version and meta dictates that farming for 70 minutes is the most consistent and effective method for winning, so be it. Likewise, when pushing down all of the lanes within 30 minutes was found to be the best road to the top, Chinese DotA did not hesitate to do so with overwhelming force. This is the difference between Chinese and Western DotA; whereas most in the West pursue it as a hobby, the Chinese youngsters who embark upon this path do so with complete devotion. It is a career, even a life.
The following seeks to be a brief primer into the world of Chinese DotA, a rough sketch of what lies behind the false perception that Chinese DotA was all about farming,
Chinese DotA is not about ganking, Chinese DotA is not about pushing, Chinese DotA isn’t even about farming; Chinese DotA is about winning. From the pressure of 三核 (the three core) to the 冲脸 (facerush) of today, the consummate that ties the disparate styles of Chinese DotA together is the desire for victory. If the version and meta dictates that farming for 70 minutes is the most consistent and effective method for winning, so be it. Likewise, when pushing down all of the lanes within 30 minutes was found to be the best road to the top, Chinese DotA did not hesitate to do so with overwhelming force. This is the difference between Chinese and Western DotA; whereas most in the West pursue it as a hobby, the Chinese youngsters who embark upon this path do so with complete devotion. It is a career, even a life.The following seeks to be a brief primer into the world of Chinese DotA, a rough sketch of what lies behind the false perception that Chinese DotA was all about farming,
2009 - 大国崛起
The Rise of a Great Power Chinese DotA Emerges
With EHome’s victory in SMM 2008, Chinese DotA took the first step onto the world stage. Having been prevented from going to ESWC 2008 by visa issues, SMM’s clashes of the finest teams SEA had to offer drew less attention than a foray to Europe likely would have, but it certainly made legends like Loda pay attention. Perhaps the first glimpse of a distinct Chinese style came when a team obtained some “secret Chinese replays” with the first trademark Chinese hero – Bristleback. In fact, the hero began to make a splash in China when it became heavily nerfed, the first of many testaments to the strength and understanding of Chinese DotA.
The scene developed with a style that was an amalgamation of Western and SEA styles, spiced with Chinese elements. EHome and KS.cn, the two strongest teams at the start of the era, both ran highly aggressive styles. EHome’s play often centered around gank and push, while KS.cn favored a push/teamfight composition. Ironically, in those early days, BurNIng was known as the best Chen in China, while LongDD (the best carry in China during his time on KS.cn) played first position for EHome and was famed for his farming ability. That their reputations would be flipped years later should come as no surprise to fans of Chinese DotA.
The establishment of For The Dream in August, and the release of 6.64 in October, would set the stage for the rise of China. Importing the nascent SEA style of running three lanes, FTD would hone that lineup to perfection and come to own the era.
三核 - Three Cores
Tanking, Damaging, Winning Meet the Cores
The three core meta is perhaps the first famous Chinese Style. Its workings come from an early understanding of lanes and of pressure. Fundamentally, it relied upon the use of 3 carries or semi-carries that were difficult to gank, and could clear waves quickly and scale very effectively into the lategame.
Its use and effectiveness can be summed up by this simple paradigm: if it takes three enemy heroes to gank one of your cores, the lane pressure and farm accumulated in the other two lanes will more than offset the benefit of the gank. With this consistent economic and creepwave advantage, combined with superior lategame scaling, the overall theory was nearly flawless for the game version.
As 2009 would show, the normal progression for such a lineup is three farmed heroes at 30-35 minutes pushing down the base like a set of relentless waves until the pressure forces the other team to buckle. However, even though the lineup scales brilliantly, it can be stalled, should the midgame plan fail to pan out. The standardized lineup involved a core to control midgame tempo, a core to be the frontline tank, and a core to carry the world, along with a pure support and a teamfight support. In the famous game below, #1 - #5 would be SF, Razor, PL, CM, and ES.
SMM 2009
SMM 2009 ft. FTD
Gx (5), 2009 (2)(C), ZSMJ (1), Benz(Sharingan) (4), KingJ (3)
note: the 1-5 denotes the player's respective positions, with (C) denoting the captain
"自己菜=。=那场要是3800没被打掉的话我们可能早就输了"
"We were noob =。= if we didn't kill the relic we would have lost that game before long." - Chuan
The culmination of this would come at SMM 2009 during the end of the year. The most famous game would be between KingSurf and FTD, the legendary “we can give you 3800 gold and still win” showdown. It was here that the seven-minute relic was born. The tournament would be the first to showcase Chinese DotA to the world. Three western teams had been quickly eliminated, and could only watch from the sidelines as the Chinese went head to head in the finals.
"In the year 2009, the tournament that changed the way the world played DotA – SMM, CD, EHome, FTD, three teams together raising the Chinese flag occupying all three slots of the podium." - 2009
With EHome’s victory in SMM 2008, Chinese DotA took the first step onto the world stage. Having been prevented from going to ESWC 2008 by visa issues, SMM’s clashes of the finest teams SEA had to offer drew less attention than a foray to Europe likely would have, but it certainly made legends like Loda pay attention. Perhaps the first glimpse of a distinct Chinese style came when a team obtained some “secret Chinese replays” with the first trademark Chinese hero – Bristleback. In fact, the hero began to make a splash in China when it became heavily nerfed, the first of many testaments to the strength and understanding of Chinese DotA.The scene developed with a style that was an amalgamation of Western and SEA styles, spiced with Chinese elements. EHome and KS.cn, the two strongest teams at the start of the era, both ran highly aggressive styles. EHome’s play often centered around gank and push, while KS.cn favored a push/teamfight composition. Ironically, in those early days, BurNIng was known as the best Chen in China, while LongDD (the best carry in China during his time on KS.cn) played first position for EHome and was famed for his farming ability. That their reputations would be flipped years later should come as no surprise to fans of Chinese DotA.The establishment of For The Dream in August, and the release of 6.64 in October, would set the stage for the rise of China. Importing the nascent SEA style of running three lanes, FTD would hone that lineup to perfection and come to own the era.The three core meta is perhaps the first famous Chinese Style. Its workings come from an early understanding of lanes and of pressure. Fundamentally, it relied upon the use of 3 carries or semi-carries that were difficult to gank, and could clear waves quickly and scale very effectively into the lategame.Its use and effectiveness can be summed up by this simple paradigm: if it takes three enemy heroes to gank one of your cores, the lane pressure and farm accumulated in the other two lanes will more than offset the benefit of the gank. With this consistent economic and creepwave advantage, combined with superior lategame scaling, the overall theory was nearly flawless for the game version.As 2009 would show, the normal progression for such a lineup is three farmed heroes at 30-35 minutes pushing down the base like a set of relentless waves until the pressure forces the other team to buckle. However, even though the lineup scales brilliantly, it can be stalled, should the midgame plan fail to pan out. The standardized lineup involved a core to control midgame tempo, a core to be the frontline tank, and a core to carry the world, along with a pure support and a teamfight support. In the famous game below, #1 - #5 would be SF, Razor, PL, CM, and ES.SMM 2009 ft. FTDGx (5), 2009 (2)(C), ZSMJ (1), Benz(Sharingan) (4), KingJ (3)"自己菜=。=那场要是3800没被打掉的话我们可能早就输了""We were noob =。= if we didn't kill the relic we would have lost that game before long." - ChuanThe culmination of this would come at SMM 2009 during the end of the year. The most famous game would be between KingSurf and FTD, the legendary “we can give you 3800 gold and still win” showdown. It was here that the seven-minute relic was born. The tournament would be the first to showcase Chinese DotA to the world. Three western teams had been quickly eliminated, and could only watch from the sidelines as the Chinese went head to head in the finals."In the year 2009, the tournament that changed the way the world played DotA – SMM, CD, EHome, FTD, three teams together raising the Chinese flag occupying all three slots of the podium." - 2009
2010 - 独霸天下
Dominion over Heaven and Earth The Romance of the Three Kingdoms
The three core style would, for a time, dominate the scene, as FTD gained the sponsorship of LGD to emerge as the most enduring franchise in the Chinese DotA Scene. EHome's persistent use of the old gank->push style proved ineffective in the face of the consistency and adaptability of the lumbering Juggernaut. It would be the change of seasons that led to another evolution. With the nerf of Vanguard and the ever-increasing standard of player laning ability, the tempo of DotA sped up once again, and the top Chinese teams would soon have to wrangle with the new meta, filled with aggressive ganks and the first advent of tactics like dual roam and trilane carry that are standard today.
爹妈大战 - Paternal Strife (LGD vs EHome)
Towards the middle of 2010, Chinese DotA began to shift again. While aggression had been the hallmark of the last era, with relentless pushing and aggressive lineups as the golden standard of competitive play, the new meta first focused on securing an advantage via midgame clashes, and then using it to push yourselves to victory late game. Two teams, LGD and EHome, would emerge as the strongest teams of the age, and their legendary clashes would shape the way the game itself was seen. DotA was played in ways never before seen, and the hidden elements of the game were revealed along the path to perfection that these two teams followed. Over time, their aggression was tempered, their pushing became reserved; the hot-blooded ganking and relentless pushing lineups of the age would fade in favor of the turtle, where simply stalling could lead to victory.
The following video, translated by the author, is a brilliant highlight of the shift in action. LGD and EHome would face off countless times this year, but this pair of games brilliantly summed up the tipping point between push and turtle.
ESWC 2010
ESWC 2010 ft. EHome
357/QQQ (4), BurNIng (1), 820 (5)(C), KingJ (3), Dai/X!!/MMY (2)
ESWC 2010 ft. EHome357/QQQ (4), BurNIng (1), 820 (5)(C), KingJ (3), Dai/X!!/MMY (2)
ESWC 2010 was a watershed moment, for it was the absolute zenith of Chinese DotA. The majesty of the strongest team in the world playing a version that it had fully mastered using mechanics and a meta that was significantly superior to those of its hapless opponents revealed a scene of absolute dominion. Despite picking an extreme late game carry like Medusa or Morphling in almost every game, EHome managed to average less than 35 minutes a game as it crushed all opposition in its near-flawess run. Over the entire course of the tournament, EHome played from behind for only around eight minutes.
A tribute to a bygone team of a bygone era, masters of the world in their time. A tribute to a bygone team of a bygone era, masters of the world in their time.
四保一 - Four Protect One
No rush 40min pl0x
The Lords of Turtle
Where Midgame?
The Vassals of Turtle
No farm, no exp, all antipush The Kings of TurtleThe Lords of TurtleThe Vassals of Turtle
The development of the trilane and the emergence of freefarming carries, combined with the emphasis on stalling and lategame oriented play, led quickly to the absolute 4-1 strategy. This would be Chinese DotA at both its most precise and at its most absurd. If both sides ran solid trilanes that were unassailable and warded mid correctly, then the first 20 minutes of each game might as well just be skipped as top-tier Chinese mids fought each other to more or less a draw and both carries got freefarm, while the supports afk-pulled.
A guaranteed progression into midgame with a pair of extremely well-farmed carries and underfarmed supports only led to more farming, since, as LGD vs EHome had already proven, the only way to win was to get so farmed you could 5v10. As such, why even bother fighting when everything would be decided by farm?
With heroes like Spectre, Alchemist, Medusa, and Morphling, the 4-1 offered ridiculous amounts of physical DPS on the back of nigh-invincible carries that could wipe out the enemy back line in an instant. This in turn would lead to buybacks and stalemates as the winning team was usually forced to retreat, allowing the losing team to farm for even more buybacks.
Finally, a single game took this concept to its logical extreme. In this match, EHome was able to completely dominate the early game and ended up controlling the map against LGD. Yet, the lesson of the era was that turtling could win games, with multiple games reversed by ZSMJ's Medusa turtling to save the world with a maxed out inventory. EHome simply controlled the map and maxed out three heroes before even attempting to go onto LGD's high ground. At 75 minutes, there were five rapiers on the map, and the score was 7:8. EHome's execution was indeed masterful, using mobile semi-cores to control the map and slowly building up the advantage necessary to take LGD's high ground by storm. However, as every exhausted commentator, player, and viewer would express, the trend had reached its inevitable conclusion, and it blew. This was not the DotA we wanted.
The Chinese version of the cast is below, should one wish to relive the true nature of the brief period of Chinese "farming" meta (warning: do not watch unless you are willing to die of boredom)
WDC 2010
WDC 2010 ft. Nv.cn (and DTS)
Zhou (1)(C), DGC (4), Yaphets (2), Insense (5), Banana (3) WDC 2010 ft. Nv.cn (and DTS)Zhou (1)(C), DGC (4), Yaphets (2), Insense (5), Banana (3)
With 6.69c released and the community becoming increasingly disdainful of the way the LGD and EHome rivalry concluded, WDC was a surprising breath of fresh air that swept across the dreary battlefield that was Chinese DotA. A single match would bring new life to an ancient way of war and help usher in an era vastly different to the one it followed.
It would be DTS, the forerunner of Na`Vi, that would bring a pushing lineup back into the spotlight. The pushing cores of Lone Druid (Syllabear) and Panda would do surprisingly well against EHome, the undisputed master of the late game 4-1, and Enchantress would plunge a dagger into the pride of Chinese DotA in these matches. DTS ended with a respectable third place in the tournament after performing one of the biggest upsets in history.
The bloodletting would, however, lead to a renewal; Nirvana.cn would quickly showcase exactly what a prepared team could do against a pushing lineup. Sadly, the rivalry and earth-shattering duels between EHome and LGD obscured the strength of the third member of the triumvirate – Nirvana.cn. The team, anchored by Zhou and Yaphets, continued to play a dual core strategy that ran contrary to the extreme lategame of LGD and EHome and finally saw their ingenuity in the midgame rewarded in the tournament.
The lesson had been learned. The potential of Lone Druid had been discovered and would eventually be perfected as an integral part of modern Chinese DotA. The curtain had set on the "farming" era of the Chinese metagame. There was no question, however, that the lessons learned during this period of high economy play would give the Chinese teams an undisputed edge in any late game situation.
The three core style would, for a time, dominate the scene, as FTD gained the sponsorship of LGD to emerge as the most enduring franchise in the Chinese DotA Scene. EHome's persistent use of the old gank->push style proved ineffective in the face of the consistency and adaptability of the lumbering Juggernaut. It would be the change of seasons that led to another evolution. With the nerf of Vanguard and the ever-increasing standard of player laning ability, the tempo of DotA sped up once again, and the top Chinese teams would soon have to wrangle with the new meta, filled with aggressive ganks and the first advent of tactics like dual roam and trilane carry that are standard today.Towards the middle of 2010, Chinese DotA began to shift again. While aggression had been the hallmark of the last era, with relentless pushing and aggressive lineups as the golden standard of competitive play, the new meta first focused on securing an advantage via midgame clashes, and then using it to push yourselves to victory late game. Two teams, LGD and EHome, would emerge as the strongest teams of the age, and their legendary clashes would shape the way the game itself was seen. DotA was played in ways never before seen, and the hidden elements of the game were revealed along the path to perfection that these two teams followed. Over time, their aggression was tempered, their pushing became reserved; the hot-blooded ganking and relentless pushing lineups of the age would fade in favor of the turtle, where simply stalling could lead to victory.The following video, translated by the author, is a brilliant highlight of the shift in action. LGD and EHome would face off countless times this year, but this pair of games brilliantly summed up the tipping point between push and turtle.ESWC 2010 was a watershed moment, for it was the absolute zenith of Chinese DotA. The majesty of the strongest team in the world playing a version that it had fully mastered using mechanics and a meta that was significantly superior to those of its hapless opponents revealed a scene of absolute dominion. Despite picking an extreme late game carry like Medusa or Morphling in almost every game, EHome managed to average less than 35 minutes a game as it crushed all opposition in its near-flawess run. Over the entire course of the tournament, EHome played from behind for only around eight minutes.The development of the trilane and the emergence of freefarming carries, combined with the emphasis on stalling and lategame oriented play, led quickly to the absolute 4-1 strategy. This would be Chinese DotA at both its most precise and at its most absurd. If both sides ran solid trilanes that were unassailable and warded mid correctly, then the first 20 minutes of each game might as well just be skipped as top-tier Chinese mids fought each other to more or less a draw and both carries got freefarm, while the supports afk-pulled.A guaranteed progression into midgame with a pair of extremely well-farmed carries and underfarmed supports only led to more farming, since, as LGD vs EHome had already proven, the only way to win was to get so farmed you could 5v10. As such, why even bother fighting when everything would be decided by farm?With heroes like Spectre, Alchemist, Medusa, and Morphling, the 4-1 offered ridiculous amounts of physical DPS on the back of nigh-invincible carries that could wipe out the enemy back line in an instant. This in turn would lead to buybacks and stalemates as the winning team was usually forced to retreat, allowing the losing team to farm for even more buybacks.Finally, a single game took this concept to its logical extreme. In this match, EHome was able to completely dominate the early game and ended up controlling the map against LGD. Yet, the lesson of the era was that turtling could win games, with multiple games reversed by ZSMJ's Medusa turtling to save the world with a maxed out inventory. EHome simply controlled the map and maxed out three heroes before even attempting to go onto LGD's high ground. At 75 minutes, there were five rapiers on the map, and the score was 7:8. EHome's execution was indeed masterful, using mobile semi-cores to control the map and slowly building up the advantage necessary to take LGD's high ground by storm. However, as every exhausted commentator, player, and viewer would express, the trend had reached its inevitable conclusion, and it blew. This was not the DotA we wanted.The Chinese version of the cast is below, should one wish to relive the true nature of the brief period of Chinese "farming" meta (warning: do not watch unless you are willing to die of boredom)With 6.69c released and the community becoming increasingly disdainful of the way the LGD and EHome rivalry concluded, WDC was a surprising breath of fresh air that swept across the dreary battlefield that was Chinese DotA. A single match would bring new life to an ancient way of war and help usher in an era vastly different to the one it followed.It would be DTS, the forerunner of Na`Vi, that would bring a pushing lineup back into the spotlight. The pushing cores of Lone Druid (Syllabear) and Panda would do surprisingly well against EHome, the undisputed master of the late game 4-1, and Enchantress would plunge a dagger into the pride of Chinese DotA in these matches. DTS ended with a respectable third place in the tournament after performing one of the biggest upsets in history.The bloodletting would, however, lead to a renewal; Nirvana.cn would quickly showcase exactly what a prepared team could do against a pushing lineup. Sadly, the rivalry and earth-shattering duels between EHome and LGD obscured the strength of the third member of the triumvirate – Nirvana.cn. The team, anchored by Zhou and Yaphets, continued to play a dual core strategy that ran contrary to the extreme lategame of LGD and EHome and finally saw their ingenuity in the midgame rewarded in the tournament.The lesson had been learned. The potential of Lone Druid had been discovered and would eventually be perfected as an integral part of modern Chinese DotA. The curtain had set on the "farming" era of the Chinese metagame. There was no question, however, that the lessons learned during this period of high economy play would give the Chinese teams an undisputed edge in any late game situation.
2011 - 分久必合,合久必分
That which is long divided shall unite;
That which is long united shall divide.
The New Chinese DotA
Sundering of the Triumvirates
Following a year of stability and a constant elevation in the level of DotA, the Chinese scene would be caught by an earthquake. The old empires of EHome, LGD, and Nirvana.cn would all undergo drastic changes, while the arrival of new powerhouses like DK, CCM, and Tyloo would muddy the waters and shatter the conventions of DotA that had been built up over the year prior.
冲脸 - FaceRush
The first facerush was a reactionary style that responded to the massive onus that the 4-1 placed on late game hard carries. Its existence was made possible by main two factors. One was the development and usage of heroes that could play well against trilanes. The second, of course, was midgame teamfight carries that could not only overpower hard carries mid game, but could also scale well enough to be viable late game against traditional hard carries. Heroes who mature quickly, push effectively, as well as able to go toe to toe against late game carries with the advantage acquired during the midgame.
1v3? EZ
20 Min Rax?!
Push, Kill, Carry Masters of the Lanes20 Min Rax?!
The TP and buyback changes were also an important factor in these meta changes. With the increase in cost and the existence of cooldowns for these spells, turtling with TPs and BB was no longer a surefire ticket to buy more time and usher in the endgame needed by the late game carries.
The prospect of not always getting guaranteed freefarm, combined with possible midgame disaster, the extreme lategame 4-1 style that had come to exemplify Chinese DotA quickly went out of vogue. Games once again involved head-on teamfights that sundered the earth, as though the reserve shown in earlier months had been a dam waiting to burst. DotA once again became a hot-blooded affair, typified by the arrival of Seaking and Hao, a pair of new-kid-on-the-block carries whose hallmark would be midgame devastation.
ECL 2011
CCM 2011
DDC (5), 430 (3), Xiao8 (2), SanSheng (4), Zhou (1)(C) CCM 2011DDC (5), 430 (3), Xiao8 (2), SanSheng (4), Zhou (1)(C)
Taking place during the most early-game oriented meta in history, ECL was a world where Lone Druid, a core that had been used as part of all-in pushing lineups just months before was now a late-game carry. Few games of this era would take longer than 25 minutes before the first attempt on a rax.
Here the midgame would be dominant, with momentum and teamfights deciding it all. Each game was perhaps still a race against the clock as more late-game oriented lineups attempted to hold off faster-paced invaders. To the stark contrast to the games just months ago, however, the pushing side won more often than not; and the average game length was 35 instead of 65 minutes.
The finals would feature LGD against CCM in a flurry of action and non-stop teamfights. The slow waltz bad become a blitz.
Highlights of games 1 and 2
Highlights of games 1 and 2
(vods for game 3 unavailable for some reason)
To be continued in Part 2!
迷茫 - At a Loss
The Chinese at TI1
Special thanks to shiroiusagi, riptide, SirJolt, TheEmulator, CountChocula, TanGeng, and the rest of the TL Dota staff/editors, as well as BTS for helping popularize Chinese Dota 2 in the west, and Felix for the help from his past articles.
References
http://www.gosugamers.net/general/thread.php?id=575118
-CCM
http://dota.sgamer.com/201107/news-detail-93953.html
-Innovations (post 2011)
http://dota.sgamer.com/201211/news-detail-156102.html
-On the Demise of Morph + Spec
http://bbs.sgamer.com/forum.php?mod=viewthread&tid=10022108&extra=page%3D1%26filter%3Ddigest%26digest%3D1%26digest%3D1
-Chronicle of Chinese DotA
http://bbs.sgamer.com/forum.php?mod=viewthread&tid=10127616&extra=page%3D1%26filter%3Ddigest%26digest%3D1%26digest%3D1
-6.48-.71
http://dota.sgamer.com/201103/news-detail-80790_page=6.html
Chinese Dota 2010
http://bbs.sgamer.com/thread-10208355-1-1.html Loda interview-CCM-Innovations (post 2011)-On the Demise of Morph + Spec-Chronicle of Chinese DotA-6.48-.71Chinese Dota 2010
Following a year of stability and a constant elevation in the level of DotA, the Chinese scene would be caught by an earthquake. The old empires of EHome, LGD, and Nirvana.cn would all undergo drastic changes, while the arrival of new powerhouses like DK, CCM, and Tyloo would muddy the waters and shatter the conventions of DotA that had been built up over the year prior.The first facerush was a reactionary style that responded to the massive onus that the 4-1 placed on late game hard carries. Its existence was made possible by main two factors. One was the development and usage of heroes that could play well against trilanes. The second, of course, was midgame teamfight carries that could not only overpower hard carries mid game, but could also scale well enough to be viable late game against traditional hard carries. Heroes who mature quickly, push effectively, as well as able to go toe to toe against late game carries with the advantage acquired during the midgame.The TP and buyback changes were also an important factor in these meta changes. With the increase in cost and the existence of cooldowns for these spells, turtling with TPs and BB was no longer a surefire ticket to buy more time and usher in the endgame needed by the late game carries.The prospect of not always getting guaranteed freefarm, combined with possible midgame disaster, the extreme lategame 4-1 style that had come to exemplify Chinese DotA quickly went out of vogue. Games once again involved head-on teamfights that sundered the earth, as though the reserve shown in earlier months had been a dam waiting to burst. DotA once again became a hot-blooded affair, typified by the arrival of Seaking and Hao, a pair of new-kid-on-the-block carries whose hallmark would be midgame devastation.Taking place during the most early-game oriented meta in history, ECL was a world where Lone Druid, a core that had been used as part of all-in pushing lineups just months before was now a late-game carry. Few games of this era would take longer than 25 minutes before the first attempt on a rax.Here the midgame would be dominant, with momentum and teamfights deciding it all. Each game was perhaps still a race against the clock as more late-game oriented lineups attempted to hold off faster-paced invaders. To the stark contrast to the games just months ago, however, the pushing side won more often than not; and the average game length was 35 instead of 65 minutes.The finals would feature LGD against CCM in a flurry of action and non-stop teamfights. The slow waltz bad become a blitz.(vods for game 3 unavailable for some reason)迷茫 - At a LossThe Chinese at TI1Special thanks to shiroiusagi, riptide, SirJolt, TheEmulator, CountChocula, TanGeng, and the rest of the TL Dota staff/editors, as well as BTS for helping popularize Chinese Dota 2 in the west, and Felix for the help from his past articles.
When in doubt, just believe in yourself and press buttons
|
export { default as breakpoints } from "./breakpoints";
export { default as getImageId } from "./getImageId";
export { default as getVideoId } from "./getVideoId";
export { default as getVideoImage } from "./getVideoImage";
export { default as isVideoValid } from "./isVideoValid";
export { default as isTicketValid } from "./isTicketValid";
export { default as isEventValid } from "./isEventValid";
export { default as shuffleArray } from "./shuffleArray";
export { default as getTintedBackground } from "./getTintedBackground";
export { default as formatLanguage } from "./formatLanguage";
export { default as verifyEmail } from "./verifyEmail";
export { default as recursivelyFormatDate } from "./recursivelyFormatDate";
// Hooks:
export { default as useBreakpoint } from "./useBreakpoint";
export { default as useCloudinary } from "./useCloudinary";
export { default as useCourseFeed } from "./useCourseFeed";
export { default as useEventFeed } from "./useEventFeed";
export { default as usePostFeed } from "./usePostFeed";
export { default as useGeneralSettings } from "./useGeneralSettings";
export { default as usePostImage } from "./usePostImage";
export { default as useContactInfo } from "./useContactInfo";
export { default as useNavigation } from "./useNavigation";
export { default as usePayPalButtons } from "./usePayPalButtons";
export { default as useSiteMetadata } from "./useSiteMetadata";
export { default as youtubeRegex } from "./youtubeRegex";
|
import React from 'react';
import { expect } from 'chai';
import { FormattedMessage, IntlShape } from 'react-intl';
import sinon from 'sinon';
import behandlingType from 'kodeverk/behandlingType';
import behandlingStatus from 'kodeverk/behandlingStatus';
import fagsakYtelseType from 'kodeverk/fagsakYtelseType';
import DateLabel from 'sharedComponents/DateLabel';
import TableRow from 'sharedComponents/TableRow';
import TableColumn from 'sharedComponents/TableColumn';
import { K9LosApiKeys, RestApiGlobalStatePathsKeys } from 'api/k9LosApi';
import { Oppgaveko } from 'saksbehandler/behandlingskoer/oppgavekoTsType';
import { intlMock, shallowWithIntl } from '../../../../../../../setup/testHelpers/intl-enzyme-test-helper';
import RestApiTestMocker from '../../../../../../../setup/testHelpers/RestApiTestMocker';
import { OppgaverTabell } from './OppgaverTabell';
import kodeverk from "../../../../../mocks/kodeverk";
describe('<OppgaverTabell>', () => {
const intl: Partial<IntlShape> = {
...intlMock,
};
const valgtKo: Oppgaveko = {
id: '2',
navn: 'K9',
behandlingTyper: [],
fagsakYtelseTyper: [],
andreKriterier: [],
skjermet: false,
};
const oppgaverTilBehandling = [{
eksternId: '1',
status: {
erReservert: false,
},
saksnummer: '1',
behandlingId: 2,
journalpostId: null,
personnummer: '123456789',
navn: '<NAME>',
system: 'K9SAK',
behandlingstype: behandlingType.FORSTEGANGSSOKNAD,
opprettetTidspunkt: '2019-01-02',
behandlingsfrist: '2019-03-03',
erTilSaksbehandling: true,
fagsakYtelseType: fagsakYtelseType.OMSORGSPENGER,
behandlingStatus: behandlingStatus.OPPRETTET,
}, {
eksternId: '2',
status: {
erReservert: false,
},
saksnummer: '2',
behandlingId: 2,
journalpostId: null,
personnummer: '657643535',
navn: '<NAME>',
system: 'FPSAK',
behandlingstype: behandlingType.FORSTEGANGSSOKNAD,
opprettetTidspunkt: '2018-01-02',
behandlingsfrist: '2018-03-03',
erTilSaksbehandling: true,
fagsakYtelseType:fagsakYtelseType.OMSORGSPENGER,
behandlingStatus: behandlingStatus.OPPRETTET,
}];
it('skal vise kriterievelger og liste over neste oppgaver', () => {
new RestApiTestMocker()
.withRestCallRunner(K9LosApiKeys.LEGG_TIL_BEHANDLET_OPPGAVE, { startRequest: () => undefined, data: undefined })
.withRestCallRunner(K9LosApiKeys.OPPGAVEKO, { startRequest: () => undefined, data: undefined })
.withGlobalData(RestApiGlobalStatePathsKeys.KODEVERK, kodeverk)
.runTest(() => {
const wrapper = shallowWithIntl(<OppgaverTabell
intl={intl}
valgtKo={valgtKo}
reserverOppgave={sinon.spy()}
valgtOppgavekoId="1"
oppgaverTilBehandling={oppgaverTilBehandling}
requestFinished
/>);
const tableRows = wrapper.find(TableRow);
expect(tableRows).has.length(2);
const columnsRow1 = tableRows.first().find(TableColumn);
expect(columnsRow1.first().childAt(0).text()).is.eql('Espen Utvikler 123456789');
expect(columnsRow1.at(1).childAt(0).text()).is.eql('1');
expect(columnsRow1.at(2).childAt(0).text()).is.eql('Førstegangsbehandling');
expect(columnsRow1.at(3).find(DateLabel).prop('dateString')).is.eql('2019-01-02');
const columnsRow2 = tableRows.last().find(TableColumn);
expect(columnsRow2.first().childAt(0).text()).is.eql('Espen Solstråle 657643535');
expect(columnsRow2.at(1).childAt(0).text()).is.eql('2');
expect(columnsRow2.at(2).childAt(0).text()).is.eql('Førstegangsbehandling');
expect(columnsRow2.at(3).find(DateLabel).prop('dateString')).is.eql('2018-01-02');
});
});
it('skal ikke vise liste når en ikke har oppgaver', () => {
new RestApiTestMocker()
.withRestCallRunner(K9LosApiKeys.LEGG_TIL_BEHANDLET_OPPGAVE, { startRequest: () => undefined, data: undefined })
.withRestCallRunner(K9LosApiKeys.OPPGAVEKO, { startRequest: () => undefined, data: undefined })
.withGlobalData(RestApiGlobalStatePathsKeys.KODEVERK, kodeverk)
.runTest(() => {
const wrapper = shallowWithIntl(<OppgaverTabell
intl={intl}
valgtKo={valgtKo}
reserverOppgave={sinon.spy()}
valgtOppgavekoId="1"
oppgaverTilBehandling={[]}
requestFinished
/>);
const message = wrapper.find(FormattedMessage);
expect(message).has.length(1);
expect(message.last().prop('id')).is.eql('OppgaverTabell.IngenOppgaver');
expect(wrapper.find(TableRow)).has.length(0);
});
});
});
|
package auth
import "gopkg.in/square/go-jose.v2/jwt"
type Claims struct {
jwt.Claims
Scope string `json:"scope,omitempty"`
PreferredUsername string `json:"preferred_username,omitempty"`
RealmAccess realmAccess `json:"realm_access,omitempty"`
ResourceAccess resourceAccess `json:"resource_access,omitempty"`
}
type realmAccess struct {
Roles []string `json:"roles,omitempty"`
}
type resourceAccess struct {
Account account `json:"account,omitempty"`
}
type account struct {
Roles []string `json:"roles,omitempty"`
}
|
// Find the n adjacent digits that have the greatest product.
pub mod p008 {
use crate::useful_func::digits::num_to_digits;
use crate::useful_func::other_func::get_substring;
use std::cmp::max;
pub fn v1(win_size: usize, num_string: &str) -> u32 {
let mut max_prod: u32 = 0;
let n = num_string.len() - win_size;
for i in 0..n {
let win_string = get_substring(&num_string, i, win_size)
.parse::<u32>()
.unwrap();
let prod = num_to_digits(win_string).iter().product();
max_prod = max(prod, max_prod);
}
max_prod
}
}
|
// EduPeriod.java
/*
* Copyright (c) 2008, Gennady & <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* • Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* • Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* • Neither the name of the RUJEL nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.rujel.eduplan;
import net.rujel.reusables.*;
import net.rujel.interfaces.*;
import net.rujel.base.MyUtility;
import net.rujel.base.SettingsBase;
import com.webobjects.foundation.*;
import com.webobjects.eocontrol.*;
import com.webobjects.appserver.WOContext;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import com.webobjects.eoaccess.EOUtilities;
public class EduPeriod extends _EduPeriod implements EOPeriod
{
public static final NSArray sorter = new NSArray(
EOSortOrdering.sortOrderingWithKey("begin",EOSortOrdering.CompareAscending));
public EduPeriod() {
super();
}
/*
// If you add instance variables to store property values you
// should add empty implementions of the Serialization methods
// to avoid unnecessary overhead (the properties will be
// serialized for you in the superclass).
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
}
*/
public boolean contains(Date date) {
return EOPeriod.Utility.contains(this, date);
}
public static NSArray sortedPeriods(EOEditingContext ec, String listName) {
EOQualifier qual = new EOKeyValueQualifier(LIST_NAME_KEY,
EOQualifier.QualifierOperatorEqual,listName);
EOFetchSpecification fs = new EOFetchSpecification(ENTITY_NAME, qual, sorter);
return ec.objectsWithFetchSpecification(fs);
}
public static EduPeriod[] fetchPeriods(EOEditingContext ec, String listName) {
NSArray found = EOUtilities.objectsMatchingKeyAndValue(ec,
EduPeriod.ENTITY_NAME, EduPeriod.LIST_NAME_KEY, listName);
return arrangePeriods(found);
}
private static EduPeriod[] arrangePeriods(NSArray found) {
if (found == null || found.count() == 0)
return null;
EduPeriod[] periods = new EduPeriod[found.count() +1];
Enumeration enu = found.objectEnumerator();
while (enu.hasMoreElements()) {
EduPeriod per = (EduPeriod) enu.nextElement();
EOEnterpriseObject itog = per.relatedItog();
if(itog == null) {
periods[0]=per;
} else {
Integer num = (Integer)itog.valueForKey("num");
if(num >= periods.length) { //make larger array
EduPeriod[] prev = periods;
periods = new EduPeriod[num+1];
for (int i = 0; i < prev.length; i++) {
if(prev[i] != null) {
periods[i]=prev[i];
}
}
}
periods[num.intValue()]=per;
}
}
EduPeriod next=periods[0];
if(next == null) {
next = (EduPeriod)found.objectAtIndex(0);
EduPlan.logger.log(WOLogLevel.WARNING, "No end EduPeriod found for listName "
+ next.listName(),next.valueForKeyPath("relatedItog.itogType"));
return periods;
}
next._next=next;
next._perlist=periods;
for (int i = periods.length-1; i > 0 ; i--) {
if(periods[i]!=null) {
periods[i]._next=next;
periods[i]._perlist=periods;
next = periods[i];
}
}
return periods;
}
public static NSArray periodsInList(String listName,EOEditingContext ec) {
return periodsInList(listName, ec, true);
}
public static NSArray periodsInList(String listName,EOEditingContext ec, boolean noEnd) {
if(listName == null)
return null;
NSArray found = EOUtilities.objectsMatchingKeyAndValue(ec,
EduPeriod.ENTITY_NAME, EduPeriod.LIST_NAME_KEY, listName);
if(found == null || found.count() == 0)
return null;
EduPeriod tmp = (EduPeriod)found.objectAtIndex(0);
EduPeriod[] periods = tmp._perlist;
if (periods == null)
periods = arrangePeriods(found);
if(noEnd) {
tmp = periods[0];
periods[0] = null;
NSArray result = new NSArray(periods);
periods[0]=tmp;
return result;
} else {
return new NSArray(periods);
}
}
public static NSArray defaultPeriods(EOEditingContext ec) {
String listName = SettingsBase.stringSettingForCourse(ENTITY_NAME, null, ec);
return periodsInList(listName, ec);
}
public static NSArray periodsForCourse(EduCourse course) {
EOEditingContext ec = course.editingContext();
String listName = SettingsBase.stringSettingForCourse(ENTITY_NAME, course, ec);
NSArray list = periodsInList(listName, ec);
if(list == null || list.count() == 0)
list = defaultPeriods(ec);
return list;
}
public static final NSArray<EOSortOrdering> grouper = new NSArray(new EOSortOrdering[]{
new EOSortOrdering(LIST_NAME_KEY, EOSortOrdering.CompareAscending),
new EOSortOrdering(BEGIN_KEY, EOSortOrdering.CompareAscending)});
public static NSArray periods(WOContext ctx) {
// Integer eduYear = (Integer)ctx.session().valueForKey("eduYear");
EOEditingContext ec = null;
Object showFor = null;
if(ctx.component().canGetValueForBinding("showFor"))
showFor = ctx.component().valueForBinding("showFor");
if(showFor == null && ctx.hasSession())
showFor = ctx.session().valueForKeyPath("state.section");
try {
if(ctx.component().canGetValueForBinding("ec"))
ec = (EOEditingContext)ctx.component().valueForBinding("ec");
if(ec==null)
ec = (EOEditingContext)ctx.page().valueForKey("ec");
if(showFor instanceof EOEnterpriseObject) {
if(ec==null)
ec = ((EOEnterpriseObject)showFor).editingContext();
else
showFor=EOUtilities.localInstanceOfObject(ec, (EOEnterpriseObject)showFor);
}
} catch (Exception e) {
;
}
if(ec == null) {
ec = (EOEditingContext)ctx.session().defaultEditingContext();
}
Integer eduYear;
if(ctx.hasSession())
eduYear = (Integer)ctx.session().valueForKey("eduYear");
else
eduYear = MyUtility.eduYear(ec);
NSKeyValueCodingAdditions course = SettingsBase.courseDict(showFor, eduYear);
String listName = SettingsBase.stringSettingForCourse(ENTITY_NAME, course, ec);
NSArray result = periodsInList(listName, ec, true);
if(result == null || result.count() == 0)
result = defaultPeriods(ec);
return result;
}
public static EduPeriod getCurrentPeriod(NSTimestamp date, String listName,
EOEditingContext ec) {
NSArray periods = periodsInList(listName, ec);
Enumeration enu = periods.objectEnumerator();
while (enu.hasMoreElements()) {
EduPeriod per = (EduPeriod) enu.nextElement();
if (per.contains(date))
return per;
}
return null;
}
public EOEnterpriseObject relatedItog() {
return (EOEnterpriseObject)storedValueForKey("relatedItog");
}
public String name() {
return (String)valueForKeyPath("relatedItog.name");
}
public String title() {
return (String)valueForKeyPath("relatedItog.title");
}
public Number sort() {
return new Integer(code());
}
public int code() {
Calendar cal = Calendar.getInstance();
cal.setTime(begin());
int result = cal.get(Calendar.YEAR);
result -= 2000;
result = result*10000;
result += cal.get(Calendar.MONTH)*100;
result += cal.get(Calendar.DAY_OF_MONTH);
result = (result+1)*1000;
result -= EOPeriod.Utility.countDays(begin(), end());
return result;
}
/*
public String presentEduYear() {
if(eduYear() == null)
return null;
int year = eduYear().intValue();
return MyUtility.presentEduYear(year);
}*/
public int daysInPeriod(NSTimestamp toDate) {
NSTimestamp begin = begin();
NSTimestamp end = end();
if(toDate != null){
if(toDate.compare(begin) < 0)
return 0;
if(toDate.compare(end) < 0)
end = toDate;
}
int days = EOPeriod.Utility.countDays(begin, end);
days -= Holiday.freeDaysInDates(begin, end, editingContext(), listName());
return days;
}
public static int activeDaysInDates(NSTimestamp begin, NSTimestamp end, String listName, EOEditingContext ec) {
NSArray periods = sortedPeriods(ec, listName);
NSArray holidays = Holiday.holidaysInDates(begin, end, ec, listName);
if(periods == null || periods.count() == 0) {
String tmpListName = SettingsBase.stringSettingForCourse(ENTITY_NAME, null, ec);
periods = sortedPeriods(ec, tmpListName);
}
if(periods == null || periods.count() == 0)
return 0;
EduPeriod first = (EduPeriod)periods.objectAtIndex(0);
EduPeriod last = (EduPeriod)periods.lastObject();
NSTimestamp perlast = last.begin().timestampByAddingGregorianUnits(0, 0, -1, 0, 0, 0);
if(begin == null || begin.before(first.begin()))
begin = first.begin();
if(end == null || end.after(perlast))
end = perlast;
return EOPeriod.Utility.countDays(begin, end)
- Holiday.freeDaysInDates(begin, end, holidays);
}
/* public int[] weeksAndDays(NSTimestamp toDate, EduCourse course) {
EOEditingContext ec = editingContext();
String listName = SettingsBase.stringSettingForCourse(ENTITY_NAME, course, ec);
int days = daysInPeriod(toDate, listName);
int weekDays = SettingsBase.numericSettingForCourse("weekDays", course, ec, 7);
int[] result = new int[2];
result[0] = days/weekDays;
result[1] = days%weekDays;
return result;
}*/
public static int daysForList(String listName, NSTimestamp toDate, EOEditingContext ec) {
NSArray periods = sortedPeriods(ec, listName);
if(periods == null || periods.count() == 0)
periods = defaultPeriods(ec);
if(periods == null || periods.count() == 0)
return 0;
EduPeriod per = (EduPeriod)periods.objectAtIndex(0);
NSTimestamp begin = per.begin();
per = (EduPeriod)periods.lastObject();
NSTimestamp end = per.begin();
int days=-1;
if(toDate != null){
if(toDate.compare(begin) < 0)
return 0;
if(toDate.compare(end) < 0) {
end = toDate;
days =0;
}
}
days += EOPeriod.Utility.countDays(begin, end);
days -= Holiday.freeDaysInDates(begin, end, ec, listName);
return days;
}
public static int dayState(NSTimestamp date, EOEditingContext ec, String listName) {
EduPeriod current = getCurrentPeriod(date, listName, ec);
if(current == null)
return 2;
NSArray list = Holiday.holidaysInDates(date, date, ec, listName);
if(list != null && list.count() > 0)
return 1;
return 0;
}
protected static class PeriodTab implements Tabs.GenericTab {
protected String title;
protected String hover;
protected EOQualifier qual;
protected boolean current;
protected int code;
protected Period per;
public PeriodTab(EduPeriod period, boolean isCurrent) {
title = (String)period.valueForKeyPath("relatedItog.title");
code = period.code();
/* try {
EOKeyGlobalID gid = (EOKeyGlobalID)period.editingContext().
globalIDForObject(period);
Integer key = (Integer)gid.keyValues()[0];
code = key.intValue();
} catch (Exception e) {
code = 0;
}*/
current = isCurrent;
NSMutableArray quals = new NSMutableArray();
quals.addObject(new EOKeyValueQualifier
("date",EOQualifier.QualifierOperatorGreaterThanOrEqualTo,period.begin()));
quals.addObject(new EOKeyValueQualifier
("date",EOQualifier.QualifierOperatorLessThanOrEqualTo,period.end()));
qual = new EOAndQualifier(quals);
hover = period.name();
per = new EOPeriod.ByDates(period.begin(), period.end());
}
public boolean defaultCurrent() {
return current;
}
public String title() {
return title;
}
public String hover() {
return hover;
}
public EOQualifier qualifier() {
return qual;
}
public boolean equals(Object obj) {
if (obj instanceof PeriodTab) {
PeriodTab aTab = (PeriodTab) obj;
return (this.code == aTab.code);
}
return false;
}
public int hashCode() {
return code;
}
public Period period() {
return per;
}
}
public static NSArray lessonTabs(WOContext ctx) {
EduCourse course = (EduCourse)ctx.session().objectForKey("courseForlessons");
NSTimestamp currDate = (NSTimestamp)ctx.session().objectForKey("recentDate");
if(currDate == null) {
EduLesson currLesson = (EduLesson)ctx.session().objectForKey("selectedLesson");
currDate = (currLesson != null)?currLesson.date():
(NSTimestamp)ctx.session().valueForKey("today");
}
NSArray periods = EduPeriod.periodsForCourse(course);
if(periods == null || periods.count() == 0)
return null;
Enumeration enu = periods.objectEnumerator();
NSMutableArray result = new NSMutableArray();
while (enu.hasMoreElements()) {
EduPeriod per = (EduPeriod) enu.nextElement();
boolean isCurrent = per.contains(currDate);
result.addObject(new PeriodTab(per,isCurrent));
}
return new NSArray((Object)result);
}
protected EduPeriod[] _perlist;
protected EduPeriod _next;
public NSArray allInList() {
if(_perlist == null) {
_perlist = fetchPeriods(editingContext(),listName());
}
return new NSArray(_perlist);
}
public EduPeriod next() {
if(_next!=null)
return _next;
if(_perlist != null) {
for (int i = 1; i < _perlist.length-1; i++) {
if(_perlist[i]==this)
_next=_perlist[i+1];
}
if(_next==null)
_next=_perlist[0];
}
if(_next==null)
fetchPeriods(editingContext(), listName());
return _next;
}
public NSTimestamp end() {
return next().begin().timestampByAddingGregorianUnits(0, 0, -1, 0, 0, 0);
}
public static NSTimestamp[] defaultYearDates(int eduYear) {
String start = SettingsReader.stringForKeyPath("edu.yearStart", null);
String end = SettingsReader.stringForKeyPath("edu.yearEnd", null);
Calendar cal = Calendar.getInstance();
NSTimestamp[] result = new NSTimestamp[2];
if(start == null) {
cal.set(Calendar.MONTH, Calendar.SEPTEMBER);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.YEAR, eduYear);
result[0] = new NSTimestamp(cal.getTimeInMillis());
if(end == null) {
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 31);
cal.add(Calendar.YEAR, 1);
result[1] = new NSTimestamp(cal.getTimeInMillis());
return result;
}
}
Format df = new SimpleDateFormat(
SettingsReader.stringForKeyPath("ui.shortDateFormat","MM/dd"));
if(start != null) {
Date aDate = (Date)df.parseObject(start, new java.text.ParsePosition(0));
cal.setTime(aDate);
cal.set(Calendar.YEAR, eduYear);
result[0] = new NSTimestamp(cal.getTimeInMillis());
}
int startDay = cal.get(Calendar.DAY_OF_YEAR);
if(end == null) {
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 31);
} else {
Date aDate = (Date)df.parseObject(start, new java.text.ParsePosition(0));
cal.setTime(aDate);
cal.set(Calendar.YEAR, eduYear);
}
if(cal.get(Calendar.DAY_OF_YEAR) < startDay)
cal.add(Calendar.YEAR, 1);
result[1] = new NSTimestamp(cal.getTimeInMillis());
return result;
}
public void turnIntoFault(EOFaultHandler handler) {
_perlist=null;
_next=null;
super.turnIntoFault(handler);
}
}
|
<filename>pages/custom/[slug].tsx<gh_stars>1-10
import { GetStaticProps, GetStaticPaths } from 'next';
import { ParsedUrlQuery } from 'querystring';
import Link from 'next/link';
const contentPath = {
path1: 'content of path1 to illustrate the mapping',
path2: 'another content here for the second path2',
};
const CustomPageTemplate = ({
slug,
content,
}: {
slug: string;
content: string;
}): JSX.Element => {
return (
<div className="text-center text-gray-700">
<span className="font-extrabold text-4xl">We are in : {slug}</span>
<p className="font-semibold text-3xl">
A dummy content for it : {content}
</p>
<Link href="/" as="/">
<a className="font-semibold text-3xl underline">Take me be back home</a>
</Link>
</div>
);
};
// Define all the possible slug paths
export const getStaticPaths: GetStaticPaths = async () => {
const paths = Object.keys(contentPath).map((path) => '/custom/' + path);
console.log(paths);
return {
paths,
fallback: false,
};
};
// define the content generation for each generated path
export const getStaticProps: GetStaticProps = async ({
params,
}: {
params?: ParsedUrlQuery | undefined;
}) => {
let postData;
switch (params?.slug as string) {
case 'path1':
postData = contentPath.path1;
break;
case 'path2':
postData = contentPath.path2;
break;
default:
console.log('404 page will take it from here');
}
return { props: { slug: `${params?.slug}`, content: postData } };
};
export default CustomPageTemplate;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.