content
stringlengths 7
2.61M
|
---|
export {
resolveArrayIteratorFindMethod
} from './iterate'
export {
testNot,
testOr,
testAnd
} from './boolean-logic'
export {
testNames,
testName
} from './names'
|
<filename>source/application/Components/Questions/Freetext/Freetext.ts
import FreetextBase = require("Components/Questions/Freetext/FreetextBase");
import QuestionModel = require("Models/Question");
type Answer = { Text: string };
class Freetext extends FreetextBase<Answer>
{
constructor(question: QuestionModel)
{
super(question);
}
protected UpdateAnswer(text: string): void
{
this.AddEvent("Change", "Keyboard", text);
super.UpdateAnswer(text);
}
protected LoadText(answer: Answer): string
{
return answer == null || answer.Text == null ? "" : answer.Text;
}
protected SaveText(answer: string): Answer
{
return { Text: answer };
}
public AddEvent(eventType:string, method:string = "None", data:string = "None"):void
{
super.AddRawEvent(eventType, "Freetext", "Instrument", method, data);
}
}
export = Freetext;
|
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.testclient import TestClient
from imia import APIKeyAuthenticator, AuthenticationMiddleware
from tests.conftest import inmemory_user_provider
async def app_view(request: Request) -> JSONResponse:
return JSONResponse(
{
'is_authenticated': request.auth.is_authenticated,
'user_id': request.auth.user_id,
'user_name': request.auth.display_name,
}
)
def test_apikey_authentication() -> None:
app = Starlette(
debug=True,
routes=[
Route('/app', app_view, methods=['GET']),
],
middleware=[
Middleware(
AuthenticationMiddleware,
authenticators=[
APIKeyAuthenticator(user_provider=inmemory_user_provider),
],
),
],
)
test_client = TestClient(app)
response = test_client.get('/app?apikey=root@localhost')
assert response.json()['is_authenticated'] is True
assert response.json()['user_id'] == 'root@localhost'
assert response.json()['user_name'] == 'Root'
def test_apikey_authentication_with_invalid_user() -> None:
app = Starlette(
debug=True,
routes=[
Route('/app', app_view, methods=['GET']),
],
middleware=[
Middleware(
AuthenticationMiddleware,
authenticators=[
APIKeyAuthenticator(user_provider=inmemory_user_provider),
],
),
],
)
test_client = TestClient(app)
response = test_client.get('/app?apikey=invalid@localhost')
assert response.json()['is_authenticated'] is False
response = test_client.get('/app', headers={'X-API-Key': 'invalid@localhost'})
assert response.json()['is_authenticated'] is False
def test_apikey_authentication_using_header() -> None:
app = Starlette(
debug=True,
routes=[
Route('/app', app_view, methods=['GET']),
],
middleware=[
Middleware(
AuthenticationMiddleware,
authenticators=[
APIKeyAuthenticator(user_provider=inmemory_user_provider),
],
),
],
)
test_client = TestClient(app)
response = test_client.get('/app', headers={'X-API-Key': 'root@localhost'})
assert response.json()['is_authenticated'] is True
assert response.json()['user_id'] == 'root@localhost'
assert response.json()['user_name'] == 'Root'
def test_apikey_query_params_have_higher_precedense() -> None:
app = Starlette(
debug=True,
routes=[
Route('/app', app_view, methods=['GET']),
],
middleware=[
Middleware(
AuthenticationMiddleware,
authenticators=[
APIKeyAuthenticator(user_provider=inmemory_user_provider),
],
),
],
)
test_client = TestClient(app)
response = test_client.get('/app?apikey=root@localhost', headers={'X-API-Key': 'invalid@localhost'})
assert response.json()['is_authenticated'] is True
def test_apikey_with_missing_token() -> None:
app = Starlette(
debug=True,
routes=[
Route('/app', app_view, methods=['GET']),
],
middleware=[
Middleware(
AuthenticationMiddleware,
authenticators=[
APIKeyAuthenticator(user_provider=inmemory_user_provider),
],
),
],
)
test_client = TestClient(app)
response = test_client.get('/app', headers={'X-API-Key': ''})
assert response.json()['is_authenticated'] is False
response = test_client.get('/app?apikey=')
assert response.json()['is_authenticated'] is False
response = test_client.get('/app')
assert response.json()['is_authenticated'] is False
|
Chronic inflammatory demyelinating polyradiculoneuropathy with diffuse and massive peripheral nerve hypertrophy: Distinctive clinical and magnetic resonance imaging features We present 3 patients with chronic inflammatory demyelinating polyradiculoneuropathy (CIDP) with extensive and diffuse hypertrophy of the nerve roots and peripheral nerves. They exhibited slowly progressive sensory impairment and distally predominant limb weakness and muscular atrophy, and markedly enlarged palpable nerve trunks. They responded beneficially to corticosteroid. Magnetic resonance imaging demonstrated diffuse and extensive hypertrophy of the peripheral nerves in the four limbs and the spinal nerve roots, with gadolinium enhancement in the nerve roots but not in the peripheral nerves. These patients were considered to have a hypertrophic variant of CIDP. © 1998 John Wiley & Sons, Inc. Muscle Nerve 21:805808, 1998.
|
def create_cluster_info(crs, cluster_name, key_words_arr):
clusters_amount = len(key_words_arr)
res_str = ''
for i in range(clusters_amount):
res_str += str(i) + ': ' + ' '.join(key_words_arr[i])
if i != clusters_amount - 1:
res_str += ', '
crs.execute('INSERT OR IGNORE INTO clusters(name, amount_of_clusters, cluster_values) VALUES("' +
str(cluster_name) + '", ' + str(clusters_amount) + ', "' + res_str + '")')
|
Susceptibility of organ cultures from chicken tissues for strains of infectious bronchitis virus isolated from the intestine. Organ cultures were prepared from various levels of intestine and kidney of 2 to 4-week old specific-pathogen-free chickens, and their susceptibility to ten strains of infectious bronchitis virus isolated from the chicken intestine and the Massachusetts strain M41 was investigated. The ability of a virus to grow depended on the strain of virus and size of the inoculum. While proventriculus, bursa and kidney were found to be universally susceptible to all viruses tested, some strains did not grow in caecal tonsils or rectum. Strain M41 showed little difference in pattern of tissue replication compared with several other strains isolated from the gut and actually grew in a wider range than some. Duodenum, jejunum and ileum were found to be non-permissive to all strains tested, even after a high input inoculum.
|
Aledo football coach Tim Buchanan was sitting in his Texas office Saturday morning watching game film from a 91-0 victory over Western Hills on Friday night when an email popped up on his computer.
The subject line read "Bullying report."
Buchanan couldn't believe it and thought it was a joke until he read the email and realized a Western Hills parent had filled out the district's online form, accusing the coaching staff of bullying thanks to the lopsided score.
Buchanan spent an hour in the superintendent's office this week and the school is currently investigating, as mandated by the state. The Aledo principal told Buchanan that a written report is expected in the next day or so, something required by state law. Buchanan -- who is in his 21st season as head coach at Aledo and said he has never been accused of bullying -- said he has the support of the Aledo administration.
"[The report filed] compliments our players, saying they showed extremely good sportsmanship," Buchanan said Tuesday morning. "This was not directed at our team, but the coaching staff for not instructing our players to ease up and quit playing hard once the game was in hand."
Western Hills coach John Naylor, whose team dropped to 0-7, didn't have any issues with how Buchanan and his staff handled the game, telling the Fort Worth Star-Telegram that the athletes played hard and didn't "talk at all."
"They're No. 1 for a reason, and I know Coach Buchanan," Naylor told the newspaper. "We're fighting a real uphill battle right now."
Undefeated Aledo, No. 1 in the Associated Press Class 4A state poll (the second-highest classification in the state), is racking up ridiculous yardage and crushing opponents this season. They are averaging just shy of 70 points per game, making some of those games essentially over before halftime.
In fact, at the half Friday, it was 56-0 and Buchanan and his coaching staff spent the intermission trying to figure out how to tap the offensive brakes without embarrassing Western Hills or hindering his own team's progress. Buchanan had one thought: "What are we going to do to not score 100?"
But he was also balancing that with the fact that his team is going to start facing tougher competition in the coming weeks and he wants to be sure his starters are used to playing at least some in the second half.
Buchanan simplified the playbook. He put in the second- and third-team offensive line and got the backups as much time as he could, while still playing a few starters here and there at the beginning of the third quarter. He told his punt returner to fair-catch the ball. All told, his offense had 32 snaps. His starters began coming out in the third quarter, some of them having played just 16 snaps, Buchanan said. The Bearcats rushed for 391 yards with eight touchdowns.
Buchanan said his starting running back touched the ball six times and scored four touchdowns. His backup kept finding holes as well, even without the starting offensive line in the game.
"I can't tell the backups not to play hard," Buchanan said. "They've worked their tails off all week. They've lifted weights in the offseason. I'm not going to tell them not to play."
But he did whatever he could to try to slow down his offense short of taking a knee in the third quarter.
The result was another easy win, but also some time in the principal's office after the report was filed.
Buchanan is now trying to focus on preparing his team for the schedule to stiffen and to be fully ready for the playoffs and a shot at a state title.
|
<filename>ext/openMVG/openMVG/features/feature.hpp<gh_stars>10-100
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2012, 2013 <NAME>.
// 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/.
#ifndef OPENMVG_FEATURES_FEATURE_HPP
#define OPENMVG_FEATURES_FEATURE_HPP
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>
#include "openMVG/numeric/eigen_alias_definition.hpp"
namespace openMVG {
namespace features {
/**
* Base class for Point features.
* Store position of a feature point.
*/
class PointFeature {
friend std::ostream& operator<<(std::ostream& out, const PointFeature& obj);
friend std::istream& operator>>(std::istream& in, PointFeature& obj);
public:
PointFeature(float x=0.0f, float y=0.0f);
float x() const;
float y() const;
const Vec2f & coords() const;
float& x();
float& y();
Vec2f& coords();
template<class Archive>
void serialize(Archive & ar)
{
ar (coords_(0), coords_(1));
}
protected:
Vec2f coords_; // (x, y).
};
/**
* Base class for ScaleInvariant Oriented Point features.
* Add scale and orientation description to basis PointFeature.
*/
class SIOPointFeature : public PointFeature {
friend std::ostream& operator<<(std::ostream& out, const SIOPointFeature& obj);
friend std::istream& operator>>(std::istream& in, SIOPointFeature& obj);
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
~SIOPointFeature() = default;
SIOPointFeature(float x=0.0f, float y=0.0f,
float scale=0.0f, float orient=0.0f);
float scale() const;
float& scale();
float orientation() const;
float& orientation();
bool operator ==(const SIOPointFeature& b) const;
bool operator !=(const SIOPointFeature& b) const;
template<class Archive>
void serialize(Archive & ar)
{
ar (
coords_(0), coords_(1),
scale_,
orientation_);
}
protected:
float scale_; // In pixels.
float orientation_; // In radians.
};
/// Return the coterminal angle between [0;2*PI].
/// Angle value must be in Radian.
float getCoterminalAngle(float angle);
/**
* Base class for Affine "Point" features.
* Add major & minor ellipse axis & orientation to the basis PointFeature.
*/
class AffinePointFeature : public PointFeature {
friend std::ostream& operator<<(std::ostream& out, const AffinePointFeature& obj);
friend std::istream& operator>>(std::istream& in, AffinePointFeature& obj);
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
virtual ~AffinePointFeature() = default;
AffinePointFeature
(
float x = 0.0f,
float y = 0.0f,
float a = 0.0f,
float b = 0.0f,
float c = 0.0f
);
float l1() const;
float l2() const;
float orientation() const;
bool operator ==(const AffinePointFeature& b) const;
bool operator !=(const AffinePointFeature& rhs) const;
template<class Archive>
void serialize(Archive & ar)
{
ar (
coords_(0), coords_(1),
l1_, l2_, phi_, a_, b_, c_);
}
float a() const;
float b() const;
float c() const;
protected:
float l1_, l2_, phi_, a_, b_, c_;
};
/// Read feats from file
template<typename FeaturesT >
static bool loadFeatsFromFile(
const std::string & sfileNameFeats,
FeaturesT & vec_feat)
{
vec_feat.clear();
std::ifstream fileIn(sfileNameFeats.c_str());
if (!fileIn.is_open())
{
return false;
}
std::copy(
std::istream_iterator<typename FeaturesT::value_type >(fileIn),
std::istream_iterator<typename FeaturesT::value_type >(),
std::back_inserter(vec_feat));
const bool bOk = !fileIn.bad();
fileIn.close();
return bOk;
}
/// Write feats to file
template<typename FeaturesT >
static bool saveFeatsToFile(
const std::string & sfileNameFeats,
FeaturesT & vec_feat)
{
std::ofstream file(sfileNameFeats.c_str());
if (!file.is_open())
return false;
std::copy(vec_feat.begin(), vec_feat.end(),
std::ostream_iterator<typename FeaturesT::value_type >(file,"\n"));
const bool bOk = file.good();
file.close();
return bOk;
}
/// Export point feature based vector to a matrix [(x,y)'T, (x,y)'T]
template<typename FeaturesT>
void PointsToMat(
const FeaturesT & vec_feats,
Mat& m)
{
m.resize(2, vec_feats.size());
using ValueT = typename FeaturesT::value_type; // Container type
size_t i = 0;
for (typename FeaturesT::const_iterator iter = vec_feats.begin();
iter != vec_feats.end(); ++iter, ++i)
{
const ValueT & feat = *iter;
m.col(i) << feat.x(), feat.y();
}
}
} // namespace features
} // namespace openMVG
#endif // OPENMVG_FEATURES_FEATURE_HPP
|
from collections import Counter
t = int(input())
for _ in range(t):
n = int(input()) # length of the team
team = input().split()
a = dict(Counter(team))
team_rep = []
all_values = a.values()
# maximum value or the digit which is repeated for maximum times
max_value = max(all_values)
team_set_length = len(set(team))
length = len(team)
if max_value > team_set_length:
print(min(max_value, team_set_length))
else:
print(min(max_value, (team_set_length-1)))
|
package main
import (
"../goLang/validate"
)
type MyReader struct{}
func (rd MyReader) Read(s []byte) (int, error) {
for i := 0; i < len(s); i++ {
s[i] = 'A'
}
return len(s), nil
}
func main() {
validate.Validate(MyReader{})
}
|
package edu.dao;
import edu.bean.CheckReport;
import java.util.List;
public interface CheckReportDao {
List<CheckReport> list();
//CheckPeport load(Long id);
// CheckPeport loadByName(String name);
//List<CheckPeport> pager(Long pageNum, Long pageSize);
// Long countByName(String name);
//List<CheckPeport> pagerByName(String name, Long pageNum, Long pageSize);
}
|
Motion induced excitation and radiation from an atom facing a mirror We study quantum dissipative effects due to the non-relativistic, bounded, accelerated motion of a single neutral atom in the presence of a planar perfect mirror, i.e. a perfect conductor at all frequencies. We consider a simplified model whereby a moving `scalar atom' is coupled to a quantum real scalar field, subjected to either Dirichlet or Neumann boundary conditions on the plane. We use an expansion in powers of the departure of the atom with respect to a static average position, to compute the vacuum persistence amplitude, and the resulting vacuum decay probability. We evaluate transition amplitudes corresponding to the excitation of the atom plus the emission of a particle, and show explicitly that the vacuum decay probabilities match the results obtained by integrating the transition amplitudes over the directions of the emitted particle. We also compute the spontaneous emission rate of an oscillating atom that is initially in an excited state. I. INTRODUCTION Quantum vacuum fluctuations are at the origin of many interesting phenomena. A prominent place among them corresponds to the forces arising between static neutral objects, originated in the fluctuations of the electromagnetic (EM) field. These Casimir forces have been measured with precision in the last decades, and there have also been theoretical advances on finding their dependence on the geometry and composition of the bodies. Vacuum fluctuations also affect the decay probability of single atoms, via spontaneous emission. In the proximity of metallic plates or when the atom is in a cavity, those decay probabilities may change because of the influence of the boundary conditions on the properties of those fluctuations. This kind of effect has been investigated in the context of cavity electrodynamics. Qualitatively different effects appear when the system is subjected to time dependent external conditions; for example, photon creation when macroscopic media are accelerated or when, being static, a time-dependence of their electromagnetic properties is induced. Moreover (under some conditions) even for a medium which moves at a constant velocity with respect to a static one, a frictional force, termed 'quantum friction', may arise. These phenomena, broadly named dynamical Casimir effect (DCE), do also manifest themselves at a microscopic level. For example, the oscillatory motion of the center of mass of an atom, which is initially in its ground state, can lead to different excited states of the atomfield system: one of them corresponds to a final state where the atom itself has been excited, and a photon has been emitted. Alternatively, the final state may contain a pair of photons, with the atom still in its ground state. The latter is the microscopic counterpart of the photoncreation process due to a moving mirror. A different mechanism, not involving motion, arises when external driving fields produce a time-dependence in the energy levels. Another interesting line of research, closely related to the present paper, focusses on single atoms near a mirror, and in relative motion to it. For example, for a two level atom in its excited state, an oscillating mirror induces modifications in the decay probability and in the spectrum of the emitted photons. Oscillating atoms near a perfect mirror have been considered in a number of situations, most of them using simplifying assumptions, either about the direction of the emitted photons or considering a scalar rather than the EM field. For uniform acceleration, the relation between the excitation probability for a moving atom has been compared with that of a moving mirror, in discussions of the equivalence principle. Imperfect mirrors have also been considered, in particular, in our previous work on quantum dissipative effects for an atom moving non-relativistically in the presence of a graphene sheet. The calculations were performed perturbatively in the coupling constants that define the imperfect media, estimating the dissipative phenomena, in this context, via the imaginary part of the in-out effective action. This is a "global" observable, namely, it accounts for the total probability of vacuum decay. In this paper, and for a similar kind of system, we present a two-fold approach to study quantum dissipation and then check their consistency: we first evaluate the imaginary part of the effective action, and then present a more refined study, by evaluating the probability of photon emission as a function of the direction of the emitted photons. The consistency of both approaches is checked by integrating out that emission probability over all the possible angles, and comparing with the probability of vacuum decay. We also consider the case of a moving atom that is initially in an excited state, and analyse the dependence of the probability of spontaneous emission on the acceleration of the atom and its distance to arXiv:2201.01341v2 11 Feb 2022 the mirror. We have done all calculations for a model where a real scalar field couples to a scalar model for an atom, which moves in the presence of a "perfect" mirror; namely, one which imposes either Dirichlet or Neumann boundary conditions. This paper is organised as follows: in II, we introduce the model and evaluate the imaginary part of its effective action, both for Dirichlet and Neumann boundary conditions, to the second order in the amplitude of motion of the atom. In Sec. III, we evaluate the transition probabilities. We find the total decay probability, and also show its consistency with the finer description of the elementary processes of photon emission and atom excitation. We also discuss the decay or spontaneous emission process in terms of its corresponding probability. Finally, in IV, we summarise our main conclusions. II. THE EFFECTIVE ACTION It has become common usage in research related to both the static and dynamic Casimir effects, to begin the analysis of the phenomenon being studied in a simplified setting, with a real scalar field playing the role of the full EM field. In some cases, one can even show that transverse electric and transverse magnetic modes can be described by scalar fields satisfying either Dirichlet and Neumann boundary conditions, and that the EM field results may be obtained as the superposition of those two scalar field theories. In our model, an atom will be coupled to a quantum real scalar field, and we will assume 'perfect' boundary conditions for the scalar field on the flat boundary, i.e. Dirichlet or Neumann. The free action for the massless scalar field shall be given by and boundary conditions will be assumed to be implemented at the level of the functional integral over gauge field fluctuations. In our conventions, indices from the middle of the Roman alphabet (i, j...) are assumed to run from 1 to 3, while those of the middle of the Greek alphabet (,,...) run from 0 to 3, with x 0 ≡ ct. In our conventions, c ≡ 1. The metric tensor is, on the other hand, assumed to be (g ) = diag(1, −1, −1, −1). Einstein convention on the sum over repeated indices is also understood, unless explicitly stated otherwise. The classical action for the atom is, on the other hand, assumed to be: where q(t) plays the role of the electron's degree of freedom, r(t) of the atom's center of mass, m is the electron's mass, and g is the coupling constant between the electron and the vacuum field. We will assume that the motion of the center of mass is bounded and we will denote by r 0 the (time) averaged position. Following a similar approach to the one of our previous work, we first integrate out the internal degree of freedom q(t), what produces an "intermediate" effective action S eff (; r), given by the expression: Then, the complete effective action of the system, functional of the center of mass coordinates, , is obtained by including the real scalar field fluctuations in the presence of the appropriate boundary conditions. Namely, The subindex 'm' for the brackets in the field integration measure has been included to signal that the integral is over those field configurations that are compatible with the boundary conditions imposed by the mirrors. In our case, and as already advanced, those conditions will be either Dirichlet or Neumann on the plane x 3 = 0. We shall not need to actually perform the full integrals above when we evaluate to the first order in S (a) I. Indeed, to that order, we just need the correlator of two fields in the presence of the mirror, which is just the field propagator in the presence of Dirichlet or Neumann conditions on a plane. More explicitly, and denoting the contribution of first order in S (a) I by (am) , we see that: where the symbol... (m) denotes the functional averaging A. Dirichlet mirror For a Dirichlet mirror, we can simply use the images method, to write: where G 0 is the free scalar-field propagator Introducing the explicit form of the Dirichlet propagator above into, and using an entirely analogous approach to the one of we obtain, after some algebra: We obtain more explicit expressions by expanding in powers of the departure of the atom from an equilibrium position r 0, which in our choice of coordinates will be of the form r 0 = (0, 0, a), a > 0. To the second order in the departure, which we denote y(t), and using tildes to denote time Fourier transforms, we find Because of the presence of the plate, spatial isotropy is lost and m ij D () and not proportional to ij. Rather, as a 3 3 matrix, it has the form: where the parallel component is and results in: The perpendicular component, on the other hand, is given by: It can be seen that both functions, m and m ⊥ approach a common limit m 0 far from the plate, i.e., when ||a → ∞: As expected, this is the result corresponding to an oscillating atom in free space. In Fig.1 we plot the ratios m ⊥ /m 0 and m /m 0 as functions of a(|| − ), where the above mentioned limit can be seen explicitly. On the contrary, in the opposite regime, i.e., close to the plate, those functions approach rather different limits. Indeed, m ⊥ is enhanced by a factor which approaches 2, that is m ⊥ () ≈ 2 m 0 (), while m tends to zero in that limit. These results have a simple interpretation in terms of the images of the oscillating atom in each case. B. Neumann mirror For a Neumann mirror, one has instead the propagator: Proceeding in an entirely analogous way as for the Dirichlet case, and results in: The perpendicular component, on the other hand, is given by: or, Far from the mirror, the results for Neumann boundary conditions also coincide with the free space case. Note, however, that the behaviours of m and m ⊥ close to the mirror are reversed, when compared with their Dirichlet counterparts. These results are illustrated in Fig.2. III. TRANSITION AMPLITUDES The existence of a threshold at || =, above which there is a continuum in frequency with a non-vanishing probability of vacuum decay, suggests that the processes involved correspond to an excitation of the electron in the atom (hence the threshold ), plus the emission of a massless scalar field particle (the continuum above the threshold). Besides, we know that the imaginary part of the effective action is related to the squared modulus of the transition amplitude for the creation of real particles, when the threshold is reached. To that end, and having in mind the calculation of the imaginary part of the effective action to the same order we have used, we consider the transition matrix T, related to the S matrix by S = I + iT, (I: identity operator), to the lowest non-trivial order in the coupling constant g. We use standard perturbation theory in the interaction representation, taking as free Hamiltonian the one corresponding to the free atom plus the free scalar field (including its boundary conditions). Therefore, with T the chronological ordering operator. The matrix elements of the T matrix between the initial and final states, to the first order in g, are then of the form: The operators above evolve independently, according to their respective free Hamiltonians, thus, for the electron degree of freedom: where a and a denote the standard destruction and creation operators for the harmonic oscillator. The scalar field, on the other hand, will have different expansions depending on whether the mirror imposes Dirichlet or Neumann boundary conditions. We consider these two alternatives below. A. Dirichlet plane In this case, which we consider first, using the notations: z ≡ x 3, x ≡ (x 1, x 2 ) (and analogously for the components of k), we shall have: (k) = |k| and the only non-vanishing commutator between the operators appearing in the decomposition is = (k − k ). The initial state will be of the form: |i = |0 ⊗ |0, where the first factor refers to the electron and the second one to the field. For this kind of initial state, the only non-vanishing contribution to T f i will be of the form: The factor 1 N is included in order to normalize the state |k, what is needed in order to obtain probabilities from T f i. If the system is put in a cubic box of length L, We find: For parallel motion: r z (t) ≡ a, and to the lowest nontrivial order in the departure y (t) = r (t), Thus, the probability for the process, with the final particle in an infinitesimal volume in momentum space, dP f i, is obtained by multiplying d 3 k |T Then where a, b = 1, 2. It is convenient to introduce spherical coordinates centered at the mean position of the atom, such that is along the x 1 axis. With this choice, the spatial dependence of the probability is explicitly given by where p D is proportional to the probability per unit solid angle. In Fig. 3 we plot this function for different values of the product ka. We see that for ka ≤ O the angular dependence corresponds to quadrupole radiation, as expected from the images method; indeed, in this regime the retardation between a wave emitted by the atom and the one due to its image can be ignored, and therefore the parallel oscillating dipole behaves as a quadrupole when combined with its image companion. For intermediate values of ka, retardation cannot be ignored, and the angular dependence shows a complex structure of peaks, while at very large values The total probability of this kind of process P f i is obtained by integrating out over all the possible momenta. Rather than integrating over the variables above, it is more convenient to proceed as follows: Interchanging the order of the integrals, the one over k may then be performed exactly. This produces an expression of the form: Note that this is in agreement with our results for the imaginary part, since P is twice the imaginary part of the effective action. For motion perpendicular to the plane, and In this case there is of course axial symmetry with respect to the direction of motion; therefore we may integrate the probability along angle dP f i = g 2 2 (2) 2 m k 3 sin cos 2 cos 2 (ka cos ) In Fig. 4 and we plot the function p D ⊥ (ka, ) for different values of ka. We can see that the radiation has a dipolar pattern both at small and very large distances: at very small distances the image dipole reinforces (without retardation and therefore no interference) the effect of the vertical oscillating dipole associated to the moving atom, while at large distances we recover the result for the oscillating atom in free space. Again, the total probability becomes identical to twice the imaginary part of the effective action (evaluated to the second order in g). In the same way, we shall study the spontaneous decay process in which the initial state is now given by |i = |1 ⊗|0 (i.e. the atom in the excited state and the field in vacuum) and the final state is given by |f = |0 ⊗ |1. It is straightforward to check that in this case there is no threshold at || = and the result is given for the matrix element T f i in the parallel motion is for r z (t) ≡ a, and to the lowest non-trivial order in the departure y (t) = r (t), where, unlike the excitation case examined previously, there is a first term independent of the amplitude of the oscillation, that corresponds to the spontaneous decay for a static atom in front of a mirror. The probability for the decay process is now given by For the motion perpendicular to the plane we have and assuming that ⊥ = 0. It is worth to remark that in both situations (parallel o perpendicular motions), if the atom's center of mass oscillates harmonically with a frequency cm <, the spectrum of the emitted photons will have three different frequencies =, ± cm. A similar phenomenon occurs for an atom in front of an oscillating mirror, in the adiabatic approximation. Only two frequencies would be present in the spectrum when cm >. B. Neumann plane We now have a different expansion for the field: Since the interaction term is exactly the same as for the Dirichlet case, it is immediate to find the probabilities in this case. For parallel motion: In Figs. 5 and 6 we plot the function p N and p N ⊥, respectively. Although less evident than in the Dirichlet case, p N ⊥ shows a quadrupole pattern at small distances, being proportional to cos 4 (). Yet again, the total probabilities are consistent with the results obtained in the effective action approach. For completeness we will study in this section the case of the spontaneous decay process with Neumann bound- (c) ka = 5 Figure 6: We plot here p N ⊥ from Eq. as a function of spherical angles and, for Neumann boundary condition and perpendicular motion ary conditions on the perfect mirror. In the case of parallel to the plane oscillatory motion of the atom, the probability density for such process is obtained For the perpendicular motion we get The spectrum of the emitted particles is similar to that of the Dirichlet plane. Note, however, that the dependence with the mean distance to the mirror is different, as well as the relative weight between the static and non-static contributions for the case of perpendicular motion. IV. CONCLUSIONS In this paper we have studied the phenomena of excitation and spontaneous emission of a moving atom in front of a perfect mirror, in a model where the atom is coupled to a quantum real scalar field, and the perfect conductor boundary conditions have been mimicked by Dirichlet and Neumann boundary conditions. Assuming that the atom performs small amplitude motions, we computed the vacuum decay probability to the second order in the coupling constant between the electron and the field. This probability is determined by the imaginary part of the effective action, which is a functional of the trajectory of the atom's center of mass. When the atom is close enough to the mirror, the results for Dirichlet and Neumann boundary conditions admit simple interpretations in terms of the images method. The physical process behind vacuum decay is, up to this order, the transition of the atom from the ground state to the first excited state, along with the emission of a photon. Thus, there is a threshold for the process dictated by energy conservation which is cm >. We have also computed the probability for the decay process as a function of the direction of the emitted particle, and checked that the integration over all directions reproduce the vacuum decay probability. The angular dependence of the probability can also be understood in terms of the images method. In particular, for Dirichlet boundary conditions, the radiation emitted by an atom in parallel motion becomes quadrupolar when the atom is close to the mirror. For Neumann boundary conditions this happens for perpendicular motion. Finally, we analyzed the spontaneous decay of an oscillating atom in front of a mirror. Both the presence of the mirror and the oscillation of the atom induce corrections to the spontaneous emission in free space. The presence of the mirror modifies the angular dependence of the probability, that turns out to be a function of the atom-mirror distance, but not the energy of the emitted photons. When the atom oscillates, the spectrum of the emitted particles is modified by the appearance of two lateral peaks, symmetric with respect to the central peak that corresponds to the static atom. These results are similar to those for a static atom in front of an oscillating mirror, and opens new possibilities for the eventual experimental observation of the effect. The extension of our results to the more realistic case of the electromagnetic field can be addressed, in the dipole approximation, using similar techniques. Work in this direction is in progress.
|
Trolls Posted “It’s Okay to Be White” Stickers in Cambridge on Halloween
They were spotted in Harvard Square and around Cambridge Common.
Harvard Square is near the center of Cambridge, Massachusetts, United States. It refers to both the triangular plaza at the intersection of Massachusetts Avenue, Brattle Street, and John F. Kennedy Street; as well as the business district and Harvard University surrounding that intersection.
Here we go again. An internet genius, or geniuses, has taken to the streets of Cambridge with another message designed to rile us all up: “It’s okay to be white.”
Stickers with the infuriatingly innocent-sounding phrase, written in a cutesy font, were Globe, said 20 of them had been removed. Stickers with the infuriatingly innocent-sounding phrase, written in a cutesy font, were spotted by Boston Globe reporters Wednesday morning “on light poles and electrical boxes around Cambridge Common and Harvard Square.” A city employee spotted scraping one off, according to theGlobe,said 20 of them had been removed.
Where did they come from?
A post on a forum last night suggests it may have been part of a coordinated trolling effort timed for Halloween. It may or may not have anything to do with the stickers in Cambridge, but it offers some insight on why these campaigns keep happening. The post mentioned plans to distribute fliers reading “it’s okay to be white” on “car windshields, bulletins, telephone poles, malls, buildings,” then sit back and watch the fireworks. A similar sign was A post on a forum last night suggests it may have been part of a coordinated trolling effort timed for Halloween. It may or may not have anything to do with the stickers in Cambridge, but it offers some insight on why these campaigns keep happening. The post mentioned plans to distribute fliers reading “it’s okay to be white” on “car windshields, bulletins, telephone poles, malls, buildings,” then sit back and watch the fireworks. A similar sign was discovered yesterday outside the offices of a “Native Studies” building on the campus of the University of Alberta.
“It’s okay to be white” as a messaging tactic has gotten popular in the stupidest corners of online lately, at a time when groups affiliated with the so-called “alt-right” have begun holding rallies and promoting the idea that white people are under attack in the U.S. It’s also the name of a song from a prominent neo-Nazi band, probably not coincidentally—not necessarily because they’re affiliated in some direct way, but because it’s such a potently simple message that appeals to the kind of person “It’s okay to be white” as a messaging tactic has gotten popular in the stupidest corners of online lately, at a time when groups affiliated with the so-called “alt-right” have begun holding rallies and promoting the idea that white people are under attack in the U.S. It’s also the name of a song from a prominent neo-Nazi band, probably not coincidentally—not necessarily because they’re affiliated in some direct way, but because it’s such a potently simple message that appeals to the kind of person susceptible to the idea of “white victimhood.”
It’s hard to even write about these sorts of things, thanks to the incredibly exhausting trap its architects set for us all. The theory is that the media won’t be able to resist coverage of it, and the overheated response to it will set off alarm bells for those who believe we’re in a crisis of “political correctness” and “reverse racism.” It also follows the pattern of white nationalist groups posting provocative fliers on college campuses, like at It’s hard to even write about these sorts of things, thanks to the incredibly exhausting trap its architects set for us all. The theory is that the media won’t be able to resist coverage of it, and the overheated response to it will set off alarm bells for those who believe we’re in a crisis of “political correctness” and “reverse racism.” It also follows the pattern of white nationalist groups posting provocative fliers on college campuses, like at Emerson or Boston University , to provoke maximum angst.
Here’s what else that forum—which, again, may or may not have anything to do with the Cambridge stickers—had to say about how we all would react:
Based on past media response to similar messaging, we expect the anti-white media to produce a ********** [sic] about these “racist, hateful, bigoted fliers”… with a completely innocuous message. The media response will rally new support for pro-white activism, as normies (especially whites) will be extremely turned off by the media reaction.
I’m so tired.
Read More About: Cambridge
|
<reponame>arkiny/OSwithMSVC
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Ghost, a micro-kernel based operating system for the x86 architecture *
* Copyright (C) 2015, <NAME> <<EMAIL>> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef GHOST_RAMDISK_RAMDISKENTRY
#define GHOST_RAMDISK_RAMDISKENTRY
#include "skyramdisk.h"
#include "skyramdisk_struct.h"
/**
* Struct of a ramdisk entry
*/
struct g_ramdisk_entry {
g_ramdisk_entry* next;
g_ramdisk_entry_type type;
uint32_t id;
uint32_t parentid;
char* name;
uint32_t datalength;
uint8_t* data;
bool data_on_ramdisk;
uint32_t not_on_rd_buffer_length;
};
#endif
|
package uu.toolbox.data;
import org.junit.Assert;
import uu.toolbox.core.UURandom;
@UUSqlTable(tableName = "uu_data_model_with_compound_key", existsInVersion = 2)
public class UUDataModelWithCompoundKey implements UUDataModel
{
@UUSqlColumn(name = "c1", primaryKey = true)
public String c1;
@UUSqlColumn(name = "c2", primaryKey = true)
public String c2;
@UUSqlColumn(name = "data")
public String data;
public static UUDataModelWithCompoundKey random()
{
UUDataModelWithCompoundKey m = new UUDataModelWithCompoundKey();
m.c1 = UURandom.randomLetters(20);
m.c2 = UURandom.randomLetters(20);
m.data = UURandom.randomLetters(20);
return m;
}
public static void assertEquals(UUDataModelWithCompoundKey obj, UUDataModelWithCompoundKey other)
{
Assert.assertNotNull(obj);
Assert.assertNotNull(other);
Assert.assertEquals(obj.c1, other.c1);
Assert.assertEquals(obj.c2, other.c2);
Assert.assertEquals(obj.data, other.data);
}
}
|
Research and Comparison of Time-frequency Techniques for Nonstationary Signals Most of signals in engineering are nonstationary and time-varying. The Fourier transform as a traditional approach can only provide the feature information in frequency domain. The time-frequency techniques may give a comprehensive description of signals in time-frequency planes. Based on some typical nonstationary signals, five time-frequency analysis methods, i.e., the short-time Fourier transform (STFT), wavelet transform (WT), Wigner-Ville distribution (WVD), pseudo-WVD (PWVD) and the Hilbert- Huang transform (HHT), were performed and compared in this paper. The characteristics of each method were obtained and discussed. Compared with the other methods, the HHT with a high time-frequency resolution can clearly describe the rules of the frequency compositions changing with time, is a good approach for feature extraction in nonstationary signal processing.
|
Using panel survey and remote sensing data to explain yield gaps for maize in sub-Saharan Africa ABSTRACT The aim of this paper is to combine remote sensing data with geo-coded household survey data in order to measure the impact of different socio-economic and biophysical factors on maize yields. We use multilevel linear regression to model village mean maize yield per year as a function of NDVI, commercialization, pluriactivity and distance to market. We draw on seven years of panel data on African smallholders, drawn from three rounds of data collection over a twelve-year period and 56 villages in six countries combined with a time-series analysis of NDVI data from the MODIS sensor. We show that, although there is much noise in yield forecasts as made with our methodology, socio-economic drivers substantially impact on yields, more, it seems, than do biophysical drivers. To reach more powerful explanations researchers need to incorporate socio-economic parameters in their models. Introduction Agriculture and its related industries are potential drivers of economic growth in sub-Saharan Africa (SSA) and are often seen as keys to poverty reduction and food security. Increased smallholder productivity is an important aspect of such agriculture-based growth and development because it is a source of income for the rural poor (World Bank, 2007). However, there is a productivity gap between achieved and potential yields in SSA. Studies show that there are major and growing discrepancies in productivity both when comparing African yields to those of the rest of the world and when comparing household level yields in SSA to locally achievable yields (Dzanku, Jirstrm, & Marstorp, 2015;Jayne, Mather, & Mghenyi, 2006;Van Dijk, Meijerink, Rau, & Shutes, 2012). Reducing these productivity gaps, known as yield gaps, is therefore a major goal in SSA. An understanding of the major factors driving these observed yield gaps is important in helping to narrow productivity deficiencies and achieve the goals of increased agricultural productivity (;Lobell, 2013;Tittonell & Giller, 2013). Likewise, a better understanding of the multitude of factors which contribute to the observed yield levels in SSA can add to a dialog about how these factors can be changed and improved in order to reduce yield gaps. However, 'yield gaps are the end result of a myriad interacting biological, physical, and economic forces' (Mueller & Binder, 2015, p. 45) which cannot easily be disentangled. For this reason, understanding yield gaps is not a simple task. Spatial and temporal variation in productivity are best regarded as the result of several interacting forces -geographic, biophysical, socio-economic and political ones (Mueller & Binder, 2015). This is usually recognized in principle and theory but not always in practice and few studies examine the empirical relationship between these interacting forces. In a review of 62 papers related to yield gaps, Snyder, Miththapala, Sommer, and Braslow found that most focused only on biophysical factors. In fact, only eight papers had models which included socio-economic factors. Similarly, in a meta-analysis of 50 peer-reviewed articles on yield gaps, Beza, Silva, Kooistra, and Reidsma found that only 16 of them considered the importance of farm characteristics such as labour and income in explaining yield gaps. An integrated approach to studying yields and yield gaps which incorporates not only biophysical but also farm management and socio-economic determinants is recognized as being important; however, in practice has not often been implemented empirically. One reason for this lack of empirical research regarding the diverse factors that contribute to yield variations in SSA is a lack of good quality data. Official statistics often suffer from poor spatial and temporal coverage and low reliability which leads to deceptive conclusions and misleading, ahistorical policy recommendations (Calogero Carletto, Jolliffe, & Banerjee, 2013;Jerven, 2013Jerven,, 2015. Rather than use official statistics, many researchers collect their own data. However, resource and time constraints often mean small samples, restricted locations and cross-sectional rather than longitudinal data. While more reliable on a local scale, such data still sacrifice spatial and temporal representativeness and have led to a situation where agrarian studies, from agronomic to anthropological ones, abound in number but lack in comparability. Good, reliable data across multiple time and spatial scales is hard to come by and this difficulty is magnified when attempting to collect detailed data across several disciplines. The consequence is that researchers are locked up in their different methodologies and corresponding world views. One data source which has grown in importance within yield gaps studies is remote sensing (RS) data. RS is routinely drawn on in crop models, combined with rainfall, temperature, soil nutrients, management and other input data. Such models are known for detailed and reliable forecasts of harvests. However, these models are much more common in Europe and the United States, where modelling is facilitated by large field sizes and mono-cropping, than they are in SSA, where poor quality and low resolution of input data combined with small field sizes and pervasive intercropping limit their use. RS data can also be used to estimate vegetation indices (VIs) which can describe vegetation density and health. These VIs have been shown to be correlated with characteristics like leaf area index, biomass and productivity (;Myneni, Hall, Sellers, & Marshak, 1995). Since RS data at different resolutions is available consistently over time and space, it can be matched to socio-economic, political and other data, as long as such data is georeferenced. This combination of survey and RS data has the potential to help to reduce some of the previously discussed data issues associated with yield gap studies including the lack of pluridisciplinary perspectives. The aim of this paper is to combine RS data with geo-coded household survey data in order to measure the impact of different socio-economic and biophysical factors on maize yields. We use empirical models to study yields in 56 villages in six SSA countries during a 12 year period from 2002 to 2013. We choose to study maize yields because maize is the most common crop harvested in our sample villages. Materials and methods In order to account for both the biophysical and socio-economic drivers of yield, this study employs a mixture of two datasets along with a triangulation of methods. The datasets used include panel household surveys from the Afrint database and RS data from the MODIS satellite. Each of these will be presented in more detail in the following section. The mixed methodologies used include timeseries analysis of VIs in order to gain an understanding of vegetation change and development coupled with bivariate and multivariate modelling of maize yields. These will be presented in Section 2.2. Household level data from the afrint database The socio-economic and yield data used for this study are taken from the Afrint database, a database generated as part of the African Agricultural Intensification (Afrint) project. This project has been running since the year 2002 and was initially aimed at assessing the possibilities for an Asian style Green Revolution in nine countries in SSA based on household level data for approximately 4000 smallholder farms. Since the first round of data collection in 2002, two additional rounds have been carried out, one in 2008 and one in 2013/2015. 1 Because of resource constraints, only six countries from the original nine have continued throughout the entire project. The database consists of two panel rounds (2002-2008 and 2008-2013) and three cross-sections. A detailed description of the database and sampling methodologies can be found in Andersson Djurfeldt, Dzanku, and Cuthbert Isinika. The sample used in this study consists of 2544 households from six countries, grouped by village (N = 56) and region (N = 15). The sample constitutes between 30 and 60 farmers from each village. Table 1 shows the breakdown of the sample by country and region. This study draws on only a small subset from the dearth of data collected in the Afrint database, mainly area under maize, amount of maize harvested, amount of maize sold, other sources of income, and geolocation data. For the first two of these variables we have data regarding the panel rounds (2002, 2008 and 2013) as well as the two preceding years since farmers were asked to recall previous figures. However, the 2000 and 2001 data are not comparable to that from the other years because the questions regarding maize production and area under maize were not asked in the same way. Likewise, for the amount of maize sold we have data from each panel round as well as the two preceding years; however, only for the first and second rounds. For the other sources of income we have only three time points of data, one for each of the panel rounds. The geolocation data consist of a point location (latitude and longitude coordinates) for the center of each of the 56 villages. The area under maize and amount of maize harvested were used in order to estimate maize yields, the dependent variable in this study. The remaining variables were used to generate measures of commercialization, pluriactivity and distance to market which were used as the socio-economic indicators in this study. These indicators were chosen based on previous research drawing on Afrint data which indicate that commercialization, pluriactivity and distance to market are significant proximate causes of yield variability (Andersson, Djurfeldt, Holmquist, Jirstrm, & Nasrin, 2011;Andersson, Djurfeldt, Holmquist, & Jirstrm, 2007;Djurfeldt, Aryeetey, & Isinika, 2011;Djurfeldt, Larsson, Holmquist, Jirstrm, & Andersson, 2008;Jirstrm, Archila Bustos, & Alobo Loison, 2018). VIs are used to indicate the level of greenness of vegetation and biomass. They are conditioned by geo-and biophysical factors like rainfall, temperature and soil fertility and are therefore a good indicator of biophysical conditions (Kawabata, Ichii, & Yamaguchi, 2001). They also reflect management conditions such as fertilizer application, irrigation and labour inputs because these can impact soil conditions and alter biomass production. In this study we therefore use the Normalized Difference Vegetation Index (NDVI) in order to develop a proxy for biomass production over the growing season, which reflects both biophysical factors and farm management factors that impact yields. MODIS vegetation index products (specifically NDVI), MOD13 (Terra) and MYD13 (Aqua) with a 250 m spatial resolution and 16-day temporal resolution, were used. Because the vegetation indices from the Terra and Aqua satellites are a phased product, meaning that the 16-day composites are generated eight days apart when alternating between the two satellites, we were able to get an effective 8-day temporal resolution for NDVI. In order to cover each of our 56 villages, seven different MODIS tiles were required. MOD13 data are available from the year 2000 until the present time and, in order to match our survey data, we used data from 2001 to 2014 for a total of 14 years and 322 images per tile. MYD13 data are only available from July 2002 until the present. As such only 288 images were used. This means that the temporal resolution for the first year and a half of data is lower (16-days) as compared to the remaining study period (8-days). In total, we studied 610 images in a time-series analysis. Methods We model yields first using a bivariate model and then proceeding to a multivariate model. In this section we describe each of these models. First, however, we explain the methodology used to calculate our independent and dependent variables, summarized in Table 2. The smallest unit of analysis in our study is the village level. This is because the NDVI indicator is based on a geographical location and we did not collect locational information on individual farms. Instead, we use the village location. As such, our socio-economic indicators and yields are aggregated to the village level as well. The time period for our analysis is between 2002 and 2013 because this is the time period for which the socio-economic and NDVI indicators coincide. Additionally, some study years contain more data than other years because, as previously discussed, some information was not collected for all study years. Socio-economic indicators Commercialization is the first socio-economic indicator that we derive. We define it as the proportion of the total village harvest of maize that is sold in a given year. Pluriactivity, also referred to as non-farm diversification in other studies, is the second socio-economic driver we use. It reflects the pursuit of Village coordinates, travel time to major cities work and income outside of the farm, whether inside the village (work for other farmers, for example), or outside of it, in neighboring villages, in the nearest town or further away. We define pluriactivity as the proportion of total village income that is from non-farm sources. Finally, the third socio-economic indicator we define is distance to market. This is measured as the Euclidean distance to the nearest town of at least 50,000 inhabitants in the year 2000. Biophysical indicators derived from NDVI Time-series analysis of NDVI data allows for the extraction of seasonality parameters which, in this study, were used as proxies for biomass production and by extension biophysical and farm management indicators of maize yield. TIMESAT software was used to perform the analysis (Jnsson & Eklundh, 2002). TIMESAT extracts seasonality information by smoothing curves from noisy satellite data in two steps. It first fits local functions to sets of data points and then builds global functions to describe the VI variations in vegetation seasons based on those local functions (Jnsson & Eklundh, 2002). For each village, two separate locations, composed of one MODIS pixel each, were examined, one representing intensively managed land close to the known village coordinates (the cropped pixel) and a second representing land further away from the village which appeared to be unmanaged (the reference pixel). The selection of these two locations was done manually based on visual inspection of Google Earth imagery. Both locations were screened and moved if they showed uncharacteristic seasonal patterns. Thus, the reference pixels do not show the clear seasonal variations that the cropped pixels do. In order to avoid mistakes in this manual process, Afrint-team members familiar with the villages were consulted. The TIMESAT software was then used to fit a seasonal curve to the time series data for each of the two pixels in each of the 56 villages, resulting in a total of 112 time-series. A Savitsky-Golay filter was used to smooth the data. Additionally, a seasonality parameter was set based on observation of the data. The value of this parameter determines whether there are one or two growing seasons. Finally, the value for the start of season was set as the point at which the left edge had risen from the left minimum to 50% of the seasonal amplitude. The end of season was likewise set as the point at which the right edge had declined to 50% of the seasonal amplitude from the right minimum, see Figure 1. Figure 1. TIMESAT parameters, amplitude, start and end of season, base level, small integral Two results were reported from each time series for each growing season (one growing season in some villages and two growing seasons in others). Because the filtering algorithm can introduce inaccuracies in the first and last growing seasons of the time series, the output from the 2001 and 2014 growing seasons was ignored. The first output result taken was the length of the growing season. The second was the NDVI small integral, which is determined as the integral of the fitted function from the season start to the season end, minus the area below the base level, as illustrated in Figure 1. This is a reflection of the biomass produced over the entire growing season. Yield estimation by household survey panel data Production and area under cultivation data were used to generate yield estimates at the village level by calculating truncated village geometric means. Studies have shown that yield calculations are especially sensitive to bias in farmers' estimates for small fields (Carletto, Jolliffe, & Banerjee, 2015;Fraval et al., forthcoming). Because our data includes self-reported estimates for area under maize cultivation for fields that are usually of a small size we first pruned the input data in order to attempt to reduce some of the inaccuracies introduced by farmer bias. Initially, cases with reported land sizes of less than 0.1 hectares were excluded. Additionally, cases with household level yields (calculated as the production divided by the cultivated land size) of over 10 tons per hectare were omitted. Furthermore, we deleted cases that reported a more than six-fold increase in yields between consecutive years. As a village level characteristic of yield (production/cultivated land area) we calculated the geometric mean of the within-village farmers yields. This gives a measure less sensitive to the skew distributions in production as well as in cultivated land area (and by implication also in yield) among the sampled farmers in the village. In order to 'robustify' the village estimate further, we removed the top and bottom 10% of observations per village in both the production and area variables. Statistical analysis and models for yield estimation We begin by presenting descriptive statistics over the length of season and NDVI small integral for both the cropped and reference pixel as well as the maize yields for each of the three time periods and performing an ANOVA of the differences between the time periods and the two types of pixels. The null hypothesis is that there are no differences between these variables over time or for different levels of management. A rejection of this hypothesis could signify a changing significance of the length of season or biomass over time or for different levels of management. Next, we introduce two statistical models of the variation in yields. The first is a bivariate model and the second is a multivariate one. The aim of the bivariate model is to establish the relationship between biomass production (for the cropped pixel) and maize yields, without taking into account the contribution of the socio-economic indicators. Here we expect a positive relationship, in line with previous research (Lewis, Rowland, & Nadeau, 1998;Vrieling, de Beurs, & Brown, 2008;Wang, Rich, Price, & Kettle, 2005). Thus, we regress the log geometric mean of maize yield on the log NDVI small integral. This model, however, does not serve to address our research question, which aims to identify the impact of both biophysical and socio-economic factors on yield variation. As such, we introduce our socio-economic indicators into a multivariate model. 2 This model also examines the difference between the three survey periods, not with the primary aim of showing change between periods, but mainly to get three separate tests of the determinants of village yields. The null hypothesis is that these determinants do not change over time. If the hypothesis is refuted it could, again, reflect changes in determinants of yields between periods. For this reason, we introduce two dummy variables, one for the second round of data and one for the third round. The reference is the first round, which, as mentioned earlier, is effectively only the year 2002 because of limitations with our different data. We choose to simplify the time series into these three groups in order to simplify the model and because of limitations with data availability. For the yield and NDVI small integral, which were gathered over multiple years, the average for the corresponding panel period is taken. Here, as with the bivariate model, we use the NDVI small integral only for the cropped pixel. The socio-economic variables are taken from the 2008 period in order to assure that, at least in comparison to the more dynamic last period, they reflect impacts of the independent variables on the dependent one and not the other way around. We employ a multilevel or hierarchical multivariate model with three levels, village, region and country, mimicking the household survey sample design. The model is estimated by MLWin (Rasbash, Browne, Healy, Cameron, & Charlton, 2010), which is a software tailored to hierarchical models. Estimation is two-step, firstly by iterative generalized likelihood (IGLS) and, using the IGLS estimates as Bayesian priors, secondly by Markov-Chain Monte Carlo (MCMC) estimation. Formally the model looks as below: Equation 1. Mathematical description of multivariate model. The dependent variable is the log geometric mean of maize yield (ln(y ijk )) for village (i), region (j) and country (k). The link function is approximately normal () and models log village yield as a linear function of an array of independent variables (X) with each one its regression coefficient (B). We model village-panel yield as dependent on a village, region and country-specific intercept ( 0ijk ), the log NDVI small integral ( 1 VI ijk ), commercialization ( 2 comm ijk ), pluriactivity ( 3 plur ijk ), distance to market ( 4 dist ijk ) and the dummies for panel 2 ( 5 panel2 ijk ) and 3 ( 6 panel3 ijk ), again using the first panel 3 as the reference category. The intercept ( 0ijk ) is a function of the overall intercept ( 0 ), the between country variance (v 0k ), the between-region variance (u 0jk ) and the between-village variance (e 0ijk ). All these variances are assumed to be approximately normal with mean = 0 and variance () equal to the level-specific sample variances ( 2 ). Table 3 shows descriptive statistics for the length of season and NDVI small integral for both the cropped and reference pixel as well as the mean village maize yields by panel period. Results and discussion An ANOVA of the differences between the three time period means shows that none of them are statistically significant. However, the difference between the total mean length of season observed in the cropped pixel and the one in the reference pixel is indeed statistically significant (p < 0.001) with the former being shorter by about ten days. The difference in the NDVI small integral between the two pixels is, however, not large enough to be significant. Thus, we do not see any significant differences over time in any of the variables studied. We do, however, see one difference when it comes to management. While the NDVI small integral is not changed, there is a shorter growing season for the managed land. An ad hoc explanation is that ploughing and sowing is somewhat delayed after the start of the rains, which is why the green season starts a little later in the cropped land. The fact that the NDVI small integral is unchanged, despite a shorter growing season, can be interpreted as an indicator of the low productivity of the majority of the smallholders in our sample villages. Here we make an assumption that the cropped pixel should achieve higher biomass than the reference pixel. This is based on two further assumptions, drawn from our foundation that the NDVI small integral reflects both biophysical and farm management indicators of yield. First, we assume that good husbandry should lead to higher biomass production by improving the natural conditions of the land for growth of maize. Second, we assume that farmers knowingly select land with better biophysical preconditions for production. Therefore, we would expect to see that the cropped pixel would have a higher biomass production than the reference pixel; we, however, do not find such a trend. The farmers in our study have, therefore, not reached above the biological potential of the land which they are farming. Descriptive statistics have shown no significant difference between the cropped and reference pixel and this we attribute to the fact that farmers are not improving the biological potential of their land. The cropped pixel managed by farmers who cultivate their land, while the reference pixel is not. For this reason, we move on to examine the cropped pixel specifically and explore how both biophysical and socio-economic factors influence the variance in yields. We start, as previously explained, by examining the biomass production only as a means of further examining the relationship between biophysical factors, farm management and yields. Figure 2 presents a scattergram of the logged village mean yields and the logged NDVI small integral. There is a positive correlation, significant at the 10 per cent level; however, the coefficient of determination is very low (R2 = 0.013), indicating that the log NDVI small integral accounts for a mere per cent of the variance in log yields. This is evident also by the wide scattering of cases around the line, as well as the breadth of the 90 per cent confidence interval. There are some outlying village-year means with low yields, all of them from 2008, which was a year with uncharacteristically low production in many villages due to flooding. Since they are located near the mean NDVI small integral (indicated by the vertical line), they contribute more to the variance than to the tilt of the regression line. Figure 2. Regression of village ratio mean yield on the NDVI small integral with 90 per cent confidence interval While this bivariate exercise confirms the expected relationship between biomass and maize yields, in our SSA context it proves to be a weak relationship. For this reason, we expand the bivariate model in Figure 2 to a multivariate one, which allows us to look at the interaction between biophysical and socio-economic factors in driving yield variation. The results of this multivariate model are seen in Table 4. The estimated model is statistically significant (Chi2 = 120.35, df = 10, p < 0.001). The variance between villages is highly significant while the within-village variance does not deviate far from normality, with no apparent bias in the estimation. The variances between countries and between regions are not statistically significant. 4 Let us comment on the results variable by variable, starting with the NDVI small integral. In the bivariate model presented in Figure 2, the log of the NDVI small integral was statistically significant, but only at 10 per cent level. This result holds in the multivariate setup and is, in fact, somewhat stronger (p < 0.05). However, the NDVI small integral still explains only a small share of the overall variance in village yields. A one per cent relative increase in the NDVI small integral is expected to result in a 0.18 per cent relative increase in the village yield. Thus, most of the variance in yields is explained, not by the biophysical and management factors, but by other factors, some of which are the socio-economic indicators which we now turn our focus to. It is first, however, important to recognize one of the main limitations of this study. We have found that NDVI small integral is not a very strong indicator of yields under the observed conditions in SSA and among smallholders. It should be stressed, however, that this is partly a scale effect, since we are studying MODIS pixels of the size of 250 250 meters with no indicator of within-pixel variance. We do this, however, in order to be able to get a detailed time series. Other RS datasets (such as Landsat) have higher spatial resolutions, but this comes at the expense of temporal resolution. Because our aim was to integrate survey data, which we have over a 12 year period, with RS data using the NDVI small integral, which requires detailed time series data, we feel that this trade-off is justified. Looking now at our socio-economic indicators, both commercialization and pluriactivity are statistically significant (p < 0.05 and p < 0.001 respectively); however, the distance indicator is not significant. 5 A unit increase in commercialization is expected to result in an almost 60 per cent increase in yields, controlling for other factors. However, since commercialization is defined as a ratio, this implies an unrealistic change between zero and unity. To clarify, increasing commercialization from, for example, 0.5 to 0.6 (one tenth of a unit) is expected to result in a relative change in village yield of 5.9 per cent. 6 This result reflects the differences in land productivity between highly commercialized villages and those more oriented to subsistence production. 7 Unlike the relationship with commercialization, the relationship between pluractivity and yields is a negative one. A unit increase in the pluriactivity rate of a village is expected to be associated with approximately 30 per cent lower yields than otherwise. Similar to commercialization, pluriactivity is a ratio variable so, again, looking more specifically at increasing pluriactivity from 0.5 to 0.6 (one tenth of a unit), for instance, would give a relative negative change in village yield of 6.6 per cent. 8,9 Here we see that villages with a high share of households drawing on non-farm sources of income may be more oriented to subsistence production than villages focused on maize production where farmers may dedicate more time and resources to trying to increase maize yields since this is their main source of income. Like commercialization and pluriactivity, travel time to the nearest major market was expected to be significantly associated with yield levels; however, in the current model we find that travel time is not statistically significant, even when the other socio-economic variables are removed from the model. One possible explanation for the discrepancy between the observed findings and those expected based on previous studies may be that the lag time is too long, since the travel time is estimated under conditions prevailing in the year 2000. Much can have changed since then, both in terms of urbanization, in the size of towns neighbouring our villages, and in the infrastructure connecting the villages to major markets. Another possibility is that the distance indicator is collinear with the rates of commercialization and pluriactivity. This, however, is less likely, since running separate models for each panel period shows substantially the same results. 10 In terms of change over time, the period dummies in the multivariate model are both statistically significant. The regression coefficients should be interpreted in comparison to the reference Thus, the multivariate analysis highlights a trend in yields, which was not apparent in the bivariate analysis or analysis of the descriptive statistics. 11 Some of the above results tally well with those shown in several previous publications using the same Afrint data, mainly that socio-economic factors such as commercialization and pluriactivity have a strong impact on yields ;Djurfeldt et al.,, 2008). In other words, if our sample is representative of wider trends, market integration drives the development of smallholder agriculture in SSA. Biophysical and farm management factors, as reflected in the NDVI small integral, apparently neither prevent nor encourage this development to a significant level. Conclusion The purpose of this paper was to measure the impact of different socio-economic and biophysical factors on maize yields using a combination of RS data and household survey data. We evaluated the relationship between the NDVI small integral during the growing season, commercialization, pluriactivity and distance to market and variation in maize yields during a 12 year period from 2002 to 2013. We find that, on average, the NDVI in areas managed by farmers (cropped pixel) is not significantly different from that in less managed areas (reference pixel). We also find that, while a significant positive relationship between the NDVI small integral and maize yields exists, it is weak, when examined individually. When examined along with socio-economic indicators, the weak significant relationship persists, but now we find that there is a stronger relationship between commercialization and pluriactivity and maize yields. Contrary to expectations, we find no significant relationship with distance to market. We conclude that, at this scale of analysis, changes in biomass production, due to both biophysical conditions such as rainfall and temperature, and soil conditions driven by both these conditions and management factors, do not drive changes in yields to a significant level. Instead, trends in maize yields are more predominantly driven by socio-economic factors, like commercialization or market integration and rates of pluriactivity. Thus, yield estimation models focusing on biophysical drivers of yields while neglecting other drivers are likely to overestimate the effects of the former on yields. Models of yield estimation would thus benefit greatly from accounting for not only biophysical drivers of yield variation but also the socio-economic context within which maize is grown and harvested. Notes 1. In the third round, data for four of the six countries was collected in 2013. The data for Mozambique and Tanzania was collected in 2015 instead of 2013. The third round of data collection will be referred to as 2013 in this study. 2. A second, more elaborate multivariate model containing fixed country effects for three of the independent variables (panel period, pluriactivity and commercialization) was also developed. Details have been excluded here; however, it has been included in Table A1. In instances where the findings from the first multivariate are modified by the second, this has been identified in a footnote. 3. As pointed out, in effect only year 2002. 4. The second multivariate model in Table A1 brings the variance between countries to light. Here the variance between several countries is statistically significant for a number of variables. 5. The second multivariate model in Table A1 shows a significant negative association between distance to market and yield. One way to interpret this is that differences between countries with small distances and good infrastructure and others are masked in the model above. 6. exp(0.058) -1 = 5.9%. 7. Here Mozambique and also Zambia pull down the positive value of the regression coefficient, perhaps because the former country is more subsistence-oriented. In the case of Zambia, the heavy dependence of maize production on government purchasing policy is possibly an explanation for the deviant pattern. 8. exp(0.068) -1 = 6.6%. 9. The generally negative effect of pluriactivity on yields ( = −0.68) is masked somewhat by Malawi and to a smaller extent by Zambia. Referring to Djurfeldt, Djurfeldt, Hall, and Archila Bustos a possible explanation is that the former country is less affected by the agrarian change driven by the structural transformation in the other countries since 2002. As noted in footnote 7, Zambia may be exceptional due to its State-dominated purchasing policy for maize. 10. The second multivariate model in Table A1 does, however, as previously mentioned, show a significant negative association between travel time and yields. This is more in line with the expected patterns. 11. Malawi is a deviant country and pulls down the general effects and the regression coefficients for panel 2 and 3. In other words, stagnation in Malawi somewhat masks the overall progress in yields in the five other countries.
|
<gh_stars>1-10
#pragma once
#include "Base.h"
NAMESPACE(Engine)
class GameObject;
class Layer final :
public Base
{
private:
protected:
public:
explicit Layer(void) {};
virtual ~Layer(void) {};
std::unordered_map<std::wstring, std::list<GameObject*>> gameobjectgroup;
void AddGameObject(const std::wstring& _objectKey, GameObject* _object);
void Update(const FLOAT& dt);
void LateUpdate(const FLOAT& dt);
void ResetDevice(void);
void LostDevice(void);
void Free(void) override;
};
END
|
def _prepare_exchange_diff_partial_reconcile(self, aml, line_to_reconcile, currency):
if aml.currency_id:
residual_same_sign = aml.amount_currency * aml.amount_residual_currency >= 0
else:
residual_same_sign = aml.balance * aml.amount_residual >= 0
if residual_same_sign:
debit_move_id = line_to_reconcile.id if aml.credit else aml.id
credit_move_id = line_to_reconcile.id if aml.debit else aml.id
else:
debit_move_id = aml.id if aml.credit else line_to_reconcile.id
credit_move_id = aml.id if aml.debit else line_to_reconcile.id
return {
'debit_move_id': debit_move_id,
'credit_move_id': credit_move_id,
'amount': abs(aml.amount_residual),
'amount_currency': abs(aml.amount_residual_currency),
'currency_id': currency and currency.id or False,
}
|
<reponame>walkinsky8/nana-runner<filename>runa/base/mt_mutex.h
/**
* Runa C++ Library
* Copyright (c) 2017-2019 walkinsky:lyh6188(at)hotmail(dot)com
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
// Created on 2018/11/04
#pragma once
#include <runa/base/_config.h>
#include <mutex>
namespace runa { namespace mt {
using std::mutex;
}}
|
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
package com.mediatek.bluetooth.ftp;
import com.mediatek.bluetooth.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
/* This activity is launched for FTP-server-authorizing and FTP-server-connected notification. */
public class BluetoothFtpServerNotify extends Activity
implements DialogInterface.OnClickListener {
private static final String TAG = "BluetoothFtpServerNotify";
private boolean isDone = false;
private AlertDialog mDialog;
private String mDeviceName;
private int mNotifyType;
private IBluetoothFtpServerNotify mServerNotify = null;
private ServiceConnection mFtpServerNotifyConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mServerNotify = IBluetoothFtpServerNotify.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
}
};
private IntentFilter mFilter = new IntentFilter(BluetoothFtpService.SERVER_DISCONNECTED);
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "onReceive()");
forceExit();
}
};
private OnCancelListener mCancelListener = new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
finish();
}
};
private AlertDialog buildDialog(int type, String deviceName) {
Builder builder = new Builder(this);
String msg = null;
int icon_id = 0, title_id = 0, positive_id = 0, negative_id = 0;
if (type == BluetoothFtpService.FTPS_AUTHORIZE_NOTIFY) {
icon_id = android.R.drawable.ic_dialog_info;
title_id = R.string.bluetooth_ftp_server_authorize_title;
msg = String.format(
getString(R.string.bluetooth_ftp_server_authorize_message),
deviceName);
positive_id = R.string.bluetooth_ftp_server_authorize_allow;
negative_id = R.string.bluetooth_ftp_server_authorize_decline;
} else if (type == BluetoothFtpService.FTPS_CONNECTED_NOTIFY) {
icon_id = android.R.drawable.ic_dialog_info;
title_id = R.string.bluetooth_ftp_server_disconnect_title;
msg = String.format(
getString(R.string.bluetooth_ftp_server_disconnect_message),
deviceName);
positive_id = R.string.bluetooth_ftp_yes;
negative_id = R.string.bluetooth_ftp_no;
} else {
Log.e(TAG, "Invalid notification type: " + type);
forceExit();
}
builder.setIcon(icon_id)
.setTitle(title_id)
.setMessage(msg)
.setPositiveButton(positive_id, this)
.setNegativeButton(negative_id, this)
.setOnCancelListener(mCancelListener);
return builder.create();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Log.d(TAG, "onCreate()");
Intent intent = getIntent();
mNotifyType = intent.getIntExtra(BluetoothFtpService.NOTIFY_TYPE, -1);
mDeviceName = intent.getStringExtra(BluetoothFtpService.DEVICE_NAME);
if (mNotifyType == -1) {
Log.e(TAG, "Notification type is not assigned.");
forceExit();
}
mDialog = buildDialog(mNotifyType, mDeviceName);
bindService(new Intent(IBluetoothFtpServerNotify.class.getName()),
mFtpServerNotifyConn, Context.BIND_AUTO_CREATE);
registerReceiver(mReceiver, mFilter);
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume()");
mDialog.show();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause()");
mDialog.dismiss();
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop()");
if (!isDone) {
updateNotification();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
unregisterReceiver(mReceiver);
unbindService(mFtpServerNotifyConn);
}
private void sendAuthResult(boolean res) {
// Log.d(TAG, "Authorize: " + (res ? "Allow" : "Reject"));
try {
mServerNotify.authResult(res);
} catch (Exception ex) {
Log.e(TAG, "authResult() failed.");
}
forceExit();
}
private void sendDisconnect() {
// Log.d(TAG, "Disconnect from notification");
try {
mServerNotify.disconnect();
} catch (Exception ex) {
Log.e(TAG, "disconnect() failed.");
}
forceExit();
}
private void updateNotification() {
try {
mServerNotify.updateNotify(mNotifyType);
} catch (Exception ex) {
Log.e(TAG, "updateNotification() failed.");
finish();
}
}
private void forceExit() {
isDone = true;
finish();
}
/* Functions for DialogInterface.OnClickListener */
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Log.d(TAG, "Positive button pressed.");
if (mNotifyType == BluetoothFtpService.FTPS_AUTHORIZE_NOTIFY) {
sendAuthResult(true);
} else {
sendDisconnect();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
Log.d(TAG, "Negative button pressed.");
if (mNotifyType == BluetoothFtpService.FTPS_AUTHORIZE_NOTIFY) {
sendAuthResult(false);
} else {
finish();
}
break;
default:
break;
}
}
}
|
def run_crashed(self,datadir):
crash = datadir+"/crash.dat.0"
store = datadir+"/store.dat.0"
return os.path.exists(datadir+"/crash.dat.0") and os.stat(crash).st_mtime > os.stat(store).st_mtime
|
Machine translation is a sub-field of computational linguistics in which software is used to translate text (or speech) from one natural language to another. In its basic form, machine translation systems perform simple substitution of words in one language for words in another, but more sophisticated systems may use corpus and statistical techniques for improved recognition of whole phrases. Examples of existing web-based translation systems include Google Translate and Bing Translator.
Conventional translators allow manual text translation and/or webpage translation. With text translation, the user must navigate to the webpage of the translator, select a translation language from a “Languages” drop down box, then type or paste text to be translated into an “Enter text or webpage” box, and then click a “Translate” button to activate the translation. With Web page translation, the user performs the same steps except the user enters a URL of a webpage in the “Enter text or webpage” box instead of text. In some systems, the original language of the text or webpage can be automatically detected by the translation software. Further, Google Translate offers a service where visitors to a webpage have the option to view a translated version of a website.
While the automatic translation of an entire text (or selection thereof) or an entire webpage may be valuable to users, existing systems fail to take into account user language preferences for different types of content when browsing the Internet or even within a website. Many multi-language users, for example, may prefer to read different types of content in different languages.
Accordingly, it would be desirable to provide automatic machine translation of a text into multiple languages
|
Responding to an open records request, the CTA said between January of 2017 to May 2018, there were 471 disruptions of 10 minutes or longer.
Anyone who’s ever been stuck on a stopped el train knows it’s not a pleasant experience. Number one, you’re getting nowhere fast. Then there’s the fact you are cooped up in a metal tube with total strangers for an indeterminate amount of time.
The CTA says it knows that---and they share your pain.
He’s right. Out of the hundreds of thousands of miles traveled by CTA trains during any given year---an actual stopped train doesn’t happen that often.
But an analysis by NBC 5 shows that it does happen on Blue Line trains more than all others.
Responding to an open records request, the CTA said between January of 2017 to May 2018, there were 471 disruptions of 10 minutes or longer. Of those 469 breakdowns, 162 were on the Blue Line. The Red Line was second with 94, followed by the Green with 55.
“First and foremost, the Blue Line is our second busiest line---it’s also our longest rail line,” Steele said. Plus---it’s also the line which may have gotten the least amount of TLC in recent years.
Steele likened the Blue to a road filled with potholes---leading to slow zones, and a lot of wear and tear.
What about the causes of breakdowns? The CTA data showed the number one issue is brakes.
The second leading cause of disruptions is doors, followed by train propulsion systems.
It’s important to note that CTA trains make some 12 thousand trips in a given week, and most take place without incident. And it would only be fair to argue that if you are really unhappy with having to sit next to that guy playing the saxophone in a stopped train---you might want to take it up with Springfield.
“Since 2011, the CTA has completed, announced, or begun over $8 billion in modernization projects,” Steele notes. But he also points out that the State of Illinois hasn’t managed a capital bill since 2009. And the Civic Federation said in a recent report, that the CTA’s “state of good repair” backlog is approaching $13 billion.
Indeed, that same Civic Federation report warned that the CTA will need over $23 billion over 10 years just to address its backlogged needs.
Steele notes another issue which prevents the addition of more trains on the Blue Line: power. Anyone who has tried to plug too many appliances into the kitchen counter, knows there are only so many watts to go around.
One other note. A 2016 report shows that the CTA manages over 22,000 miles between major mechanical failures, even though 25 percent of its vehicles are now classified as “beyond their useful life”. But even that put Chicago in fifth place among America’s mass transit systems. Philadelphia and Houston both say at least 39 percent of their rolling stock is obsolete.
From January 2017 to May 2018, the CTA had 469 disruptions of 10 minutes or longer. Here they are, by line, and by cause.
|
<gh_stars>0
version https://git-lfs.github.com/spec/v1
oid sha256:d30245856ce451965c5dda464d934fc31b86ea0f76eeeb0ed1ddb137059a9757
size 2207
|
package socialnetwork.controller;
import javafx.fxml.FXML;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import socialnetwork.controller.imageViewController.ImageViewUserProfileController;
import socialnetwork.domain.ProfilePhotoUser;
import socialnetwork.domain.User;
import socialnetwork.service.FriendshipService;
import socialnetwork.service.ProfilePhotoUserService;
import socialnetwork.service.UserService;
import socialnetwork.utils.ChangeProfilePhoto;
import socialnetwork.utils.ChangeProfilePhotoRectangle;
import socialnetwork.utils.ChangeProfilePhotoRound;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class UserProfileController {
private ProfilePhotoUserService profilePhotoUserService;
private UserService userService;
private FriendshipService friendshipService;
private ImageViewUserProfileController imageViewUserProfileController = new ImageViewUserProfileController();
private User user;
private Stage userProfileStage;
@FXML
ImageView imageViewUserProfile;
@FXML
ImageView imageViewStUser;
@FXML
ImageView imageViewNdUser;
@FXML
ImageView imageViewRdUser;
@FXML
ImageView imageView4thUser;
@FXML
Label labelUserName;
@FXML
void initialize() {
}
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* @param user User, representing the new User
*/
void setUser(User user) {
this.user = user;
imageViewUserProfileController.setUser(this.user);
labelUserName.setText(user.getFirstName() + " " + user.getLastName());
}
public void setProfilePhotoUserService(ProfilePhotoUserService profilePhotoUserService) {
this.profilePhotoUserService = profilePhotoUserService;
this.profilePhotoUserService.addObserver(imageViewUserProfileController);
imageViewUserProfileController.setProfilePhotoUserService(this.profilePhotoUserService);
}
public void setUserProfileStage(Stage userProfileStage) {
this.userProfileStage = userProfileStage;
}
public ImageView getImageViewUserProfile() {
return imageViewUserProfile;
}
public void initializeUserProfile() {
if (user != null) {
ChangeProfilePhotoRound changeProfilePhotoRound = new ChangeProfilePhotoRound();
changeProfilePhotoRound.changeProfilePhoto(profilePhotoUserService, imageViewUserProfile, user);
imageViewUserProfileController.setImageViewUserProfile(imageViewUserProfile);
List<Long> idsFriends = new ArrayList<>();
userService.getAllFriends(user.getId()).forEach(friendUser -> idsFriends.add(friendUser.getId()));
Collections.shuffle(idsFriends);
User stUserFriend = null, ndUserFriend = null, rdUserFriend = null, fourthUserFriend = null;
if (idsFriends.size() >= 1)
stUserFriend = userService.getUser(idsFriends.get(0));
if (idsFriends.size() >= 2)
ndUserFriend = userService.getUser(idsFriends.get(1));
if (idsFriends.size() >= 3)
rdUserFriend = userService.getUser(idsFriends.get(2));
if (idsFriends.size() >= 4)
fourthUserFriend = userService.getUser(idsFriends.get(3));
ChangeProfilePhoto changeProfilePhoto = new ChangeProfilePhotoRectangle();
if (stUserFriend != null) {
changeProfilePhoto.changeProfilePhoto(profilePhotoUserService, imageViewStUser, stUserFriend);
} else {
imageViewStUser.setVisible(false);
}
if (ndUserFriend != null) {
changeProfilePhoto.changeProfilePhoto(profilePhotoUserService, imageViewNdUser, ndUserFriend);
} else {
imageViewNdUser.setVisible(false);
}
if (rdUserFriend != null) {
changeProfilePhoto.changeProfilePhoto(profilePhotoUserService, imageViewRdUser, rdUserFriend);
} else {
imageViewRdUser.setVisible(false);
}
if (fourthUserFriend != null) {
changeProfilePhoto.changeProfilePhoto(profilePhotoUserService, imageView4thUser, fourthUserFriend);
} else {
imageView4thUser.setVisible(false);
}
}
}
public void changeProfilePhotoEvent() {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File("C:\\Users\\dasco\\OneDrive\\Pictures\\ProfilePhotos"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png"),
new FileChooser.ExtensionFilter("JPG Files", "*.jpg"));
File file = fileChooser.showOpenDialog(userProfileStage);
if (file != null) {
String pathProfilePhoto = file.toString();
ProfilePhotoUser newProfilePhotoUser = new ProfilePhotoUser(pathProfilePhoto);
newProfilePhotoUser.setId(user.getId());
profilePhotoUserService.updateProfilePhotoUser(newProfilePhotoUser);
ChangeProfilePhotoRound changeProfilePhotoRound = new ChangeProfilePhotoRound();
changeProfilePhotoRound.changeProfilePhoto(profilePhotoUserService, imageViewUserProfile, user);
}
}
}
|
INTERNATIONAL – Apple is buying the power-management technology at the heart of its iPhones in a $600 million ( R8,7bn) deal with Dialog Semiconductor that also secures the German-listed company’s role as a supplier to the US tech giant.
The agreement to acquire patents and people from the Anglo-German chip designer is not only unusual, but also the largest of its kind by Apple, whose last sizeable acquisition was the $350 million purchase of Face ID creator PrimeSense in 2013.
Dialog shares surged as much as 34 percent on Thursday, their most since 2002, as the deal bought the company time to reduce its dependence on Apple - which it expects to account for three-quarters of this year’s sales.
Dialog’s shares had tumbled earlier this year when it said Apple planned to use chips from another supplier.
Dialog Chief Executive Jalal Bagherli told Reuters he could now lead a “managed, smooth” transformation of the business as Dialog seeks new opportunities in areas such as the Internet of Things that includes connected devices like home speakers, fitness trackers or smartwatches.
Since the first iPhones a decade ago, Apple has used Dialog power-management chips to extend their battery life. Under the deal, Apple is buying patents, a 300-strong engineering team, most of whom already worked on chips for Apple devices, and Dialog offices in Britain, Italy and Germany.
Dialog said its 2018 revenue would not be affected and it would continue shipments of existing main power management integrated circuits (PMICs) to Apple. It expects to sell current and future generations of so-called sub-PMICs to Apple.
Bagherli said that Apple increasingly viewed the main PMICs, which are central to the operation of its devices, as a strategic element that it wanted to control directly. This was not the case for sub-PMICs that manage features such as onboard cameras, he told Reuters.
After the deal, Dialog expects Apple to account for 35-40 percent of its total revenues in 2022. That is down from around 75 percent in the current year. Headcount will fall to 1,800.
The chipmaker also said it would begin a share buyback program for up to 10 percent of its stock following its next quarterly trading update.
The $600 million windfalls will add to Dialog’s already-healthy net cash position of $525 million, analysts said.
Other chip designers in Europe have struggled to manage their relationship with Apple due to its sheer scale. Britain’s Imagination Technologies ended up being sold to a Chinese-backed fund last year after losing Apple as a client.
“Dialog has bought itself much more than just time,” said Karsten Iltgen, an analyst at Bankhaus Lampe, which rates the stock ‘buy’.
Half of the deal’s value, or about $300 million, is cash for the Dialog engineers and offices and the other $300 million is pre-payment to Dialog for supplying chips over the next three years, the companies said.
Dialog said it would continue to deliver chips to other customers, focusing on the automotive and internet-of-things markets, among others.
It forecast that its sub-PMIC business would achieve compound annual growth rates of 30-35 percent between 2018 and 2022. Its AMS, Connectivity and Automotive & Industrial business would grow at a 10-15 percent rate.
The deal represents an expansion of Apple’s chip design operations, which kicked into high gear in 2010 when the company released its first custom processor for the iPad and iPhone.
Apple is buying about 16 percent of Dialog’s workforce. Apple said these employees would stay in Europe and would report to Johny Srouji, the company’s senior vice president of hardware technologies who oversees Apple’s chip design efforts.
“Our relationship with Dialog goes all the way back to the early iPhones, and we look forward to continuing this long-standing relationship with them,” Srouji said. Apple has added around 20,000 employees in Europe since 2000. It already has a chip design center in Munich, Germany, where it employs 1,000 staff, and St Albans, Britain. The deal will give Apple four more from Dialog, in Livorno in Italy, Swindon in Britain, and Nabern and Neuaubing in Germany.
The transaction is expected to close in the first half of 2019, subject to customary closings and regulatory approvals, Dialog said. It expects annual operational savings of $35 million from the deal but declined to give more detail on its financial impact ahead of an investor presentation on Nov. 1.
Dialog said Qatalyst Partners acted as its financial adviser and Linklaters as its legal counsel.
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from nasbench import api
import numpy as np
import pandas as pd
import json
import tensorflow as tf
import os
NASBENCH_TFRECORD = '../../nasbench-master/dataset/nasbench_only108.tfrecord'
dest = './dataset/destfile'
INPUT = 'input'
OUTPUT = 'output'
CONV1X1 = 'conv1x1-bn-relu'
CONV3X3 = 'conv3x3-bn-relu'
MAXPOOL3X3 = 'maxpool3x3'
def get_all_data(data_dir):
# Load whole nasbench dataset
nasbench = api.NASBench(data_dir)
# Load the mapping from graph to accuracy
dataMap = nasbench.get_maping()
return dataMap
def matrix_eq_comp(mat1, mat2):
inters = np.intersect1d(mat1, mat2)
bc1 = np.bincount(mat1)
bc2 = np.bincount(mat2)
same_count_list = [min(bc1[x], bc2[x]) for x in inters]
same_count = sum(same_count_list)
return same_count
dataMapping = get_all_data(NASBENCH_TFRECORD)
adj0 = np.array(np.array(dataMapping[0]['module_adjacency']).reshape(1, -1)[0])
adj1 = np.array(np.array(dataMapping[1]['module_adjacency']).reshape(1, -1)[0])
# op0 = np.array(dataMapping[0]['module_operations'])
# op1 = np.array(dataMapping[1]['module_operations'])
# inters = np.intersect1d(adj0, adj1)
# bc1 = np.bincount(adj0)
# bc2 = np.bincount(adj1)
# same_count_list = [min(bc1[x], bc2[x]) for x in inters]
# same_count = sum(same_count_list)
# count = sum(adj0 != adj1) + sum(op0 != op1)
# print(same_count_list)
# print(same_count)
print(np.sum(adj0 == adj1))
# print(type(adj0))
# print(type(adj1))
|
/**
* <p>
* Event triggered to report the progress of an asynchronous operation
* </p>
* @param iUpperBound Mandatory int parameter.
* @param iCurrent Mandatory int parameter.
* @param strMessage Mandatory java.lang.String parameter.
* @param objWbemAsyncContext Mandatory com4j.typelibs.wmi.ISWbemNamedValueSet parameter.
*/
@DISPID(3)
public void onProgress(
int iUpperBound,
int iCurrent,
java.lang.String strMessage,
com4j.typelibs.wmi.ISWbemNamedValueSet objWbemAsyncContext) {
throw new UnsupportedOperationException();
}
|
/**
* @author Mik Kersten
*/
class PointcutWizard extends JFrame {
private static final long serialVersionUID = -9058319919402871975L;
// private BrowserViewPanel typeTreeView = null;
// private java.util.List signatures = null;
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JPanel jPanel4 = new JPanel();
JLabel jLabel1 = new JLabel();
BorderLayout borderLayout1 = new BorderLayout();
BorderLayout borderLayout2 = new BorderLayout();
BorderLayout borderLayout3 = new BorderLayout();
JLabel jLabel4 = new JLabel();
JPanel jPanel3 = new JPanel();
JCheckBox jCheckBox5 = new JCheckBox();
JCheckBox jCheckBox4 = new JCheckBox();
JCheckBox jCheckBox3 = new JCheckBox();
JCheckBox jCheckBox2 = new JCheckBox();
JCheckBox jCheckBox1 = new JCheckBox();
JButton cancel_button = new JButton();
JButton ok_button = new JButton();
JPanel jPanel5 = new JPanel();
public PointcutWizard(java.util.List signatures) {
// this.signatures = signatures;
ArrayList views = new ArrayList();
views.add(StructureViewProperties.Hierarchy.INHERITANCE);
// typeTreeView = new BrowserViewPanel(AjdeUIManager.getDefault().getIconRegistry(), views, StructureViewProperties.Hierarchy.INHERITANCE);
throw new RuntimeException("unimplemented, can't get the current file");
//typeTreeView.updateTree(Ajde.getDefault().getEditorManager().getCurrFile());
// try {
// jbInit();
// }
// catch(Exception e) {
// Ajde.getDefault().getErrorHandler().handleError("Could not initialize GUI.", e);
// }
// this.setSize(400, 400);
// this.setIconImage(((ImageIcon)AjdeUIManager.getDefault().getIconRegistry().getStructureSwingIcon(ProgramElementNode.Kind.POINTCUT)).getImage());
}
// private Map getViewProperties() {
// Map views = new HashMap();
// GlobalViewProperties INHERITANCE_VIEW = new GlobalViewProperties(StructureViewProperties.Hierarchy.INHERITANCE);
//// INHERITANCE_VIEW.addRelation(IRelationship.Kind.INHERITANCE);
//// views.put(INHERITANCE_VIEW.toString(), INHERITANCE_VIEW);
// return views;
// }
//
// private void jbInit() throws Exception {
// jLabel1.setFont(new java.awt.Font("Dialog", 0, 11));
// jLabel1.setText("Generate pointcut designator for corresponding joinpoints:");
// jPanel1.setLayout(borderLayout1);
// jPanel4.setLayout(borderLayout2);
// jPanel2.setLayout(borderLayout3);
// jLabel4.setText("Select the target type that will host the generated pointcut:");
// jLabel4.setFont(new java.awt.Font("Dialog", 0, 11));
// jLabel4.setToolTipText("");
// jPanel3.setMaximumSize(new Dimension(32767, 34));
// jCheckBox5.setEnabled(false);
// jCheckBox5.setFont(new java.awt.Font("Dialog", 0, 11));
// jCheckBox5.setSelected(true);
// jCheckBox5.setText("call");
// jCheckBox4.setEnabled(false);
// jCheckBox4.setFont(new java.awt.Font("Dialog", 0, 11));
// jCheckBox4.setText("execution");
// jCheckBox3.setEnabled(false);
// jCheckBox3.setFont(new java.awt.Font("Dialog", 0, 11));
// jCheckBox3.setText("initialization");
// jCheckBox2.setEnabled(false);
// jCheckBox2.setFont(new java.awt.Font("Dialog", 0, 11));
// jCheckBox2.setText("static initialization");
// jCheckBox1.setEnabled(false);
// jCheckBox1.setFont(new java.awt.Font("Dialog", 0, 11));
// jCheckBox1.setText("field get/set");
// cancel_button.setFont(new java.awt.Font("Dialog", 0, 11));
// cancel_button.setText("Cancel");
// cancel_button.addActionListener(new java.awt.event.ActionListener() {
// public void actionPerformed(ActionEvent e) {
// cancel_button_actionPerformed(e);
// }
// });
// ok_button.setText("OK");
// ok_button.addActionListener(new java.awt.event.ActionListener() {
// public void actionPerformed(ActionEvent e) {
// ok_button_actionPerformed(e);
// }
// });
// ok_button.setFont(new java.awt.Font("Dialog", 0, 11));
// this.setTitle("Pointcut Wizard");
// this.getContentPane().add(jPanel1, BorderLayout.CENTER);
// jPanel1.add(jPanel4, BorderLayout.NORTH);
// jPanel4.add(jLabel1, BorderLayout.NORTH);
// jPanel4.add(jPanel3, BorderLayout.CENTER);
// jPanel3.add(jCheckBox5, null);
// jPanel3.add(jCheckBox4, null);
// jPanel3.add(jCheckBox3, null);
// jPanel3.add(jCheckBox2, null);
// jPanel3.add(jCheckBox1, null);
// jPanel1.add(jPanel2, BorderLayout.CENTER);
// jPanel2.add(jLabel4, BorderLayout.NORTH);
// jPanel2.add(typeTreeView, BorderLayout.CENTER);
// jPanel1.add(jPanel5, BorderLayout.SOUTH);
// jPanel5.add(ok_button, null);
// jPanel5.add(cancel_button, null);
// }
// private void ok_button_actionPerformed(ActionEvent e) {
// throw new RuntimeException("unimplemented, can't paste");
//// Ajde.getDefault().getEditorManager().pasteToCaretPos(generatePcd());
//// this.dispose();
// }
//
// private void cancel_button_actionPerformed(ActionEvent e) {
// this.dispose();
// }
//
// private String generatePcd() {
// String pcd = "\n\n" +
// " pointcut temp(): \n";
// for (Iterator it = signatures.iterator(); it.hasNext(); ) {
// pcd += " call(* " + it.next() + ")";
// if (it.hasNext()) {
// pcd += " ||";
// } else {
// pcd += ";";
// }
// pcd += "\n";
// }
// return pcd;
// }
}
|
A state of emergency has been declared in the city of Dallas, Texas as it struggles to contain an outbreak of mosquito-borne West Nile virus.
Residents have been urged to use insect repellent and avoid going out at dusk and dawn.
The BBC reports the declaration clears the way for aerial spraying to kill infected mosquitoes that transmit the disease.
At least 14 people are dead after contracting the virus in the state so far this year.
Almost 700 cases have been reported in 42 states - the highest number since 2004. Texas, Mississippi and Oklahoma represent 80% of the cases.
The virus was first discovered in 1937 in Uganda. It is carried by birds and spread to humans by mosquitoes.
|
Cathy O'Dowd
Cathy O'Dowd (born 1968) is a South African rock climber, mountaineer, author and motivational speaker. She was the first woman to reach the summit of Mount Everest from both south (25 May 1996) and north sides (29 May 1999).
O’Dowd grew up in Johannesburg, South Africa, and attended St. Andrew's School for Girls. She has climbed since her university days. At 21 she took part in her first mountain expedition, to the Ruwenzori in central Africa.
Southeast ridge route
Towards the end of 1995, O'Dowd was finishing a master's degree in Media Studies at Rhodes University when she applied for and got a place on the First South African Everest Expedition. On 11 May 1996, eight climbers died in a severe blizzard on their descent from the summit on the south side. This included a climbing guide and the leaders of two expeditions, American Scott Fischer and the New Zealander Rob Hall. O'Dowd was at the high camp just below the southeast ridge preparing to summit with her expedition when the blizzard struck, forcing the team to delay the summit attempt. She finally reached the summit on 25 May 1996. One member of the South African party, 37-year-old Bruce Herrod, died on the descent. His body was discovered the following year by an Indonesian expedition party led by Anatoli Boukreev.
North ridge route
In 1998 she attempted the north side of Everest, where George Mallory had disappeared in 1924. Her attempt ended hours from the summit when she came across Francys Arsentiev, an American climber who had collapsed. They attempted to help her for over an hour but were forced to turn around and descend, leaving Arsentiev behind. Two of the Sherpas went on to the summit. She described this decision to Michael Buerk on the BBC Radio 4 programme 'The Choice' aired in November 2009.
In 1999 she returned, and on this occasion succeeded, becoming the first woman to climb Everest from both north and south sides. In 2000, she became the fourth woman to climb Lhotse, the world's fourth highest mountain.
East face route
In 2003, she made an unsuccessful attempt at a new route up the east face of Everest.
Other expeditions
In the spring of 2004 she joined British woman Rona Cant and Norwegian Per-Thore-Hansen on a dog-sled expedition of 650 km through the Norwegian Arctic, from Styggedalen to Nordkapp, the most northerly point in Europe.
Cathy O'Dowd has climbed mountains across southern and central Africa, in South America, in the Alps and in the Himalaya. She remains an active mountaineer, rock-climber and skier.
She married the First South African Everest Expedition leader Ian Woodall in 2001 and lives in Andorra in the Pyrenees.
|
import features from '../libs/features';
import interact from 'interactjs';
import select from 'select-dom';
async function init() {
interact('.aui-sidebar-wrapper')
.resizable({
edges: {
top: false, // Use pointer coords to check for resize.
left: false, // Disable resizing from left edge.
bottom: false, // Resize if pointer target matches selector
right: true, // Resize if pointer target is the given Element
},
})
.on('resizemove', event => {
let x = event.target.dataset;
x = parseFloat(x) || 0;
Object.assign(event.target.style, {
width: `${event.rect.width}px`,
transform: `translate(${event.deltaRect.left}px, ${event.deltaRect.top}px)`,
});
Object.assign(event.target.dataset, x);
select(
'.aui-sidebar~.aui-page-panel'
).style.paddingLeft = `${event.rect.width}px`;
});
}
features.add({
id: 'project-resizable-nav',
include: [features.isProject],
load: features.onDomReady,
init,
});
|
Google Voice is great, especially if you’re on a mobile platform that offers a native Voice application (namely Android or BlackBerry). But if you’ve been using the service on a regular basis, you may have run into an odd issue: sometimes when you go to actually call someone there’s a lag, as if the phone isn’t altogether sure what it’s supposed to do when you tap on the ‘Call’ button next to a contact’s name. Today, Google is getting rid of that lag in its native applications.
As Google details in its blog post, that pause was due to Google Voice making a small data request to Google’s servers whenever you initiated a call, which would return the number the application was supposed to dial. That works well enough when you have a decent 3G or EDGE connection, but it can also lead to annoying timeouts and pauses when you don’t. The new version of the Voice applications fixes this by assigning a unique phone number to your contacts, bypassing the need to initiate a data connection. In other words, your outbound calls should be faster now.
Disclosure: The Google Voice team has ported my cell number over to the service, as they did with Michael’s number.
|
Effect of Different Illumination Sources on Reading and Visual Performance Purpose: To investigate visual performance during reading under different illumination sources. Methods: This experimental quantitative study included 40 (20 females and 20 males) emmetropic participants with no history of ocular pathology. The participants were randomly assigned to read a near visual task under four different illuminations (400-lux constant): compact fluorescent light (CFL), tungsten light (TUNG), fluorescent tube light (FLUO), and light emitting diode (LED). Subsequently, we evaluated the participants experiences of eight symptoms of visual comfort. Results: The mean age of the participants was 19.86 ± 1.09 (range: 1821) years. There was no statistically significant difference between the reading rates of males and females under the different illuminations (P = 0.99); however, the reading rate was fastest among males under CFL, and among females under FLUO. One way analysis of variance (ANOVA) revealed a strong significant difference (P = 0.001) between males and females (P = 0.002) regarding the visual performance and illuminations. Conclusion: This study demonstrates the influence of illumination on reading rate; there were no significant differences between males and females under different illuminations, however, males preferred CFL and females preferred FLUO for faster reading and visual comfort. Interestingly, neither preferred LED or TUNG. Although energy-efficient, visual performance under LED is poor; it is uncomfortable for prolonged reading and causes early symptoms of fatigue. INTRODUCTION there is little consideration regarding their impact on visual comfort or ocular health. Berman et al provided evidence that scotopic rich fluorescent source illumination reduces pupil size and improves visual acuity; however, the effect was only measurable with low-contrast briefly-presented stimuli. Moreover, the chromaticity of light seems to influence visual stimuli; Yamagishi et al compared two groups (young and elderly subjects), and found that visual performance, mood, and subjects' perception of comfortable reading and visual task performance improved under artificial LED lighting. However, Nagy et al showed that differences in the spectral distribution of the ambient illumination also affect visual tasks like color and when the stimulants changed and presented on the monitor screen, they adapted to the ambient illumination. Color chromaticity also changes with LED illumination. Mott et al conducted a quasi-experiment, showing that, compared to natural lighting conditions, increasing the quality of artificial light positively affected students' oral reading performance in classrooms. Lin in et al studied the effect of illumination and chromatic contrast on reading performance; they found that white light was associated with better reading performance than yellow light and, thus, that light intensity, rather than color, significantly affected reading. Similarly, using various colors of LED lamps, Eo et al explored the effect of classroom lighting upon student psychology; the mood of music and art rooms were altered by different colors, and this illumination variance improved students' creativity (LED lamps created a more positive feeling than fluorescent lamps). Shieh and Lin showed the effect of ambient illumination and color on visual performance, using visual display terminal (VDT) screens; color performance and visual fatigue were less than illumination and color combined, and working on liquid crystal display (LCD) screens was less comfortable because of the slow accommodative velocity of users indirectly affecting visual comfort. Bowers et al explained how illumination influences reading performance in macular degeneration patients; the majority of patients required a task illumination of at least 2,000 lux to increase and achieve good reading performance. However, they concluded that an ideal illumination should be determined individually for each patient using both objective (such as reading acuity) and subjective assessments to achieve better visual comfort. Carver and Leibert suggested that measuring reading rate in standard words per minute compensates for changes in difficulty level across reading materials, depending on the nature of the reading task level and purpose, and that verbal reading rate is 50% slower than silent reading. However, further studies improved that verbal reading and silent speech is mostly used to aid memory during reading, and it is not active during skim-and-scan reading type of comprehension. Simonson and Brozek demonstrated the effect of illumination and visual fatigue; altering the illumination, above the optimal level, resulted in a decline in performance and an increase in fatigue. Owens et al reported that convergence was a more important distance cue than accommodation in low lighting conditions; convergence was more affected than accommodation. D'Zmura studied surface color changes in response to illumination, and found that the spectral properties of a trichromatic visual system recover three constant color reflectance descriptors per surface, if the color of the surface illuminant is changed. This variation in illumination creates color constancy. Legge and Bigelow examined reading print size, and provided evidence that print size is critical for clear reading. Succar et al showed that, among low vision patients, altering the illumination levels of visual tasks significantly affected their reading performance. The present study aims to investigate individual reading and visual performance under different lighting sources used in daily life. Participants This study was conducted in accordance with the Declaration of Helsinki, and approval by our Institutional Ethics Committee, School of Medical Sciences, at the University of Hyderabad, India. Forty participants, 20 males and 20 females, aged 18-21 years, were included. All participants were from the university student community, and were selected by quantitative random sampling. No monetary reward was provided for participation, written and verbal consent were obtained from all participants. The participant inclusion criteria were as follows: 1) emmetropia; 2) visual acuity of 6/6 in meters for distance and N 6 for near with a standard error (SE) of ≤±0.50 D; 3) good general health. In addition, participants who did not have the mentioned inclusion criteria and who had a history of ocular pathology and high refractive errors and illiterate subjects were excluded from our study. Experimental Apparatus and Setting The current study was divided into two phases: the preliminary examination and experimental phases can be seen in Figure 1. A digital photometer (model-HS1010, Taiwan Tai Shi TES Company, China) was used for measuring light intensity. The following four illumination sources were chosen: 1) compact fluorescent light (CFL), 12 watt, 3400-Kelvin color temperature; 2) fluorescent tube light (FLUO), 20 watt, 3000-Kelvin color temperature; 3) tungsten light (TUNG), 100 watt, 3000-Kelvin temperature; 4) LED, 8 watt, 3100-Kelvin color temperature. TUNG is warm white colors. An intensity 400 lux was kept constant across all four lighting sources, and monitored with digital photometer; this constant intensity was chosen based on various photometric standards provided by lighting institutes. An average of all the standards for a near visual reading task was taken. The luminous efficiency of the illumination sources was measured for the effectiveness of luminance, and the warm light composition (400-lux intensity) for specific reading tasks. Standards were followed, according to the International Lighting Commission Code of Industrial Engineering (CIE), to provide a psychophysical analog of radiance, known as luminance. A stopwatch (KadioModel KD-2004, La Kadio Company Ltd., China) was used to record reading times, and a reading pad (5 5 feet) was adjusted to hold the reading material. Ishihara color vision plates (38 th edition, Kanehara trading Inc., Tokyo, Japan) were used to assess color vision, and a Baily Lovie 10% Contrast Sensitivity Chart was used to measure contrast. Participants were well seated in a silent and ambient illuminated room. A reading task was placed 40 cm from the participants' eyes, under overhead illumination arranged 1 m from the reading material . Visual Stimuli Reading passages of equal readability scores were generated, according to a standardized psycholinguistic text readability consensus calculator software tool. The passages used for the near visual task were checked for validity and reliability using the software. The visual stimuli/passages were presented to the participants in 14 lines of Times Roman Numeral, 12-point, bold, black font, printed on a white non-glossy chart. The passages, of equal readability scores but different content, were randomly presented to participants to read under the four different illuminations. The passages were not repeated; each participant received different passages of equal readability scores. Passages were read aloud by the participants in the closed room, and checked by the experimenter for accuracy. Experimental Procedure The experimental procedures were performed in all four illumination-conditions (CFL, FLUO, TUNG, and LED). Passages were presented for reading under the four illuminations, after which contrast acuity was measured and the participant underwent color vision testing with the 17 Ishihara pseudo-isochromatic plates. A time gap of fifteen minutes was provided under each light source for adaptation purposes. This same procedure was repeated under all four illuminations to know the subjective response of participants. A closed-ended questionnaire feedback form relating to visual performance and symptoms , with yes and no options, was given to participants to assess their satisfaction levels and visual comfort under the four illumination sources. The questionnaire consists of nine validated questions of good reliability, assessed by the Cronbach's alpha test ( = 0.824), and an average contingency percentage (ACP) of 90%. All illumination source sequences were changed randomly, but the tests were undertaken systematically. Data Preparation and Statistical Analysis All the experimental data was stored using Microsoft Excel (version 2010, Microsoft Corporation limited, Washington, USA) software. GraphPad Prism (version 7, GraphPad Software, Inc., California) statistical software was used for the statistical analyses of normal distributions using Shapiro-Wilk's tests. One-way analyses of variance (ANOVA) were used to explore the differences between all four illumination sources. Reliability and validity of the questionnaire data was assessed using Cronbach's alpha tests and ACPs calculated using SPSS (version 19, IBM Corporation, New York, USA) statistical software. Did you feel aching in your eyes? 6 Did you experience color confusion or difficultly discriminating between colors? 7 Did you get a headache? 8 Did you feel grittiness? 9 Did your eyes feel tired? RESULTS This study included 40 participants (50% male, 50% female). The relationship between reading rate and illumination was not statistically significant (P = 0.99) in either male or female participants. Reading rate was fastest in males under CFL, and in females under FLUO. There was no statistically significant difference between illumination and contrast acuity (P > 0.47) or color vision (P < 0.99) in either male and female participants . However, one-way ANOVA with Friedman's test revealed a significant association between visual performance and illumination in both males (P = 0.001) and females (P = 0.002) . All participants were asked to suggest satisfactory illuminations based on their experience of visual comfort and reading; most male participants suggested CFL (85%) and most female participants suggested FLUO (65%) . DISCUSSION This study sought to explore visual performance while reading under different illuminations, and their effect on visual comfort. No statistically significant associations between reading rate and illumination were found. However, reading rates were faster under the following illuminations: Males: CFL > FLUO > LED > TUNG Females: FLUO > CFL > LED > TUNG We could not find any studies to either support or contradict our findings. However, interestingly, in our study, participants who read under LED illuminations experienced poor visual performance. This supports the study of Yamagishi et al in which visual performance, mood, and psychological perception of pleasant reading and performance of visual tasks improved under artificial LED lighting. However, in our experiment, LED lighting was associated with reduced reading performance and visual discomfort, after TUNG illumination. However, at the end stage of the experiment, male participants (85%) were satisfied with CFL (it was their first choice lighting source) and female participants (65%) were satisfied with FLUO; this finding is supported by Eo et al who showed that students' mood changed as a result of music and art rooms altered by fluorescent lamps, improving students' creativity and visual performance compared to colored LED lighting. We found that reading under white fluorescent illumination resulted in better reading performance and visual comfort, consistent with Mott et al who found that, compared with natural lighting, increasing the quality of artificial light positively affected students' verbal reading performance. We also found that visual comfort and performance was good under both CFL and FLUO, similar to Simonson and Brozek who found that maintaining optimum illumination for visual tasks improved visual performance and reduced ocular fatigue. Nevertheless, there were few limitations to our study that need to be addressed in future work. It is unclear how the spectral distribution of artificial lighting influences the visual system and visual performance. Future studies should be conducted on different age groups and larger sample sizes. Moreover, changing standard color vision tasks may improve our understanding of the impact of lighting on visual tasks. In conclusion, we found a weak association between illumination type and reading rate. However, our findings suggest that most males (85%) prefer CFL and most females (65%) prefer FLUO, as opposed to LED and TUNG illuminations. Thus, whilst LED lighting is energy-and cost-efficient, visual performance under LED is poor and it is not suitable for prolonged visual tasks like reading and writing as it may also cause early ocular fatigue. Visual discomfort was highest under both TUNG and LED illuminations. Clinically, these findings suggest an association between illumination type and visual performance, and that improper illumination and intensity may cause early eye-fatigue problems. The current study may also raise patient awareness as to the importance of illumination, and support maintenance of a steady relationship with optometrists and eye care specialists. It is fundamental to educate patients as to the importance of visual task standards and illumination in reading, given their role in day-to-day life.
|
Judit Polgar is a phenomenon. She is not just the best woman chess player of all time; she is the best by a mile. Chess grandmasters (note master! – traditionally, chess barely recognised the existence of women) have official ratings. Polgar is the only woman in the world's top 100; at her peak, and before she had two children, she was in the top 10.
In December she will pay a rare visit to the UK for the London Chess Classic and do what she has always done – play as the lone woman against eight top male players, including world champion Vishy Anand and world No 1 Magnus Carlsen. Aggressive at the board and now getting back to her best after a mid-career slump when her results were poor following the birth of her second child in 2006, she will give as good as she gets.
Does it feel odd to be playing against a field of men? "For me it is very natural," she says. "I started when I was five, and grew up playing against adults and against men most of the time." She never accepted the path many leading female players take, competing in separate women's events and aiming at the women's world title. She took on all-comers from an early age, became the then youngest ever grandmaster (male or female) at the age of 15, and didn't bother competing for the women's world championship because she could have won it in her sleep. She simply aimed to be the best in the world, regardless of gender.
Polgar, who was born in Budapest, is one of three chess-playing sisters. The eldest, Susan, was women's world champion; the middle sister, Sofia, was an international master; but Judit, hard-working and with an immense will to win, proved the strongest of all. The three were part of a controversial experiment conducted by their teacher father Laszlo, whose contention was that "geniuses are not born, but made". He taught his daughters at home – the curriculum included Esperanto – and drilled chess into them from an early age.
"I grew up in a very special atmosphere," she says. "Everything was about chess. I learned from my sisters and won my first international competition at nine years old." Did she resent being part of her father's experiment? "In the beginning it was a game. My father and mother are exceptional pedagogues who can motivate and tell it from all different angles. Later, chess for me became a sport, an art, a science, everything together. I was very focused on chess, and happy with that world. I was not the rebelling and going out type. I was happy that at home we were a closed circle and then we went out playing chess and saw the world. It's a very difficult life and you have to be very careful, especially the parents, who need to know the limits of what you can and can't do with your child. My parents spent most of their time with us; they travelled with us [when we played abroad], and were in control of what was going on. With other prodigies it might be different. It is very fragile. But I'm happy that with me and my sisters it didn't turn out in a bad way."
Top chess players can be dysfunctional – think Bobby Fischer, who Polgar knew when he lived in Budapest in the 1990s – but Polgar is relaxed, approachable and alarmingly well balanced. After her 2006-09 slump, she says she worked out how to juggle a career in competitive chess with having two young children, running a chess foundation in Hungary, writing books and developing educational programmes based on chess. "My life is very complex and rich now," she says.
Has she struck a blow for women by showing they can compete with the best men? "There are many guys who say: 'OK, you are an exception, so you prove the rule. Show me the next.' I say: 'Yes, I am so far exceptional, but I don't think I will be the only one in the upcoming decades.'" Women's chess is getting stronger, more girls are playing at a very young age, and strong women players are emerging from China and India. Chess would benefit from an influx of women able to compete with the top men, because it would add spice to a pursuit that struggles for media attention. The first ever world title match between a male and female player would generate huge interest.
Polgar came close to the summit – she was eighth in the tournament to determine the world champion in 2005 – but, at 36, realises that the chance to compete for the world title won't come again. Forty is a watershed for top players, and many start to ease away from serious competition, but she has no thoughts of retiring. "I don't like 'never, never, never'," she says. "I don't think I could ever say that I will never play again, because even if I felt I could never play in top-class tournaments again because I don't have time for the preparation, after a while you might one day think: 'maybe, maybe, maybe … why not?'"
The London Chess Classic is at Kensington Olympia, London W14 from 1-10 December, hosted by Chess in Schools and Communities.
|
San Jose, California, 1881
A moonlight tower or moontower is a lighting structure designed to illuminate areas of a town or city at night.
The towers were popular in the late 19th century in cities across the United States and Europe; they were most common in the 1880s and 1890s. In some places they were used when standard street-lighting, using smaller, shorter, and more numerous lamps, was impractically expensive. In other places they were used in addition to gas street lighting. The towers were designed to illuminate areas often of several blocks at once, on the "high light" principle. Arc lamps, known for their exceptionally bright and harsh light, were the most common method of illumination. As incandescent electric street lighting became common, the prevalence of towers began to wane.
Austin, Texas [ edit ]
Austin, Texas, is the only city in the world known to still have moonlight towers. They are 165 feet (50 m) tall with foundations 15 feet (4.6 m) wide. The towers were manufactured in Indiana by Fort Wayne Electric Company and assembled on site.[1] In 1894, the City of Austin purchased 31 used towers from Detroit. A single tower cast light from six carbon arc lamps, illuminating a 1,500 feet (460 m) radius circle brightly enough to read a watch.[2]
In 1993, the city of Austin dismantled the towers and restored every bolt, turnbuckle and guy-wire as part of a $1.3 million project, the completion of which was celebrated in 1995 with a citywide festival.
Detroit [ edit ]
Detroit, Michigan had a particularly extensive system of light towers inaugurated in 1882[3] with 122 towers, 175 feet (53 m) tall and 1,000–1,200 feet (300–370 m) apart downtown, shorter, less powerful, and twice as far apart elsewhere.[4] The towers were masts secured with cables and were maintained daily by crew who hauled themselves to the top using a counterweighted elevator. The system covered about 21 square miles (54 km2), but soon had to be supplemented with incandescent lighting in the city center, partly because trees interfered with the light, and by the turn of the century they remained only in Cadillac Square; the towers were soon removed there, too.[5]
New Orleans [ edit ]
New Orleans riverfront electrically illuminated at night, 1883
Towers were erected in New Orleans, Louisiana, starting in the early 1880s. One set of towers illuminated a section of the Mississippi River levee, aiding in loading and unloading ships at night in the busy port. A tower at the busy intersection of Canal Street, Bourbon Street, and Carondelet Street was constructed with a set of four water pipes to aid in fire-fighting in the nearby multi-story buildings.[6]
San Jose, California [ edit ]
In 1881, a 237-foot (72 m)-tall[7] tower was erected spanning the intersection of Santa Clara and Market streets in San Jose, California, making it the first city to be illuminated by electric light west of the Rocky Mountains.[8] James Jerome ("J.J.") Owens, publisher of the San Jose Mercury, came up with the idea for the tower after visiting the first electrical lighting station in San Francisco in 1879.[9] The tower collapsed in a storm on December 3, 1915.[10]
In 1977, a nearly half-sized replica, 115 feet (35 m) tall, was constructed at the San Jose Historical Museum.[11]
Wabash, Indiana [ edit ]
Wabash, Indiana, was the first city to use arc lamps: four mounted on the city hall dome, turned on on March 31, 1880.[12] Wabash used a self-regulating lamp invented by Charles Brush in 1870.
References [ edit ]
|
<filename>nn.py
import logging
import numpy as np
import theano
from sklearn.metrics import adjusted_mutual_info_score
from theano import tensor as T
from theano.compile.ops import as_op
logger = logging.getLogger('main.nn')
def prepend_empty_dim(x):
dim = ['x'] + range(x.ndim)
return x.dimshuffle(*dim)
def flatten_first_two_dims(x):
f2 = (x.shape[0], x.shape[1])
def undo(y):
return y.reshape(f2 + tuple(y.shape[i] for i in range(1, y.ndim)))
prod = f2[0] * f2[1]
yy = x.reshape((prod,) + tuple(x.shape[i] for i in range(2, x.ndim)))
return yy, undo
def softmax_n(x, axis=-1):
e_x = T.exp(x - x.max(axis=axis, keepdims=True))
out = e_x / e_x.sum(axis=axis, keepdims=True)
return out
def soft_clip(var, epsilon):
# Clip a [0, 1] variable to [0 + epsilon, 1 - epsilon]
# Useful for binary values that goes into a log that might blow up
if epsilon > 0:
epsilon = np.float32(epsilon)
return var * (np.float32(1) - np.float32(2) * epsilon) + epsilon
else:
return var
def soft_binary_crossentropy(est, label, epsilon):
epsilon = np.float32(epsilon)
assert epsilon >= 0
assert epsilon < 0.5
if est.dtype not in ['float32']:
est = T.cast(est, 'float32')
return T.nnet.binary_crossentropy(soft_clip(est, epsilon), label)
def exp_inv_sinh(x):
y = T.sqrt(x**2 + 1)
return T.switch(T.le(x, 0), np.float32(1) / (y - x), x + y)
def infer_shape_ami_score(node, input_shapes):
ashp, bshp = input_shapes
return [(ashp[1],)]
@as_op(itypes=[theano.tensor.ftensor3, theano.tensor.ftensor3],
otypes=[theano.tensor.fvector], infer_shape=infer_shape_ami_score)
def ami_score_op(s, s_hat):
scores = []
for i in range(s.shape[1]):
true_labels = s[:, i, :].argmax(0)
m = s[:, i, :].max(0) > 0.9
pred_labels = s_hat[:, i, :].argmax(0)
scores.append(adjusted_mutual_info_score(true_labels[m], pred_labels[m]))
return np.array(scores, dtype=np.float32)
def sigmoid_mis_classification_rate(predict, target, objects=1, return_full=False):
assert target.ndim == 2
assert predict.ndim == 2
# Simple calculation if we only have one object
if objects == 1:
return T.neq(T.argmax(predict, 1), target.reshape((target.shape[0],))).mean(dtype='floatX') * np.float32(100.)
top_k_diff = T.argsort(-predict, axis=1)[:, :target.shape[1]]
res_diff = T.cast(T.eq(T.repeat(top_k_diff, target.shape[1], axis=1),
T.tile(target, (1, target.shape[1]))), 'float32')
res_diff = T.sum(res_diff, axis=1) / T.cast(target.shape[1], 'float32')
assert objects == 2
top_k_same = top_k_diff[:, 0] # Complex top-one top_k
res_same = T.eq(top_k_same, target[:, 0])
result = (np.float32(1) -
T.cast(T.switch(T.eq(target[:, 0], target[:, 1]), res_same, res_diff), 'float32')) * np.float32(100.)
if return_full:
return top_k_diff, top_k_same, result, result.mean()
return result.mean()
def categorical_crossentropy(predict, target, objects=1):
assert target.ndim == 2
assert predict.ndim == 2
if objects > 1:
target = target.reshape((target.shape[0], objects)) # Only do to catch errors where #objects is wrong
target_k_hot = [T.extra_ops.to_one_hot(target[:, s], predict.shape[1]) for s in xrange(objects)]
target_k_hot = sum(target_k_hot) / np.float32(objects)
else:
target_k_hot = target.reshape((target.shape[0],)) # Simultaneously checks that it's only one class
return T.nnet.categorical_crossentropy(predict, target_k_hot).mean()
|
// SendMessage.java - Sample application.
//
// This application shows you the basic procedure for sending messages.
// You will find how to send synchronous and asynchronous messages.
//
// For asynchronous dispatch, the example application sets a callback
// notification, to see what's happened with messages.
//
// Bulk Operator used: Clickatell (http://www.clickatell.com)
// Please look the ClickatellHTTPGateway documentation for details.
package org.ajwcc.pduUtils.test.integration;
import org.smslib.*;
import org.smslib.http.*;
public class ClickatellSendMessage extends AbstractTester
{
@Override
public void test() throws Exception
{
OutboundMessage msg;
OutboundNotification outboundNotification = new OutboundNotification();
System.out.println("Example: Send message from Clickatell HTTP Interface.");
System.out.println(Library.getLibraryDescription());
System.out.println("Version: " + Library.getLibraryVersion());
ClickatellHTTPGateway gateway = new ClickatellHTTPGateway("clickatell.http.1", " 2982992", "tdelenikas", "AFghjkr3");
gateway.setOutbound(true);
gateway.setOutboundNotification(outboundNotification);
// Do we need secure (https) communication?
// True uses "https", false uses "http" - default is false.
gateway.setSecure(true);
srv.addGateway(gateway);
gateway.startGateway();
// Create a message.
msg = new OutboundMessage("+639183018888", "Hello from SMSLib (Clickatell handler)");
msg.setFrom("SMSLIB.ORG");
// Ask for coverage.
System.out.println("Is recipient's network covered? : " + gateway.queryCoverage(msg));
// Send the message.
gateway.sendMessage(msg);
System.out.println(msg);
System.out.println(msg.getPduUserDataHeader());
// Now query the service to find out our credit balance.
System.out.println("Remaining credit: " + gateway.queryBalance());
System.out.println("Now Sleeping - Hit <enter> to terminate.");
System.in.read();
srv.stopService();
}
public class OutboundNotification implements IOutboundMessageNotification
{
public void process(String gatewayId, OutboundMessage msg)
{
System.out.println("Outbound handler called from Gateway: " + gatewayId);
System.out.println(msg);
}
}
public static void main(String args[])
{
ClickatellSendMessage app = new ClickatellSendMessage();
try
{
app.initModem();
app.test();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
<reponame>uiradias/saveferris
package com.ferrishibernatesupport.saveferris.criteria.projection.transformers;
import com.ferrishibernatesupport.saveferris.criteria.projection.mapping.EntityTupleMapping;
import com.ferrishibernatesupport.saveferris.reflection.ResultSetEntityCache;
import org.hibernate.transform.ResultTransformer;
import java.util.*;
/**
* Result transformer that should be used to convert into beans
* a result set of hibernate criteria using projections.
*
* This result transformer is able to map association and group the
* result in order to resturn unique results in one-to-one, many-to-one
* and one-to-many associations.
*
* It optimizes the transformation by keeping an internal cache that
* avoids multiple parsing of the same instance of object.
*
* If you uses the projection in an hibernate criteria, hibernate will
* not be able to parse the associations between classes. This transformer
* should be used to parse projections created in the following way:
*
* @see EntityTupleMapping
* @see EntityKeyCache
*
* @author <NAME> <EMAIL>, <EMAIL>
*/
public class DistinctAliasToBeanResultTransformer implements ResultTransformer {
private static final long serialVersionUID = 8705706398275156725L;
private static final int ROOT_LEVEL = 0;
private Class<?> clazz;
private boolean initialized;
private EntityTupleMapping root;
/**
* Group the sorted list of root entities
*/
private ArrayList<Object> rootEntities;
private Map<String, ResultSetEntityCache> cacheMap;
public DistinctAliasToBeanResultTransformer(final Class<?> clazz) {
super();
this.clazz = clazz;
}
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
if(!initialized) {
initialize(aliases);
rootEntities = new ArrayList<Object>();
cacheMap = new HashMap<String, ResultSetEntityCache>();
}
return processAssociation(root, tuple);
}
@Override
@SuppressWarnings("rawtypes") // removing warning because interface from hibernate does not use generics
public List transformList(List collection) {
if(rootEntities == null) {
return Collections.EMPTY_LIST;
}
return rootEntities;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Object processAssociation(EntityTupleMapping association, Object[] tuple) {
Object instance = null;
try {
instance = getCachedOrFillNewEntity(association, tuple);
if(instance == null) {
return null; // no information set
}
for (EntityTupleMapping subAssociation : association.getAssociations()) {
Object result = processAssociation(subAssociation, tuple);
if(result == null) continue;
if(subAssociation.isManyRelationship()) {
List list = getPreviousOrCreateNewList(instance,
subAssociation);
if(!list.contains(result)) {
// TODO Andre: Esse metodo esta em O(n2), pois esta verificando se o item
// ja existe antes de adicionalo a listagem.
// Pode ser utilizado um SET auxiliar para jogar essa complexidade para O(log(n))
list.add(result);
}
} else {
subAssociation.join.set(instance, result);
}
}
} catch (InstantiationException e) {
//TODO Log something here...
} catch (IllegalAccessException e) {
//TODO Log something here...
}
return instance;
}
@SuppressWarnings("rawtypes")
private List getPreviousOrCreateNewList(Object instance,
EntityTupleMapping subAssociation) throws IllegalAccessException {
List list = (List) subAssociation.join.get(instance);
if(list == null) {
list = new ArrayList();
subAssociation.join.set(instance, list);
}
return list;
}
private Object getCachedOrFillNewEntity(EntityTupleMapping association,
Object[] tuple) throws InstantiationException,
IllegalAccessException {
Object instance;
if(association.isEmpty(tuple)) {
return null;
}
ResultSetEntityCache entityCache = cacheMap.get(association.getRegexPrefix());
if(entityCache == null) {
entityCache = ResultSetEntityCache.newInstance(association);
cacheMap.put(association.getRegexPrefix(), entityCache);
}
instance = entityCache.getCached(tuple);
if(instance == null) {
instance = association.getAssocType().newInstance();
for (EntityTupleMapping.TupleFieldAcessor fieldAcessor : association.getFields()) {
fieldAcessor.set(instance, tuple);
}
if(association == root) {
rootEntities.add(instance); // new root entity created
}
entityCache.cache(instance, tuple);
}
return instance;
}
private void initialize(String[] aliases) {
replaceUnderlines(aliases);
root = new EntityTupleMapping(clazz);
root.load(aliases);
initialized = true;
}
/**
* Relation aliases could use underline _ when
* @param aliases
*/
private void replaceUnderlines(String[] aliases) {
for (int i = 0; i < aliases.length; i++) {
aliases[i] = aliases[i].replace("_", ".");
}
}
}
|
Braking torque distribution for hybrid electric vehicles based on nonlinear disturbance observer This article develops a two-layer brake control framework for hybrid electric vehicles equipped with both hydraulic and regenerative braking systems. In order to obtain better braking performance and higher regenerative braking efficiency, a cooperative braking control strategy is presented. In the first layer, a simple but robust brake controller is proposed to overcome the uncertainties of road condition and load variation by introducing a nonlinear disturbance observer. The convergence and stability are proved through the Lyapunov theory. In the second layer, a novel braking torque distribution strategy is proposed based on battery state of charge, which can recover more braking energy and improve the health of the battery. By simulation, the braking strategy is proved to be effective under various conditions and it shows a good compromise between the battery state of charge health and the regenerated energy recovery.
|
Auditory perception in the aging brain: the role of inhibition and facilitation in early processing Aging affects the interplay between peripheral and cortical auditory processing. Previous studies have demonstrated that older adults are less able to regulate afferent sensory information and are more sensitive to distracting information. Using auditory event-related potentials we investigated the role of cortical inhibition on auditory and audiovisual processing in younger and older adults. Across puretone, auditory and audiovisual speech paradigms older adults showed a consistent pattern of inhibitory deficits, manifested as increased P50 and/or N1 amplitudes and an absent or significantly reduced N2. Older adults were still able to use congruent visual articulatory information to aid auditory processing but appeared to require greater neural effort to resolve conflicts generated by incongruent visual information. In combination, the results provide support for the Inhibitory Deficit Hypothesis of aging. They extend previous findings into the audiovisual domain and highlight older adults' ability to benefit from congruent visual information during speech processing. Introduction Aging affects auditory perception in a diverse and multi-faceted manner. Presbycusis is a general term that refers to high-frequency age-related hearing loss and is present in approximately 50% of adults aged over 70 (). It is typically characterized by a progressive loss of hearing that begins in the high-frequency ranges and subsequently advances into the middle and lower frequencies (Gates and Mills, 2005). Interestingly, auditory ability as measured via puretone-hearing threshold levels (HTLs) does not straightforwardly correlate with functional performance by older adults on auditory tasks (Schneider and Pichora-Fuller, 2000;). Instead, functional deficits in older adults, such as impaired frequency discrimination (Schneider and Pichora-Fuller, 2000), gap detection ((Schneider et al.,, 1998, and greater sensitivity to noise during speech perception (Helfer and Freyman, 2008;) are better predicted by measures of executive function (Akeroyd, 2008;Houtgast and Festen, 2008;Humes, 2005). That is, frontal cortical areas appear to compensate for reduced peripheral auditory and auditory cortex activity (), although the frontal lobe itself shows the greatest age-related linear degeneration in the cortex (Raz and Rodrigue, 2006;). The emerging picture is that auditory perception and cognition involve a complex interplay between peripheral and central systems, each undergoing age-related changes (see also ;). The Inhibitory Deficit Hypothesis (IDH) of cognitive aging proposes that age-related deficits in performance across a wide range of perceptual, attentional, and cognitive tasks stem from an inability to inhibit the processing of irrelevant information (Hasher and Zacks, 1988). Three functions of inhibition have been distinguished: controlling access of irrelevant information to the focus of attention and working memory, deleting irrelevant information from attention and working memory, and suppressing or restraining strong but inappropriate responses (;). The second and third aspects of inhibitory deficit have been well demonstrated in many studies in which older adults are able to facilitate and enhance the processing of relevant visual information, yet are unable to efficiently ignore irrelevant information (e.g., Gazzaley et al.,, 2008). In addition, these deficits are to some extent reversible with training that boosts frontal lobe activity (). Less well-established, particularly in the auditory modality, are the effects of age on the first subcomponent of inhibition, that is, controlling access to the focus of attention, We used the P50, N1, P2, N2, mismatch negativity (MMN) and P3a event-related potentials (ERPs) to examine the role of inhibition in controlling access to the focus of attention in early perceptual processing in young and older adults. The earliest component, P50, typically peaks between 40 and 70 ms, is generated bilaterally in the primary auditory cortex (;;) and reflects the regulation of sensory information from the peripheral nervous system to the cortex. The N1 typically peaks between 90 and 130 ms, and like the P50, is generated bilaterally in the primary and association auditory cortex, with generators in the transverse temporal gyri (;). The P2 peaks between 150 and 200 ms with generators in the auditory association cortex and is responsive to complex acoustic features, and its modulation by learning and expertise. (;). The P50-N1-P2 complex reflects the information flow from primary auditory to association cortical processing, and the transition from tonotopic auditory processing to more complex spectral processing, and greater sensitivity to top-down regulation. The N2 family comprises the standard N2, the N2a, and the N2b. These subcomponents appear between 200 and 350 ms, and their topography, neural sources, and proposed function varies depending on subtype (Folstein and Van Petten, 2008). We focussed on the standard N2, typically observed in response to stimuli that involves inhibitory processing, for example, ignoring the standard stimulus in an oddball task (Bertoli and Probst, 2005). It has a fronto-central distribution with neural sources in the right orbito-frontal cortex and anterior cingulate (Falkenstein, 2006;Ntnen and Picton, 1986). Deficits in inhibitory processing due to age or pathology (e.g., depression, alcoholism) have been associated with reduced or absent standard N2 (Bertoli and Probst, 2005;;;). The MMN represents the detection of change, in particular in the sensory environment (Escera and Coral, 2007), and can initiate the orientation of attention to novel or unexpected stimuli (Ntnen and Michie, 1979;). It is calculated by subtracting the response to the frequently presented standard stimulus from that of a rare deviant stimulus and is typically characterized by a negative deflection in this difference wave during the period of 100e250 ms with neural sources located bilaterally in the superior temporal gyri and frontal lobes (for a review see Deouell, 2007). Finally, the P3a component provides the first index of selective attentional orientation and is proposed to represent the updating of working memory representations of incoming stimuli. The P3a has a fronto-central topography and is elicited in response to task-irrelevant rare events (Katayama and Polich, 1998). Age affects these ERPs differentially. Early P50 and N1 amplitudes have been shown to increase and latencies decrease in older adults, explained as a reduction in frontal regulation of afferent sensory input (see Friedman, 2008 for a comprehensive review). No demonstrable pattern emerges for P2, while there is limited but consistent evidence for a reduction in N2 amplitudes (). Oddball paradigms are valuable tools in assessing both distraction and inhibition in older adults. Measures of distraction, for example, P3a or incorrect behavioral responses to task-irrelevant deviant stimuli, have been demonstrated to be slower in older adults (). Inhibition can be observed in oddball paradigms through responses to repeating, task-irrelevant standard stimuli. In aging, the P50 or N1 amplitudes to standard stimuli have been shown to be enhanced as a result of less efficient inhibition of irrelevant information, whereas the N2 response to standard stimuli which is considered to reflect a halt in the processing of an irrelevant stimulus (see Section 4) has been shown to be reduced or absent in older adults (Bertoli and Probst, 2005). There is mixed evidence for age-related changes to MMN, with considerable variance in experimental design, analysis techniques and controlling for age-related hearing loss contributing to conflicting results (see for a meta-analysis and review). The P3a response is typically reduced or delayed in healthy aging, suggesting a reduced attentional orientation response in older adults (;Fabiani and Friedman, 1995;see Friedman, 2008 for a review; Knight, 1987;Walhovd and Fjell, 2001). However, there is evidence that the P3a habituates in younger adults, but not in older adults, suggesting that attentional capture by rare or novel stimuli may be greater in aging (;). Speech processing provides a useful tool to examine whether the effects of age on perception and attention in auditory processing extend to audiovisual processing and whether older adults are still able to benefit from the presence of visual cues and "facilitate" the processing of relevant sensory information. As an experimental stimulus, speech is equally ecologically valid in both its audiovisual and auditory forms. Viewing a speaker while listening to continuous speech has been shown to be equivalent to a 15 dB increase in the auditory signal (Sumby and Pollack, 1954), whereas simply observing silent visual speech articulation activates the primary and association auditory cortices (). The boost given to auditory processing by visual information is however dependent on the congruency and predictive value of the visual articulation (van ;Winneke and Phillips, 2011). It appears that much of the benefit derived from multisensory speech is maintained in aging. Older adults' behavioral performance in speech perception studies using multisensory and unisensory speech stimuli has been demonstrated to be comparable to younger adults (;) and their sensitivity to the McGurk illusion as equivalent to younger adults (Cienkowski and Carney, 2002;). It has been proposed that audiovisual integration is exceptionally robust to, and may even be enhanced by, aging, and that enhancement may be a compensatory process for unisensory processing deficits (;;Winneke and Phillips, 2011). What remains to be addressed is how multisensory processing performance in older adults contributes to more general theories of cognitive aging. Following the predictions of the IDH, congruent visual information should aid auditory processing and be maintained in older adults, and incongruent visual information however should serve as a greater distractor to older adults. We conducted 2 experiments to investigate the role of facilitation and inhibition in auditory processing in aging. Experiment 1 examined the effects of age on auditory processing of puretone and natural speech stimuli. We hypothesized that older adults experience deficits in the inhibition of auditory information that would manifest as increased early sensory responses (P50 and N1), as a consequence of reduced frontal lobe regulation of afferent sensory information. In addition, we hypothesized that older adults would show a reduced N2 to standard stimuli and reduced auditory mismatch negativity (aMMN) as a consequence of their inability to successfully ignore or inhibit the processing of repeating standard stimuli. Experiment 2 examined whether the patterns of age-related change observed in experiment 1 extended to audiovisual speech processing. In addition, by manipulating the congruency of the accompanying visual information, we were able to examine the influence of "relevant" versus "distracting" visual information. We hypothesized that older adults should still be able to facilitate relevant information, that is, congruent visual information but would show greater distraction or interference from incongruent visual information. Experiment 1 The experiment consisted of 2 paradigms. First, puretones were presented in a passive listening paradigm providing measures of basic auditory processing (P50, N1, and P2) and inhibitory processing (N2). Second, natural speech syllables were presented in an oddball paradigm which in addition to the measures provided by the passive listening paradigm (P50, N1, P2, and N2) also provided measures of change detection and attentional orientation (MMN and P3a, respectively, to task-irrelevant deviant stimuli). Participants Twenty younger adults (aged 18e23, mean age 19.5 , 5 males) and 26 healthy older adults (aged 62e88, mean age 76.0 , 14 males) gave consent to participate in the study. Younger adults were recruited from the University of Bristol student population and declared themselves to be in normal health. Older adults were recruited by the Avon and Wiltshire and South Gloucestershire Primary Care Trust memory service clinics at the Bristol Research into Alzheimer's and Care of the Elderly Centre, Frenchay Hospital, and the Research Institute for the Care of Elderly People, Royal United Hospital, Bath. They participated as part of a wider study into dementia as healthy controls. Each older adult was assessed by memory clinic staff and displayed normal cognitive function in relation to their age and educational attainment (mean mini-mental state examination Score 28.5/30 ) and none met clinical criteria for dementia or any other neuropsychological disorder. No older adults had history or signs of stroke or transient ischemic attack, significant head injury, depression, or other psychiatric disorder, or major neurological disease, and none were receiving medication (prescribed or non-prescribed) deemed likely to affect cognitive function. All had normal or corrected-to-normal vision and were right hand dominant. All appropriate approvals for our procedures were obtained from the National Research Ethics Service Committee South West-Bristol, Ref. 09/H0106/90. Participants provided written informed consent before participating and were free to withdraw at any time. Puretones Stimuli were 1000-Hz puretones presented binaurally through headphones at a fixed volume of approximately 60-dB sound pressure level (SPL). The duration of the tones was 200 ms with a mean interstimulus interval (ISI) of 560 ms, varying randomly between 480 and 640 ms. Auditory speech Stimuli were digitally recorded samples (audio sample rate: 44.1 KHz in 16 bits) of a female speaker pronouncing the syllables /ba/ (standard), /da/ (deviant), and /bi/ (target). The /ba/ syllable was the audio recording taken from the /ba/ video used in the audiovisual paradigm (see experiment 2) ensuring that the standard stimuli were acoustically identical in both experiments. Stimuli were presented binaurally through headphones at approximately 60-dB SPL above the participant's HTL. The duration of the stimuli was 325 ms with a mean ISI interval of 620 ms, varying randomly between 520 and 720 ms. Stimuli were matched for intensity using Praat software (Boersma and Weenink, 2009). Hearing threshold level assessment and adjustment Participants' HTLs were assessed using a Bekesy threshold procedure. The auditory standard /ba/ and deviant /da/ stimuli were used as stimuli in the HTL test rather than puretones to provide an ecologically appropriate measure of HTL. Puretone stimuli were presented at a fixed 60-db SPL and not adjusted for individuals' HTL. Auditory speech stimuli were presented at approximately 60-db SPL above the participant's individual HTL, which required an increase in the stimuli SPL by 8.98 (AE2.82) dB for younger adults and 17.80 (AE7.33) dB for older adults. This ensured that any age-related differences observed in responses to the auditory-only or audio-visual speech could be compared against a paradigm in which HTL had not been adjusted to dissociate the effects of age from the effects of the physical intensity of the stimulus. In addition, correlational analyses between ERP amplitudes and HTL are presented in Supplementary Material. 2.3.1.1. Puretones. Participants were instructed to listen to the tones, to not respond in any way, and to maintain their gaze at a fixation point on the monitor. Two hundred tones were presented. 2.3.1.2. Auditory speech. Participants were instructed to maintain their gaze at a fixation cross in the centre of the screen while listening to a continuous stream of syllables, consisting of the frequent standard syllable /ba/ interspersed with an infrequent deviant /da/ and infrequent target /bi/. They were asked to press a button in response to the target stimulus. They were instructed to ignore the standard and deviant stimuli. The target and deviant stimuli were presented in a pseudo-random sequence among the standards with at least 2 standards preceding each deviant. Eight hundred and ninety six standards, 112 deviants (i.e., standard:deviant ratio 8:1) and 8 targets were presented in 2 blocks lasting 8 minutes each. (Initially, no target stimulus was included to exactly match the audiovisual paradigm in experiment 2. However, pilot data revealed that the lack of task, combined with the lack of visual stimulation led to participants becoming drowsy and subsequent overwhelming alpha wave contamination of the evoked potentials. Therefore, a rare target stimulus was introduced to maintain the attentional and physiological arousal of the participant. The number of target stimuli was very low to maintain as much congruity with the audiovisual paradigm as was possible.) EEG recording Electroencephalographic (EEG) signals were sampled at 1000 Hz from 64 Ag/AgCl electrodes fitted on a standard electrode layout elasticized cap using a BrainAmp DC amplifier (Brain Products GmbH) with a common FCz reference and online low-pass filtered at 250 Hz. Impedances were below 5kU. Recordings were analyzed offline using Brain Electrical Source Analysis software v5.3 (BESA GmbH). Artifacts including blinks and eye movements were corrected using BESA automatic artifact correction (Berg and Scherg, 1994), and any remaining epochs containing artifacts !100 mV were rejected. The rejection rate never exceeded 10% of trials for each participant and stimulus. EEG analysis Data were re-referenced offline to a virtual linked mastoid reference, using BESA spherical spline interpolation (BESA GmbH). Epochs from 100 to 500 ms around stimulus onset were defined for the auditory and puretone data. Given the well-established scalp distribution of auditory ERPs (i.e., peak amplitude typically occurring at the vertex) and after confirmation via examination of the topography of each component in each group (see Fig. 1C), the values of 9 electrodes (FC1, FCz, FC2, C1, Cz, C2, CP1, CPz, and CP2) were averaged to form a vertex region of interest. Averaging across electrodes that show consistent and comparable activity has also been demonstrated to be more reliable than using single electrodes (). Grand average waveforms were used to select peak latency measurement epochs, see Supplementary Material. P50 was defined as the first positive maximum value following stimulus onset, N1, P2, N2, and P3 peaks were defined as sequential polarity maxima. Peak magnitude was measured as the mean amplitude during epochs defined by 1 SD around the mean peak latency. To calculate the aMMN, the averaged response to the standard stimuli was subtracted from the deviant stimuli to create a difference waveform. Sequential 1 sample t-tests were then applied to the difference waveforms for each group using the method outlined by Guthrie and Buchwald. The consecutive time points necessary to indicate an epoch of significant difference between the standard and deviant responses were obtained from a simulation using an autocorrelation estimated from the data. Intervals with values of p < 0.05 that lasted for the required duration, (14 consecutive time points for the healthy older adults, 7 for the younger adults), were accepted as significantly different epochs. An aMMN amplitude was then calculated as the mean amplitude of any significant negative deflection in the difference waveform (as identified by the sequential t-test procedure) following the N1 peak, and aMMN peak latency as the most negative deflection in the difference wave. Statistical analysis For the puretone paradigm, the amplitudes and latencies of the P50, N1, P2, and N2 were examined in a 1-way (age: young vs. old) analysis of variance (ANOVA). For the auditory speech paradigm, the amplitudes and latencies of the 4 major auditory ERPs (P50, N1, P2, and N2) were examined individually in a 2 (age: young vs. old) 2 (condition: standard vs. deviant) ANOVA. An aMMN and P3a to deviants were examined separately in a 1-way (age: young vs. old) ANOVA. Puretone ERPs Averaged ERPs to puretones for younger and older adults are shown in Fig. 1. Auditory speech ERPs Averaged ERPs to auditory-only speech for younger and older adults are shown in Fig. 2 was weak evidence for an interaction between age and condition (F 3.74, p 0.060). There was no significant effect of age interaction between age and condition (F 5.58, p 0.023) due to a more pronounced effect of condition on N1 latency in younger adults. Discussion Experiment 1 compared ERPs from younger and older adults to puretones, and to simple speech stimuli (syllables /ba/ and /da/) presented in an oddball paradigm. Older adults showed earlier P50 latencies followed by increased N1 amplitudes compared with younger participants for puretones. Similarly, older adults showed increased P50 and N1 amplitudes for auditory speech. Increased amplitudes of early sensory components in older participants under conditions when the HTL was adjusted (auditory speech) or not adjusted for (puretones) demonstrate that the effect was not a simple consequence of physically more intense/louder stimuli (see Supplementary Material for correlational analyses between ERP amplitudes and HTL). Critically, older adults' N2 response to regular repeating stimuli (i.e., the puretone stimulus and to the standard in the auditory speech paradigm) was absent or strongly reduced compared with younger adults. As expected, no N2 peak was found in response to deviant stimulus in either group (Bertoli and Probst, 2005). Older adults' P3a responses to deviant stimuli were increased and delayed. The combination of increased early sensory responses P50 and N1, absent or strongly reduced N2 to standard stimuli, and an increased P3a to deviant stimuli in older participants points to a decreased ability to inhibit responses to regular repeating information, and greater attentional capture from rare task-irrelevant information. There was no effect of age on P2 amplitudes or latencies in either paradigm, and aMMN in older adults was equivalent in amplitude and peak latency to that in younger adults. The implications of these findings for cognitive theories of aging are discussed in full in the Section 4 Experiment 2 Experiment 2 extended experiment 1 into the audiovisual domain, using the same participants as in experiment 1. In experiment 2, we manipulated the congruency of the visual information accompanying the auditory speech stimulus to examine the influence of "relevant" versus "distracting" visual information. We expected that facilitatory effects of congruent visual information will be preserved in older adults, however that the interference from incongruent visual information will increase with age. Audiovisual speech Stimuli were digitally recorded videos (frame rate: 25 images/s; audio sample rate: 44.1 KHz in 16 bits) of a female speaker pronouncing the syllables /ba/ and /ga/. Videos were digitally edited using Pinnacle software v.15 (Corel Inc) to ensure that the onset of syllabic articulatory movements, auditory onset, and auditory duration in both videos were identical. The videos were 1280 ms long with articulatory onset at 240 ms and auditory onset at 560 ms, see Fig. 3. The duration of the auditory stimuli was 325 ms. The standard stimulus was the video of the speaker pronouncing /ba/. The deviant stimulus was created by overdubbing the audio track from the /ba/ video onto the silent video of the speaker pronouncing /ga/. The combination of auditory /ba/ and visual /ga/ typically elicits the McGurk illusion (McGurk and MacDonald, 1976) fused percept of /da/. A summary of the syllables and percepts in both auditory and audiovisual paradigms is presented in Table 1. The mean ISI between videos of 620 ms varied randomly between 520 and 720 ms. During the ISI, a still frame of the speaker's face was presented on screen. This image was matched to the first and last frame of the videos, creating the impression of continuous natural speech, that is, no visual onset or offset. Stimuli were matched for auditory intensity using Praat software (Boersma and Weenink, 2009). Behavioral discrimination task Participants completed a discrimination task at the end of the EEG recording session. They were presented 25 congruent /ba/ and 50 incongruent McGurk /da/ videos, identical to those used in the audiovisual paradigm. In addition, 25 congruent /ga/ videos were presented (i.e., /ga/ video with congruent /ga/ auditory stimulus). Participants were instructed to watch the speaker's face at all times and to report the syllable they heard using a handheld response button box. The videos were presented in a fully randomized sequence lasting approximately 3 minutes. Audiovisual speech The videos were presented on a computer monitor 0.5 m directly in front of the participant. The auditory stimuli were presented binaurally through headphones at approximately 60-dB SPL above the participant's HTL following the same adjustment procedure as in experiment 1. Participants were instructed to attend to the speaker, listen to what was said and watch the speaker's face at all times. The standard /ba/ and deviant /da/ (i.e., McGurk) stimuli were presented in a pseudo-random sequence with at least 2 standards preceding each deviant. The ratio of standards:deviants was 8:1. Eight hundred and ninety six standards and 112 deviants were presented in 2 blocks lasting 12 minutes each. EEG recording techniques and analyses were identical to experiment 1. Epochs from 100 ms to 1500 ms were used for the audiovisual data in experiment 2. The influence of visual information on speech processing in aging To examine the role of visual information on speech processing in aging, we compared responses to the standard stimuli across the auditory and audiovisual paradigms as they were perceptually and acoustically identical in both paradigms, that is, the participant heard and perceived a /ba/ syllable. Deviant stimuli were not compared as although they were perceptually the same (i.e., auditory "spoken" /da/, audiovisual "illusory" /da/), they were acoustically different (i.e., auditory deviant "spoken" /da/, audiovisual deviant "spoken" /ba/). Statistical analysis The amplitudes and latencies of the 4 major auditory ERPs (P50, N1, P2, and N2) were examined individually in a 2 (age: young vs. old) 2 (condition: standard vs. deviant) ANOVA. The influence of visual information on auditory processing and its interaction with age was examined using a mixed design ANOVA. A 2 2 ANOVA with factors group (young/old) and visual information (absent /present ) was performed for the P50, N1, P2, and N2 responses to standard stimuli. No MMN or P3a response was observed; however, an extended period of positivity following the P2 peak was observed in the older adults' responses. To quantify group differences in this response, the mean amplitude of the difference wave (deviant minus standard) between 800e1500 ms was examined in 1-way (age: young vs. old) ANOVA. Behavioral discrimination task One older adult did not complete the task due to tiredness. There was no significant difference between the groups in the number of McGurk /da/ illusions perceived (Younger mean (M) 72% SE 8.78, Older M 75% SE 6.12; t 0.33, p 0.740), or the number of congruent /ba/ or /ga/ syllables correctly identified The influence of visual information on speech processing in agingecomparison of auditory versus audiovisual ERPs To examine the role of visual information on speech processing in aging, we compared responses to the standard stimuli across the auditory (experiment 1) and audiovisual (experiment 2) paradigms. Recall that standard stimuli in the auditory and audiovisual paradigms were perceptually and acoustically identical, that is, the participant heard and perceived a /ba/ syllable. Deviant stimuli were not compared across the auditory (experiment 1) and audiovisual (experiment 2) paradigms, as the stimuli were acoustically different, that is /da/ in experiment 1 and /ba/ in experiment 2. The presence of visual information significantly delayed N1 latencies (F 4.85, p 0.033). There was no significant effect of age (F 0.49, p 0.826) or interaction between age and visual information (F 1.85, p 0.181). N2. There was some evidence for the presence of visual information to increase N2 amplitude, although the effect was marginally significant (F 3.79, p 0.058). Older adults showed significantly reduced N2 amplitudes across paradigms (F 16.26, p < 0.001). There was a significant interaction between age and the presence of visual information (F 5.45, p 0.024) as visual information increased N2 amplitude in older but not younger adults. Discussion In experiment 2, older adults showed equivalent behavioral sensitivity to the McGurk illusion as younger adults. In terms of ERPs, experiment 2 replicated the pattern of inhibitory deficit in older adults observed in experiment 1. Older adults showed significantly increased P50 and N1 amplitudes compared with younger adults and no observable N2 peak to standard stimuli. The effect of congruency of visual information was also considerable, with congruent visual information increasing N1 amplitudes in both younger and older adults compared with incongruent visual information. Examination of the effects of the presence of visual information (via comparison of ERPs in response to standard stimuli in the audiovisual paradigm in experiment 2 vs. auditory paradigm in experiment 1) demonstrates similarly enhanced N1 amplitudes when (congruent) visual information is added to accompany an auditory stimulus in younger and older adults. This suggests that the facilitatory effect of visual information is maintained in aging. General discussion Across puretone, auditory and audiovisual speech paradigms older adults showed a consistent pattern of inhibitory deficits, manifested as increased P50 and/or N1 amplitudes and an absent or significantly reduced N2. Experiment 1 demonstrated that this pattern was present in auditory processing regardless of adjustment for HTL or the acoustic complexity of the stimuli, whereas experiment 2 demonstrated that this pattern extended to audiovisual processing. We propose that these findings provide evidence for IDH, in particular for the claim that older adults are less able to regulate the access to attentional focus of afferent sensory information. Experiment 2 also provided further insights into the role of visual information in auditory processing in aging. Congruent articulatory visual information enhanced N1 amplitudes for the audiovisual compared with auditory speech in both younger and older adults. When the effect of congruent and incongruent visual information were compared in audiovisual processing, incongruent information resulted in a prolonged, late positivity in older adults. An increase in early auditory ERP amplitudes in healthy older adults as compared with younger adults has been previously demonstrated (see ;Friedman, 2008) and proposed to reflect a lack of inhibitory regulation of afferent sensory information by the prefrontal cortex. The absence of the standard N2 in older adults is less well documented and often overlooked in analyses in favor of examining responses to deviants or targets (e.g., ). When addressed directly, the absence or reduction of the N2 has been associated with poorer gap detection and processing speed () and proposed to reflect a lack of frontal inhibition among older adults (Bertoli and Probst, 2005;;;Zendel and Alain, 2014). The N350 is a possible equivalent observed in sleep EEG, it is observed during sleep and sleepiness and reflects a mechanism contrary to attention, preventing conscious processing of stimuli and facilitating falling asleep (). It is speculative and beyond the remit of the present study to link the inhibitory negative components observed in sleep with the N2 observed in younger adults, but is a deserved avenue for future research. We propose that the standard N2 in our present study represents a neural "stop-signal" that serves to prevent further unnecessary processing of a repetitive stimulus and that it is consistently and markedly absent in older adults across a variety of auditory processing tasks. This is a critical element of the first aspect of inhibition, that is, controlling access of irrelevant information to the focus of attention and working memory (;) and is an automatic and integral part of sensory processing. Note that in experiment 2, younger adults showed a clear N2 to the deviant stimulus, a finding that we did not predict. The incongruity of the audio-visual deviant affected even the earliest ERPs thus making effects in later windows such as the N2 window difficult to interpret (see discussion of the absent audiovisual mismatch negativity below). One possibility that is suggested by the presence of an N2 to both standards and deviants is that N2 is based on the basis of the auditory stimulus only (/ba/, i.e., identical for the standard and deviant), that is, it remains relatively unaffected by audiovisual binding compared to earlier (P50 and N1) components. Another possibility is that the N2 to deviants is an N2b, reflecting the direct attention to stimuli (Patel and Azzam, 2005). This is notably different from the auditory speech paradigm, in which no N2 was observed to deviant stimuli, raising the possibility that attentional focus was greater to the audiovisual speech paradigm. Experiment 2 provides support for previous assertions that older adults maintain the ability to process relevant information yet are more susceptible to the distracting and interfering effects of irrelevant information (e.g., ;Gazzaley et al.,, 2008. Congruent articulatory visual information significantly increased N1 amplitude in both younger and older adults compared with auditory processing alone, demonstrating that older adults are still able to facilitate and enhance the processing of relevant (visual) information. This adds to the behavioral findings of Sommers et al. in which older adults received an equivalent visual "enhancement" of auditory processing in noise to younger adults. It should be noted that the interpretation of this increased N1 as a facilitatory effect, rather than as a marker of inhibitory deficit, is due to the underlying assumption that the younger adults' ERPs are the default "healthy" response, that is, because younger adults show an increase in N1 amplitude in the audiovisual paradigm, this is the baseline against which to compare. Older adults' P50 and N1 latencies were delayed, and younger adults showed earlier P50 latencies, in the presence of visual information, suggesting there may be a temporal cost to maintaining the benefit of congruent visual information with age. This adds to the findings of Diederich et al. who demonstrated that compared with younger adults, older adults showed slower overall multisensory integration during a saccadic reaction time task yet showed a greater neural benefit from congruent compared with incongruent multisensory stimuli. Older adults also perceived the McGurk illusion with comparable frequency to younger adults, replicating previous behavioral findings demonstrating maintained audio-visual integration in healthy aging (Cienkowski and Carney, 2002;). The increase in N1 amplitude as a consequence of the presence of congruent visual articulatory information is contrary to some previous ERP studies of audio-visual processing (e.g., van ;Winneke and Phillips, 2011) in which audio-visual N1 amplitudes were reduced and latencies shortened compared with those in the auditory-alone condition, a pattern interpreted as reflecting increased neural efficiency. However, a critical difference between the present study and previous studies is that participants were not asked to respond to stimuli, and there was no distinct visual onset, that is, the speaker's face was onscreen at all times. Therefore, the interaction of attention, task demands, and the alerting effect of a distinct visual onset may affect the influence of predictive visual information on the timing and magnitude of auditory ERPs (). Among older adults only, incongruent visual information resulted in a prolonged late positive deflection following the P2 that lasted the duration of the epoch. We suggest that the late positive deflection observed in the present study may reflect the increased processing effort required by older adults to reanalyse/revise mismatching visual articulatory and auditory information. Such increased processing has been previously demonstrated in psychophysical tasks in which older adults show a larger impact of distracting information on perceptual abilities as a result of prolonged processing of distractors (). Most relevantly, a similar late positivity has been demonstrated by Liu et al in response to incongruent audio-visual scenarios in which the action in the video (e.g., fireworks explode) mismatched the preceding audio (e.g., shattering glass). The authors related their finding to the linguistic "P600" effect, which is known to reflect a reanalysis or revision of incongruent syntactic information into a plausible or meaningful arrangement (Osterhout and Holcomb, 1992). Further research is needed to elucidate whether the late positivity observed in our study belongs to the same family of effects. Older adults showed an equivalent aMMN to younger adults, contrary to many previous studies of aMMN (e.g., ), and contrary to our predictions. Interestingly, the MMN response appears to be robust to the preceding impact of inhibitory deficit on N1 amplitudes. The adjustment of HTL may explain the discrepancy with previous findings. It is well-known that aMMN amplitudes increase as the standard and deviant become more discriminable (). Therefore, it is possible that previous studies that did not adjust for individual HTLs and simply ensured that all participants had HTLs below a common threshold (e.g., ;;) were presenting less discriminable stimuli for the older adults, resulting in a reduced aMMN. The use of natural speech stimuli, rather than puretones, may have also contributed to the maintenance of aMMN in older adults in the present study. The few electrophysiological studies on speech MMN in older adults show conflicting results, e.g., Bellis et al. found no effects of age on MMN to syllables, whereas Cheng et al. () showed a reduction amongst older adults in the magnetic MMN to speech syllables. In addition the measurement of the aMMN differed from previous studies, that is, we used sequential t-tests to identify the duration of the aMMN response and then measured the mean amplitude during this bespoke epoch as opposed to taking mean amplitudes during arbitrarily defined epochs, e.g., from 100-200 ms, or for 100 ms following the N1 peak. In fact, if such arbitrarily defined fixed epochs were used to measure the aMMN in the present study it would show a lower mean aMMN amplitude in older adults. This is because the older adults' aMMN response was 26 ms shorter than that in younger adults, which would have resulted in a lower mean aMMN amplitude for older than younger adults if it were measured using a fixed window. By accurately identifying the duration of the aMMN response we are more able to accurately assess its magnitude in each group. A possible interpretation of the current data is that aMMN is impacted by healthy aging, but it is the duration rather than the amplitude of the response that is reduced. For this hypothesis to be tested further, aMMN paradigms should be optimized to enable calculation of the duration of individuals' aMMN responses as well as group responses. Interestingly, despite the lack of large differences in the MMN, older adults also showed increased and delayed P3a responses to deviant stimuli, suggesting greater neural resources devoted to the attentional orientation toward deviant stimuli. These findings complement previous studies showing increases in the P3a in older adults (e.g., ;) and provide further support for the idea that older adults find it harder to ignore task-irrelevant information; a fundamental element of the IDH. No MMN response was observed in the audiovisual paradigm. In the present study, congruency of visual information significantly affected both the P50 and N1 peaks, consequently the pre MMN epoch (i.e., from stimulus onset to the N1 peak) was not equal for standard and for deviants. If deviant stimuli did elicit an MMN response it may have been masked by the preceding peak amplitude differences. Previous studies that have demonstrated a McGurk illusion MMN (;;) had 2 important methodological differences. First, there was a distinct visual onset and offset of the visual information, that is, the speaker's image appeared at the start and disappeared at the end of each trial. Second, visual-only ERPs were subtracted from the audio-visual ERPs to calculate the auditory ERPs. In the present study, the speaker's face remained onscreen at all times, so there was no distinct visual onset and offset. This provided more ecologically valid speech stimuli, avoided the confounding effect of visual-onset ERPs but may have compromised the measurement of the audiovisual MMN. There are some limitations to the present study. First, attention was not directly controlled for. This raises the possibility that increased early sensory P50 and N1 amplitudes may have been a consequence of additional attentional effort among the older adult group, for example, as an attempt to compensate for any deterioration in hearing ability. Note that the absence/reduction of the standard N2 in the older participants cannot be solely an outcome of extra attention because Bertoli and Probst previously demonstrated such an age-related N2 reduction in both attended and unattended auditory oddball paradigms. Hence, the age-related reduction in the standard N2 cannot be explained away by extra attention from the older participants but rather a genuine difference in the "stop-signal" process that the standard N2 reflects. Second, there were no behavioral measures of performance to assess the consequences of any inhibitory deficit in early sensory processing. Third, the ISIs were not equal in the auditory speech and audiovisual speech paradigms, possibly introducing a confound in the comparison of ERP amplitudes across paradigms. Future studies should investigate the role of attention and ISIs on inhibition and facilitation in older adults and explicitly examine the link between neural and behavioral responses. Finally, to further characterize oddball responses in both audio-visual and auditory-only paradigms, an additional audiovisual condition with a congruent deviant stimulus, e.g., visual /da/ auditory /da/, would allow for the comparison of both standard and deviant stimuli responses across paradigms. In summary, we have demonstrated a pattern of age-related auditory processing that is consistent with the IDH. Older adults consistently show increased early sensory ERPs, and an absence of a standard N2 which in combination reflects a deficit in the frontal regulation of sensory processing. Older adults are still able to use congruent visual articulatory information to aid auditory processing, but at a temporal cost, and appear to require greater neural effort to resolve conflicts generated by incongruent visual information. Future work should focus on establishing the neural mechanisms of frontal regulation of sensory processing, and how these mechanisms change with age. Disclosure statement The authors have no conflicts of interest to disclose.
|
Beginning at 12:30 p.m. on Saturday, their will be a rolling road closure for southbound lanes of I-35 as Richard Overton's funeral procession heads for the Texas State Cemetery.
AUSTIN, Texas — There will be road closures for portions of Interstate 35 on Saturday, Jan. 12 for decorated war veteran Richard Overton's funeral procession.
The procession is expected to make its way southbound on I-35 from SH 45 North to the Texas State Cemetery. The Texas Department of Transportation stated traffic will be greatly reduced at 12:30 p.m. as the procession moves through the area.
Motorists are encouraged to use alternate routes if you are expected to be traveling in this area.
|
A Plasma Membrane Vtype H+ATPase May Contribute to Elevated Intracellular pH (pHin) in Some Human Tumor Cells a Cytoplasmic pH of mammalian cells is mainly regulated by Na/H exchange and HC03--based transport mechanisms.'J In most eukaryotic cells, these systems collaborate to maintain pHin within a window of values that are permissive for growth and function. In some specialized cells, such as kidney and gastric cells, a plasma membrane H+/K+-ATPase has been implicated in pHh regulation." Furthermore, a V-type H+-ATPase, normally found in endosomes and other intracellular organelles,6 was also found in normally "invasive cells" such as osteoclasts7 and macrophages: and in renal collective ducts? Evidence indicates that several stages of carcinogenesis have distinct pHin optima. At least two different stages of in vitro carcinogenesis with distinct pH optimum (e.g., one acidic, one alkaline) have been described. The stage with the acidic pH optimum was observed in Syrian hamster embryo cells by LeBoeuf er aLIO In this case, cells chronically exposed to acid pH undergo morphological transformation. The stage with an alkaline pH optima to induce morphological transformation has been observed in Madin-Darby canine kidney (MDCK) cells chronically exposed to pH 8.0." The transformed phenotype induced in either case is stable, because moving cells back into their normal media does not revert the process. However, not all cell types may be susceptible to variations in pHex-induced transformation. For example, chronic exposure of NIH3T3 cells to either high or low pH does not result in tumorigenic transformation (unpublished observations). Tumorigenic transformation in these NIH-3T3 cells can be induced, however, by transfection with the yeast gene that encodes for a plasmalemmal H+-ATPase.l* These transfected cells maintain a chronically high pHin under physiological HC03concentration^.^^ This transfection also results in cell lines with stable secondary phenotypic characteristics, such as increased glycolysis, in, altered membrane potential, constitutive fos expression, and serumindependent growth.14 These observations prompted us to ask if H+-ATPases are present in the plasma membrane of naturally occurring tumor cells. We have screened 2 normal and 12 tumorigenic (primary and established) human cell lines for the presence of plasmalemmal H+-ATPase activity. To test for the presence of H+-ATPase in human tumor cells we used the most specific inhibitors currently available (SCH280804 for H+/K+-ATPase and bafilomycin All5 for V-type H+ATPase). With the aid of a novel technique to simultaneously measure pH in the cytoplasm (pHq*) using the fluorescence of SNARF-1 and in the endosomeslysosomes (pHvac) using the fluorescence of 7-OH-coumarin conjugated to 70,000 MW dextran, we found that almost all primary human tumor cells tested maintained
|
<reponame>robinmck11/Multithreading_in_java
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class SquarePaint extends JPanel {
ArrayList<DanceThread> danceThreads = new ArrayList<DanceThread>();
public void paintComponent(Graphics g) {
// paint all squares
for (int i = 0; i < danceThreads.size(); i++ ) {
g.setColor(Color.red);
g.fillRect(danceThreads.get(i).getposX(), danceThreads.get(i).getposY(),
danceThreads.get(i).getWidth(), danceThreads.get(i).getHeight());
repaint();
}
}
public void add(int x, int y, int width, int height){
Square square = new Square();
square.setWidth(width);
square.setHeight(height);
square.setposX(x);
square.setposY(y);
// Thread that will update the position
DanceThread thread = new DanceThread(square, this);
//Start and add thread to arraylist
thread.start();
danceThreads.add(thread);
}
}
|
Images by: Mark Andrew Boyer
Candi Darley, now 52, was working as a nurse and living in Washington, D.C., with her new husband, when, she said, “something started happening to me.” She began to have chronic pain and allergic reactions to common chemicals.
“Something started bothering me mentally. I also became physically ill,” she told Healthline.
When her husband left her several years later, Darley’s problems snowballed. Her mental and physical illness, later diagnosed as depression, fibromyalgia, and chronic fatigue syndrome, led her to miss work. She was eventually fired from her job. With no job, she could no longer make her mortgage payments.
In 2003, she took her son to a relative’s house and went to a homeless shelter for what she thought would be a few months. She was homeless for seven years.
While homeless, Darley made repeated trips to the emergency room seeking help and a diagnosis for her symptoms.
“You don’t get the right kind of care,” she said. “It would be this look of condescension. Sometimes I didn’t go.”
Being homeless also made it nearly impossible for Darley to manage her own health.
"You don’t rest enough. In the shelter you have to be up by a certain time,” she said. “I’m allergic to a host of things. In your own home you can recognize and change these things, but when you’re in a shelter you have absolutely no say as to what goes on.”
Even though the shelter Darley stayed in was a pretty good one, the sick and the elderly were thrown together in a single room with no barriers to stop the spread of disease.
And then there was the constant threat of violence.
“In such close quarters and with the frustration factor being so high, people are bound to clash,” she said.
The English philosopher Thomas Hobbes imagined that in a world before civilization, human life was “poor, nasty, brutish, and short.” His 17th-century description is all too apt for the lives of the homeless people who have fallen through the cracks in the United States since the 1980s.
Life for the half a million Americans who are homeless is short — they die, on average, before age 50 — and it is certainly brutish.
Skin infections, fungal outbreaks, and parasites are common. Bronchitis, pneumonia, and even tuberculosis spread in the close quarters of homeless shelters and squats. More than 5 percent of U.S. tuberculosis cases occur in homeless patients, according to the .
Homeless people also suffer from the same chronic illnesses that affect other Americans: diabetes, chronic obstructive pulmonary disease (COPD), asthma, high blood pressure, and HIV. It’s hard enough for people with regular routines and medical care to control these conditions. It’s a Herculean task for the homeless.
Chronic conditions kill homeless people as much as two decades earlier, according to Dr. Sharad Jain, the faculty advisor for a homeless health clinic offered by medical students at University of California, San Francisco.
Sleep Better with These Expert Tips from Doctors »
Trauma ‘Practically Universal’
A rare drizzle was falling outside San Francisco’s Tom Waddell Clinic, a public health clinic founded just after the devastation of the 1906 earthquake. The clinic has served the city’s substantial homeless population since 1986.
Several men who looked to be in their mid-40s were taking shelter in the doorway. A younger woman was trying to sleep on the sidewalk with a Rottweiler mix cradled in her arms and a pit bull nuzzling against her legs.
The conditions for sleep were less than ideal. Across the street, deafening construction was underway on a high-rise sure to boast multi-million dollar condominiums.
Dr. Barry Zevin is the slouched, soft-spoken medical director of San Francisco’s Homeless Outreach Team, based at the Tom Waddell Clinic. For two decades, it’s been his job to build old-fashioned doctor-patient relationships with the people that most other San Franciscans try not to see. His goal: to get them free medical care in a healthcare system that conspires against it.
Clinics like Tom Waddell reach only one in three homeless people who need medical attention, according to the National Coalition for the Homeless.
It’s common for people to become homeless, like Candi Darley, in part because of health problems. Many are also dealing with the loss of a major relationship.
Doctors like Zevin who specialize in treating the homeless don’t deny that many are mentally ill and many have substance abuse problems. But those conditions affect a smaller share of homeless people than you might think. Less than 4 in 10 homeless people are dependent on alcohol and less than 3 in 10 abuse other drugs, according to 2003 data from the Substance Abuse and Mental Health Services Administration. Between 20 and 50 percent of the homeless have a serious mental illness, according to 2013 data.
The most widely shared problem among homeless people is not substance abuse or mental illness — it’s trauma, Zevin said.
“Violence and victimization are a daily reality to most homeless people I see,” Zevin said. “If I had to say one unifying theme of practically everyone I see it’s this idea of having been traumatized, whether that was in childhood at the hands of parents, whether that was in adolescence, or sexual trauma, whether that’s in the streets. It’s just practically universal.”
Image source: Mark Andrew Boyer
Trauma, in one Australian survey, affected 100 percent of homeless women and 90 percent of homeless men. Post-traumatic stress disorder is so pervasive among homeless people that some psychologists have posited that losing one’s home is itself a trauma that can trigger the condition.
Trauma may also have spurred Candi Darley’s mental and physical symptoms. It often causes depression, and has been linked to and fibromyalgia.
Violence is widespread in the streets and in shelters, as Darley recounted. Patients who are mentally ill are sometimes beaten for being disruptive. Patients who carry prescription drugs, even those with no street value, can be assaulted and robbed. In one survey, half of respondents said an experience of violence prolonged their homelessness.
Related News: How Childhood Trauma Affects Us for Life »
Bringing Routine to Chaotic Lives
It’s relatively easy for doctors to treat the infections and infestations that dog the homeless. The UCSF medical students travel to a long-term shelter and treat cuts, bruises, and infections.
“The diagnoses we see are pretty routine,” Jain said.
Chronic conditions pose a much bigger problem. How can patients take regular medications when they don’t have any safe place to keep them? This is the kind of work Zevin does, and beneath his slouch is a strong streak of stubborn optimism.
“After 25 years of national widespread homelessness we’ve actually developed a number of adaptations in practice to make healthcare for chronic conditions doable for homeless people,” he said. “Often, it’s just thinking about it.”
The adaptations can be straightforward: Give a homeless person with diabetes a form of insulin that doesn’t need to be refrigerated, for example.
Image source: Mark Andrew Boyer
But treating homeless patients can require a dramatically different way of thinking about healthcare that focuses on what’s possible, not what’s ideal. A person addicted to heroin who has been infected with HIV is very unlikely to give up heroin on a doctor’s advice.
Instead of pressuring them to get clean, Zevin uses the routine their addiction dictates to make sure they take the medications that make HIV a serious chronic condition rather than a fatal illness.
“How do you take your medicine if you’ve got a chaotic lifestyle?” Zevin said. “Well, what do you do every day? You use heroin every day? Okay, so where in the process of fixing up your heroin are you going to take your HIV meds?”
“Someone who’s routine driven because of schizophrenia or because of an addiction can adhere to medicine,” he concluded.
Rather than giving up on a patient who might need a cocktail of pills for COPD and congestive heart failure, for example, Zevin tries to reduce the total number of pills or the number of daily doses. He also favors medications that are more forgiving of missed doses.
“Adherence to medications for chronic conditions for substance users and homeless people isn’t really that much worse than it is for anyone else if we make the right accommodations for people,” he said.
The single most powerful intervention is to help a homeless person find a home.
“The way you provide good health for homeless people is to provide them housing,” Jain said.
San Francisco has a housing-first model, where people are not required to get clean before they get subsidized or free housing. Those who need housing are queued partly based on how sick they are. Public housing units often provide healthcare, addiction treatment, and assistance with applying for benefits on-site.
Many of the health risks of homelessness go away with housing, and chronic conditions become easier to treat. So do alcohol and drug abuse.
When the city started providing housing first, the change was noticeable, Zevin said.
“Within a month or two or three, they would come in and say, ‘How do I get off drugs?’ That’s continued as a theme for me. It’s really hard to get off drugs when you’re homeless,” he said. “When we start to treat people as a whole person, we have a lot of people who are interested in making major changes.”
Learn More: Medical Treatments Available for Alcoholism »
Healthcare Reform Is a Sea Change
Short of housing, there’s another good lifeline for homeless people who need care: insurance. Many more have gotten it since California expanded Medicaid coverage (called Medi-Cal) under the Affordable Care Act.
Before the reforms, only people with children or a permanent disability, not including substance abuse, qualified. Now nearly all homeless do.
“I tell them, ‘You won the lottery — you have insurance now!’ People are still starting to get it,” Jain said.
With more patients able to see specialists and fill prescriptions, Zevin also says healthcare reform has been a blessing overall. But he also sees downsides to folding these patients into the larger medical system.
That’s because he says public healthcare has at least one thing that care for the privately insured lacks: the human touch.
Zevin and Jain can, if they see fit, send nurses or caseworkers to check on patients every day or every few days. Those efforts are funded by tax dollars. They offer a clear cost savings over having patients repeatedly wind up in emergency rooms, like Candi Darley did.
“Our medical care for this population is based on individual relationships, it’s based on this rather time-consuming concept,” Zevin said.
At Tom Waddell, patients aren’t passed off from one provider to another during the course of a visit. So much of their openness to treatment is built on personal trust in a system that hasn’t always treated them with compassion.
The current model is one that many are “struggling to make work for us,” Zevin said. Some just have more resources.
Darley makes a similar point: Homeless people are just like the rest of us, only they’ve run out of lifelines.
Darley now lives in public housing across from the National Arboretum. She works as a homeless advocate.
“We really want to break the conception that people are lazy, crazy and/or on drugs,” she said.
The photos that appear with this article, by Mark Andrew Boyer, depict homeless people in the San Francisco Bay Area. They were not interviewed by Healthline.
|
#pragma once
#ifdef SIMDJSON_COMPETITION_YYJSON
#include "large_random.h"
namespace large_random {
struct yyjson_base {
static constexpr diff_flags DiffFlags = diff_flags::NONE;
simdjson_inline double get_double(yyjson_val *obj, std::string_view key) {
yyjson_val *val = yyjson_obj_getn(obj, key.data(), key.length());
if (!val) { throw "missing point field!"; }
if (yyjson_get_type(val) != YYJSON_TYPE_NUM) { throw "Number is not a type!"; }
switch (yyjson_get_subtype(val)) {
case YYJSON_SUBTYPE_UINT:
return double(yyjson_get_uint(val));
case YYJSON_SUBTYPE_SINT:
return double(yyjson_get_sint(val));
case YYJSON_SUBTYPE_REAL:
return yyjson_get_real(val);
default:
SIMDJSON_UNREACHABLE();
}
SIMDJSON_UNREACHABLE();
return 0.0; // unreachable
}
bool run(yyjson_doc *doc, std::vector<point> &result) {
if (!doc) { return false; }
yyjson_val *coords = yyjson_doc_get_root(doc);
if (!yyjson_is_arr(coords)) { return false; }
// Walk the document, parsing the tweets as we go
size_t idx, max;
yyjson_val *coord;
yyjson_arr_foreach(coords, idx, max, coord) {
if (!yyjson_is_obj(coord)) { return false; }
result.emplace_back(json_benchmark::point{get_double(coord, "x"), get_double(coord, "y"), get_double(coord, "z")});
}
return true;
}
};
struct yyjson : yyjson_base {
bool run(simdjson::padded_string &json, std::vector<point> &result) {
return yyjson_base::run(yyjson_read(json.data(), json.size(), 0), result);
}
};
BENCHMARK_TEMPLATE(large_random, yyjson)->UseManualTime();
#if SIMDJSON_COMPETITION_ONDEMAND_INSITU
struct yyjson_insitu : yyjson_base {
bool run(simdjson::padded_string &json, std::vector<point> &result) {
return yyjson_base::run(yyjson_read_opts(json.data(), json.size(), YYJSON_READ_INSITU, 0, 0), result);
}
};
BENCHMARK_TEMPLATE(large_random, yyjson_insitu)->UseManualTime();
#endif // SIMDJSON_COMPETITION_ONDEMAND_INSITU
} // namespace large_random
#endif // SIMDJSON_COMPETITION_YYJSON
|
package com.github.al.todobackend.api.v1;
import io.micronaut.core.annotation.Introspected;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
@Introspected
public class UpdateTodoCommand {
private String title;
private Boolean completed;
private Long order;
}
|
Megaprostheses for the revision of infected hip arthroplasties with severe bone loss Background Periprosthetic hip infections with severe proximal femoral bone loss may require the use of limb salvage techniques, but no agreement exists in literature regarding the most effective treatment. Aim of this study is to analyze the infection eradication rate and implant survival at medium-term follow-up in patients treated with megaprostheses for periprosthetic hip infections with severe bone loss. Methods Twenty-one consecutive patients were retrospectively reviewed at a mean 64-month follow-up (24120). Functional and pain scores, microbiological, radiological and intraoperative findings were registered. Kaplan Meier survival analysis and log rank test were used for infection free survival and implant survival analyses. Results The infection eradication rate was 90.5%, with an infection free survival of 95.2% at 2 years (95%CI 70.799.3) and 89.6%(95%CI 64.397.3) at 5 years. Only two patients required major implant revisions for aseptic implant loosening. The most frequent complication was dislocation (38.1%). The major revision-free survival of implants was 95.2% (95%CI 70.799.3) at 2 years and 89.6% (95%CI 64.397.3) at 5 years. The overall implant survival was 83.35% (CI95% 50.793.94) at 2 and 5 years. Subgroup analyses (cemented versus cementless MPs, coated versus uncoated MPs) revealed no significant differences at log rank test, but its reliability was limited by the small number of patients included. Conclusions Proximal femoral arthroplasty is useful to treat periprosthetic hip infections with severe bone loss, providing good functional results with high infection eradication rates and rare major revisions at medium-term follow-up. No conclusions can be drawn on the role of cement and coatings. Introduction Severe bone loss, either on femoral or acetabular side, is an important issue to be addressed during revision hip arthroplasties. It usually develops secondary to multiple revisions, osteolysis following periprosthetic joint infection (PJI) or aseptic loosening, periprosthetic fractures or patients' comorbidities. Revision total hip arthroplasty (RTHA) could be particularly challenging in case of PJIs, because, beyond the bone loss, two further issues should be faced. The first is infection itself, whose eradication is difficult because of biofilm formation, especially in case of "difficult-to-treat" pathogens. The second is the wide spectrum of systemic diseases affecting the patients, who are often also immunocompromised. This leads to a more complex recovery and may Logoluso et al. BMC Surgery 22:68 potentially affect the overall outcomes in these cohort of patients. One-or two-stage RTHA are usually indicated to treat late chronic PJIs (Tsukuyama type IV) and are effective in restoring good patient functionality and life quality. Nevertheless, in case of severe proximal femoral bone loss, few options exist for limb salvage, such as the use of allograft-prosthesis composites, resection arthroplasties, and proximal femoral arthroplasties (PFA). Regardless of these techniques, currently there is no agreement in the literature as to the most effective treatment. The aim of this study was to retrospectively review our cohort of PJI patients treated with PFA due to severe bone loss, analyzing their outcomes in terms of infection eradication, complication rate and implant survival. We hypothesized that PFA could be a good limb salvage option in these patients, providing an acceptable function, long implant survival and high eradication rates. Patients and study characteristics In this retrospective cohort study, performed in accordance with STROBE guidelines, we searched our unit database from January 2010 through June 2018, for all consecutive cases of chronic PJIs (Tsukayama type IV) treated with PFA as limb salvage option because the severe femoral bone loss (before or after our radical debridement) contraindicated standard RTHA ( Fig. 1). Diagnosis of infection was made according to the MSIS criteria. We collected data on patient demographics, patient comorbidities, preoperative clinical data, number of previous procedures, the degree of bone loss according to Paprosky's classifications, indications for MP use, preoperative microbiological information whenever available, type of surgery (one-or two-stage procedure), type of MP, type of fixation (cemented or cementless), use of antibacterial coatings, intraoperative microbiological findings, complications, revisions, radiological followup according to Harris' criteria. The search started from 2010, year since when patients' data became available in the hospital electronic registry. All patients managed with RTHA of both femoral stem and acetabular component, with a minimum follow-up of 24 months after the final surgery, were included. We excluded patients with any oncologic diagnoses and those who received total femoral replacements. Then, 21 patients (15 females and 6 males), with a mean age at surgery of 67.9 years, were included, out of 2816 records screened. Surgical technique and post-operative management All surgeries followed the same surgical protocol. Hardinge's direct lateral approach was used. The procedure was carried out in one or two stages. According to our internal protocol, one-stage exchange is preferred in "type A" hosts according to McPherson classification, with good tissue coverage, when a single "low-virulence" antibiotic-susceptible causative pathogen was preoperatively known. Two-stage revisions were performed in patients not meeting the above-mentioned criteria, with persistent infections, sinus tracts and antibiotic-resistant microorganisms. Nevertheless, these indications were adapted to the patients' social and clinical needs. Paprosky system for acetabular and femoral bone losses was used for decision-making at the time of the reimplantation. In two-stage surgeries, the first stage included: implant removal, debridement of any dead tissue, osteomyelitic bone resection. Tissue samples were sent for histology and microbiology (at least 5 specimens, including the removed implant). After saline irrigation and surgical gloves and drapes change, a preformed long-stem cement spacer, loaded either with gentamicin or vancomycin and gentamicin (respectively, Spacer-G ® and Vancogenx ®, Tecres, Sommacampagna, Italy) was introduced (Fig. 2). The choice between the two spacers was based on the preoperative antibiograms, when available. Alternatively, a molded cement spacer (StageOne ™ Select, Biomet Orthopaedics, Warsaw, Indiana, US), which could be loaded intraoperatively with other antibiotics, was preferred when vancomycin-and gentamicin-resistant pathogens had been isolated preoperatively. All patients followed a postoperative antibiotic protocol set by our infectious diseases consultant and based on the intraoperative cultures antibiogram. The second stage procedures were performed once PJI was considered eradicated, in patients with no symptoms of infection and a serum C-reactive protein (CRP) < 1 mg/dl after at least fifteen days of antibiotic suspension. During the second stage, the spacer was removed, a new debridement was performed, and at least four tissue samples and the spacer were collected for microbiological investigation. Based on the Paprosky classification, small acetabular bone defects were addressed with cementless standard or multihole revision cups, while in case of massive defects Burch-Schneider cages were chosen. A dual-mobility insert was used in most cases to reduce the dislocation risk. The preferred bearing surfaces were ceramic-on-polyethylene. The femoral mega-implants were either Mega-C ® System (LINK, Hamburg, Germany), cemented or uncemented, according to stem primary stability, or Distally-Interlocked Modular Femoral Reconstruction Prosthesis REEF ™ (De Puy, Warsaw, IN, USA), allowing only for cementless stability (Fig. 3). In some selected patients (polymicrobial infection or relevant comorbidities) receiving uncemented implants, an antibacterial coating was used. Surgeons chose either to cover the implant with the antibiotic-loaded hydrogel coating DAC ® (Defensive Antibacterial Coating ®, Novagenit Srl, Mezzolombardo, Italy) just before the implantation (since it became available at our institution in 2014, or to use a silver-coated megaprosthesis (PorAg ®, Link, Hamburg, Germany). Silver coatings were sometimes used also for the extramedullary portion of cemented stems and DAC ® to protect the cementless cup used together with cemented stems. Postoperatively, a standardized rehabilitation protocol was applied. Contact weight-bearing was allowed with limited active abduction for the first two weeks, to enable good soft tissue healing. Thereafter, increased progressive weight-bearing was carried out, avoiding also involuntary movements of the operated limb during sleep. One-stage exchanges followed the same intraoperative steps, postoperative antibiotic therapy and rehabilitation of two-stage procedures. Microbiological methods Removed implants and periprosthetic tissues were sent to the laboratory within two hours from sample collection. Before 2015, sonication was used to improve microbiological cultures. Removed devices were completely covered by sterile saline in a container, then sealed and sonicated for 5 min (30 kHz, 300 W) at room temperature in an ultrasound bath (VWR, Milan, Italy). Since 2015, before culture, all samples were treated with 0.1% w:v Dithiothreitol to free pathogen from biofilm. The eluate obtained after Dithiothreitol or sonication treatment was centrifuged and the pellet plated on chocolate agar, Mac Conkey agar, Mannitol Salt agar and Sabouraud agar and inoculated into Brain Heart infusion and Thyoglycollate broths. Plates were incubated for 48 h at 37 °C while broths were maintained at 37 °C for 15 days and daily checked for microbial growth. Aliquots from broths showing any turbidity were plated on Blood agar and, in case of Thyoglycollate, also on Schaedler agar. Microbial identification and antimicrobial susceptibility testing were carried out on Vitek2 system. Assessment Each patient with a modular megaprosthesis was clinically and radiologically assessed (together with serial CRP measurement) in every scheduled follow-up at 1, 3, 6, 12, 24 months and then every 24 months according to our internal protocol. X-ray diagnoses of loosening were categorized upon Harris' criteria. Further assessments were done in case of minor o major implant failure or infection recurrence, when they became clinically evident. The average follow-up was 64 months, and no patient was lost. We collected data on: megaprosthesis survival rate; infection eradication rate; revision rate; pain level measured with visual analogue scale (VAS) score; and functional status using MSTS at last follow up. The MSTS provides a functional score on six items, scored from 0 to 5 points each (maximum score = 30): pain; walking ability; gait impairment; need of walking aids; overall function; and emotional acceptance. Scores were considered excellent for MSTS > 20, satisfactory with MSTS between 10 and 20 and insufficient for MSTS < 10. A blinded surgeon collected the outcome data. The primary endpoints of this study were: the infection healing rate, after a minimum 24-months follow-up, and the major revision rate. The infection was considered eradicated in case of negative clinical and laboratory parameters (CRP lower than MSIS definition thresholds), and according to Delphi criteria (no PJI-related death, healed wound with painless joint and without sinus tracts, no recurrence due to the same microorganism, no further reintervention for PJI recurrence) at 24 months. Major revision was defined as a substitution of either the stem or the cup, while open reduction of dislocated MPs, either with or without liner exchange, were considered as minor revisions, because the latter are characterized by a shorter surgical time and reduced blood loss. The overall implant survival (survival free from infection recurrence and/or any surgical revision) was considered as secondary outcome. Statistical analysis Statistical analysis was performed with SPSS Statistics 22.0 (IBM Corporation, Armonk, New York, US); variables were descripted through percentages, mean (range) or median (interquartile range, IQR). The implant survival was evaluated using Kaplan-Meier analysis, and Log rank to compare different groups (coated and uncoated MP, cemented and uncemented MP). Survival rate was expressed as percentage (95% confidence interval). Statistical significance was set at p < 0.05. Patients' features, microbiology, surgical details Clinical and radiological data were available for all patients. All cases had undergone from 2 to 6 previous interventions on the same joint (median 4, IQR 2-5). Femoral bone defects were classified as Paprosky type IIIB in 5 cases and Type IV in 16. The most frequent acetabular defect was Paprosky 2, and most patient received a standard or multihole revision cup. A single patient, showing a massive acetabular defect, was treated with a Burch-Schneider cage. Patients' demographics, preoperative data, microbiological results and follow up are available in Table 1. The most frequently isolated pathogen was Staphylococcus aureus (7 patients), followed by Staphylococcus epidermidis (6 patients) and Pseudomonas aeruginosa (4 patients). A polymicrobial infection was found in 7 patients (33.3%) and negative intraoperative cultures in 2. Twelve patients were affected by comorbidities. Seventeen were admitted for chronic PJI only. Patient no. 10 was admitted for a periprosthetic fracture around an infected THA. Patients no. 7, 8, 19 were admitted for septic non-unions of periprosthetic fractures with underlying PJIs. Intraoperative details are resumed in Table 2. In three cases only a one-stage exchange was performed. Out of 18 patients undergoing staged revisions, 5 needed an interim spacer exchange. We recorded 11 spacer dislocations (61%). The spacer instability required no further surgical treatment. All patients finally underwent reimplantation. Seventeen patients received cementless megaprostheses, 12 of which were protected with an antibacterial coating (PorAg ® and/or DAC ®. Three out of the 4 cemented implants received a coating (PorAg ® for the extramedullar femoral component or DAC ® for the cementless acetabular cup). No intraoperative complication was reported. Infection recurrence At a mean follow-up of 64 months, infection recurrence was observed in 2 patients (n°18 and n°21), who refused further surgeries and were treated with an antibiotic suppressive therapy, without further signs of implant loosening. Both had received a DAC ® -coated MP 2 years before ( (Fig. 4). No statistically significant differences were found comparing the infection free survival and the major revision free survival and overall implant survivals either between the coated and uncoated groups, or between the cemented and cementless groups (Table 3). Revision free survival, complications, functional outcome Two patients (9.5%) reported a mechanical implant failure, due to aseptic loosening of the cup (patient no. 4) or of the stem (patient no. 10), respectively 46 and 7 months after reimplantation. Both were treated with a revision of the failed implant component (major revision). The Kaplan-Meier survival of implants was 95.2% (95%CI 70.7-99.3) at 2 years and 89.6% (95%CI 64.3-97.3) at 5 years, considering major revisions as outcome measure (Fig. 5). The most frequent complication was MP dislocation (8 patients, 38.1%), treated in 7 patients with open reduction with or without liner substitution using dual mobility components (minor revisions). One patient was treated with closed reduction only. No further dislocations were reported, but one patient has been using hip abduction orthosis since the reduction surgery. No other complication required additional surgery. The overall implant survival, considering both infection recurrences, major and minor revisions, was 83.35% (CI95% 50.7-93.94) at 2 and 5 years (Fig. 6) with an overall revision rate of 33.3%. In fact, 7 out of 21 patients underwent at least a revision; among them, two patients underwent both a minor and, later, a major revision, and further two patients underwent a minor revision and a septic failure due to infection recurrence, but they refused further revision surgeries. The mean MSTS clinical score at last follow up was 20.6, with excellent functional results in 12 patients and no pain in 18 patients (Table 4). More in detail: 9 patients permanently required two crutches for walking; 5 patients were able to walk with the support of a single cane, 7 patients did not require any walking support (1 of them used a permanent brace). Seven patients declared to be able to walk as preoperatively with no walking fatigue, 12 patients were able to walk outside for a variably reduced walking distance, 2 patients were very old and compromised by systemic diseases, so they were not able to walk outside, but could move at home without a wheelchair. Analyzing the gait quality, 2 patients had major cosmetic problems caused by severe limb length discrepancy, conditioning a minor functional deficit, 4 had no alterations, the others presented only minor cosmetic issues. No patient showed signs of radiological loosening, dislocation or further osteolysis at last follow-up. Infection recurrences, revisions and functional outcomes are resumed in Table 4. Discussion In our series of PJIs with severe femoral bone loss treated with MPs, we found an overall infection eradication rate of 90.5% at an approximately mean 5-year follow-up, the highest reported to date. This analysis confirms the efficacy of PFA in these cases. Nevertheless, it should be noticed that in our series only 10 patients had a ≥ 5 yearfollow up, and about a quarter had a 2-year follow up only. PJIs with severe bone defects are probably one of the worst scenarios faced by orthopedic surgeons today, and the standard of care is missing. Treatment is often demanding and, as in our case series, patients may undergo multiple complex operations, with high perioperative risks and significant costs for national healthcare systems. Performing RTHA on these deficient bones, especially in the presence of ipsilateral knee prosthetic implants, constitutes a real challenge: standard revision implants are unsuitable in several cases. Recently, there has been a growing interest in the use of MP for non-tumoral indications, and heterogeneous series (periprosthetic fractures, massive bone defects, etc.) have been published. Nevertheless, few previous studies showed the results of MPs for the treatment of PJIs [13,14,. Artiaco et al. published a series of 5 patients undergoing RTHA for PJIs with cemented modular MPs (4 two-stage cases and 1. Eradication of infection was achieved in 33 (83%). All seven patients with persistent or recurrent infection had been treated for polymicrobial PJI. Subsequent treatment included MP revision (n = 4) and debridement, antibiotics, and implant retention (DAIR) (n = 3). At a median follow-up of four years, four of these patients were on long-term antibiotic therapy. The authors did not specify whether patients with persistent infections had received a silver-coated implant or not. More recently, Dring et al. reported a mixed case series of MPs implanted for non-oncological purposes. Eleven PJIs were treated for PJI, and coating use was not mentioned: 3 were lost at follow up and 5 had a recurrence. The choice between one-or two-stage procedures, in case of persistent PJIs after several failed surgeries, is a frequent matter of debate. In our experience, a two-step approach is likely preferable to reduce the risk of infection persistence, because staged procedures allow two clean-up interventions. However, the superiority of one technique over another is currently the subject of controversy. In this series, only three patients underwent one-stage exchange. For patient no. 4, onestage surgery represented a protocol violation, as he was ≥ 80 years old. Nevertheless, as he was affected by coronary artery disease, he had a very high operatory risk, so we opted for a one stage surgery in order to spare him a double surgery within few months. This choice likely did not affect the overall implant survival, as the cup revision he underwent two years later was not due to infection recurrence, but to aseptic loosening. In a study by Gomez et al., specifically designed to evaluate the clinical course of patients between the two stages of revision total hip or knee arthroplasties, the authors demonstrated that the 11.9% of patients needs an interim spacer exchange. In our series, the 23.8% of patients (5 out of 18 receiving a staged surgery) underwent a spacer exchange for infection persistence before the definitive reimplantation. Our percentage was higher than the one reported by Gomez et al., probably because patients needing a MP (excluded from the cited study) usually have a massive infectious involvement of the femur. This could have led to a higher rate of infection persistence, and consequently to a higher rate of spacer exchange. Persistence of infection after two-stage revision in the treatment of PJI remains a challenge. In our cohort, all patients finally underwent reimplantation, while Gomez et al. report that the 17.3% were never reimplanted. It could be due to several factors, but a possible reason for this unsatisfactory outcome is the difficulty in evaluating persistent infection before second-stage surgery. A diagnostic gold standard test to determine the infection persistence at reimplantation in fact is still missing: to this end, the synovial leucocyte esterase strip test seems to be a promising intra-operative diagnostic tool, beyond serum CRP and ESR assays. We hypothesized that MPs should provide non-inferior infection eradication rates than standard-size implants in a PJI scenario. Beyond the possibility that larger metal surfaces have a higher colonization risk, the longer surgical time, the wider surgical approaches and the greater frequency of polymicrobial infections may rise the risk of infection persistence. Despite all, our overall infection eradication rate (90.5%) was similar to other studies reporting RTHA with standard prostheses. It could be explained with the fact that PFA allows for a more radical surgery and bone debridement than RTHA, considering that 14 out of 21 patients had at least a difficult-to-treat microorganism isolated. Compared to standard revision surgery, PFA should be performed by surgeons experienced in bone infection management, after careful debridement and, when needed, extensive bone resections. Besides, these surgeries should be performed in referral centers only. Furthermore, the possible protective role of coatings on infection recurrence should not be forgotten. The efficacy of silver-coated MPs in preventing infections has been highlighted in oncological patients, so much to become the gold standard for this patients' subgroup. Nevertheless, silver has the limitation to coat only the extramedullary portion of MPs. A fast-resorbable hydrogel coating, composed of covalently linked hyaluronan and poly-D,L-lactide (DAC ® ), was developed to avoid bacterial colonization in the first few hours after surgery, providing short-term local antibiotic delivery, while minimizing potential side effects and resistance development. This hydrogel can be used to coat even cups, ceramic heads and liners, so that we used it in combination with a silver-coated MP in 4 patients. A reason for the high infection eradication rate of our series could lie in the use of antibacterial coatings, which protect also patients with persistent positive cultures at the time of re-implantation. Nevertheless, the comparison between coated and uncoated implants survival, as well as between cemented and cementless MP, did not reach the level of statistical significance in this study. MPs used for non-oncological purposes are in fact rarely performed, and patients' cohorts have often not enough power to perform reliable subgroup analyses. Furthermore, both patients who reported an infection recurrence after 2 years, had previously received a minor revision surgery within a month from the second stage surgery, because of MP dislocation. A possible MP contamination during this revision surgery cannot be excluded, considering that none of them received a novel application of the hydrogel coating, already resorbed at the time of revision surgery. As previously reported, dislocations were the most frequent complication. We reported 11 spacer dislocations. This high rate was expected, due to the extensive bone loss, the soft tissue disruption following multiple previous surgeries, and the lack of offset of the long-stem preformed spacers that were used in the study. Spacer dislocations were not treated, because of the temporary role of the spacer itself, and the intrinsic instability of these implants. Nevertheless, the use long-stem spacers gave the possibility to maintain a good femoral length and a better control of the operated limb, compared to the alternative options of not applying any spacer or using spacers with a standard short stem. Dislocations of definitive implants were less frequent, occurring in 8 cases. In the systematic review on proximal femoral arthroplasty in non-neoplastic conditions published by Mancino et al., the most common postoperative complication was dislocation, occurring in 74 out of 578 patients (12.8%), and requiring closed reduction in the 40.5% and reoperation in the 59.5% of cases. Our dislocation rate was 23.8%, slightly higher than the value reported in the cited article. Several factors may have influenced our dislocation rate, most of all the soft tissues condition after previous surgeries (median: 4 surgeries) to treat infection persistence, the inability to achieve secure repair of the abductors to the MPs and inadequate soft tissue tension achieved postoperatively. Implant instability in fact depends on several factors, including: failure to restore the correct length, implant anteversion, type of liners employed, implant offset, cup positioning, head size, etc. Parvizi et al. suggested the use of constrained liners to prevent recurrent dislocations. Other authors reported a dislocation rate of 37% even after special technical precautions, which included less than 30° cup inclination, reattachment of the abductor apparatus and limb-lengthening by about 1 cm. Implant instability remains a main issue after PFA, and specific studies are needed to weight the relative role of all the variables, and to define a treatment algorithm. Given the intrinsic instability of these implants after several revision surgeries, we suggest using dual-mobility cups since second-stage surgery, and not only after a dislocation occurs, as suggested by the most recent literature. Despite the dislocation rate, the overall satisfaction rate towards the treatment with MPs was good: the mean MSTS clinical score at last follow up was 20.6. These results are encouraging and strongly support this surgical option. This result is in line with the literature, reporting hip scores improvements with PFA. Furthermore, we should not forget that these high-risk patients, as an alternative, could be treated only with resection arthroplasty or disarticulation. We suppose that the functional results guaranteed by PFAs are anyway far superior, compared to these non-reconstructive surgeries. There is only one study on quality of life and patients' satisfaction following MP implantation in PJI cases, but they do not report the use of antibacterial coatings and consider together knee, hip and total femur MPs. Limitations This was a retrospective analysis, intrinsically providing a lower level of evidence than prospective studies. No control groups with PFA for different indications were available, because our unit is specialized in the treatment of orthopedic infections only. Finally, no power study was performed, and study sample size was limited to the rare patients receiving a surgical indication for PFA. This limited the reliability of log rank subgroup analyses. Furthermore, we found a highly variable interval between the two-stages, due to the organizational needs of our institution. Unluckily, several heterogeneity factors may affect the results of clinical reports dealing with rarely indicated complex surgical reconstructions, including patients' features and needs, isolated microorganisms and their spectrum of antimicrobial sensitivities, surgical techniques and biomaterials available, institutional organizational needs. Nevertheless, there are very few works available in the literature, presumably due to the rarity of this revision, as well as to the relative novelty of this indication. Therefore, our results must be viewed with reserve, and larger comparative studies with longer follow-up are needed both to confirm long-term implant survival and how it could be influenced by coatings and cementation. Certainly, it should be considered that, in case of MP failure, some complex cases could end up in disarticulation, therefore patients should be adequately informed of all possible therapeutic strategies available. Conclusions Our data suggest that PFA is useful for the treatment of PJI with severe bone loss, with results, in term of infection eradication, implant survival, functionality and patient satisfaction, in all similar to that of standard revision procedures.
|
Differential Experience of Peer Victimisation Among Children With Learning Disabilities in Hong Kong Children with learning disabilities (LDs) are often targets of peer bullying. Studies have confirmed the distress associated with victimisation impairs academic performance. Research has also shown that boys experience victimisation differently than girls. This study examined whether students with LDs were more likely to be victimised, whether there was a gender difference in victimisation, and how students were victimised. Hong Kong children participated (162 with and 162 without LDs). Results indicated that students with LDs experienced increased levels of victimisation, and boys compared to girls with LDs sustained more physical victimisation. Academic performance did not significantly mediate the relationship between LDs and victimisation. Prevention and intervention strategies are discussed for this population. Based on 'one curriculum framework for all', Hong Kong children with mild-to-moderate learning disabilities are placed in mainstream schools (Education Bureau, 2018). Along with this policy, a multitiered system is used to screen and assess children for learning disabilities by the Maternal and Child Health Centers of the Department of Health. All public primary schools assess each child in Primary One (1st grade equivalent) with the intention of identifying and intervening those with learning disabilities, among other difficulties. This procedure includes teacher evaluation of academic performance, social adjustment, and self-care skills. When learning difficulties are suspected, parents are informed and further assessment is recommended. After diagnosis by a specialist, interventions are devised to allow for continued education in mainstream classrooms while providing additional support. The Hong Kong approach to inclusivity and mainstreaming is in agreement with a human rights perspective whereby no child should be segregated from others in any form. Professionals in special education support this view (Cook, Semmel, & Gerber, 1999;Mittler, 1990). That being said, without adequate understanding of students with diversified needs, mainstream peers may discriminate against students with learning disabilities (Knight, 1999;Pivik, McComas & LaFlamme, 2002). Turning to peer discrimination, researchers have confirmed what parents and teachers already know: Children with learning disabilities are often the targets of bullying and aggression by their peers (Martlew & Hodson, 1991;Nabuzoka & Smith, 1993;Thompson, Whitney, & Smith, 1994;Whitney, Nabuzoka, & Smith, 1992). For example, interviews with elementary and middle school students (Albinger, 1995;Reid & Button, 1995) confirmed the social degradation experienced by children with learning disabilities. Specifically, the researchers reported themes of anger, frustration and embarrassment in students over being removed from general education classrooms. Students also regularly reported becoming targets of verbal and physical attacks when their academic program involved time spent in special education and resource rooms. The psychological self-concept of children with learning disabilities is linked with their peers. Beginning in elementary school, peers are key social agents in children's developing sense of self, with those who succeed academically and socially feeling largely confident, and those who fail often feeling inferior. This sense of inferiority can be enhanced greatly by acts of aggression and victimisation on the part of peers (Thijs & Verkuyten, 2008). How children with learning disabilities experience peer victimisation and what factors mediate that experience, however, are less understood. This is the purpose of the current study. Peer victimisation is often split into direct and indirect aggression. Direct aggression includes physical and verbal confrontational attacks, while indirect aggression includes manipulative attacks that are often covert in nature. Indirect aggression has also been labelled as relational or social aggression (Mynard & Joseph, 2000). Mynard and Joseph introduced more categories to better elucidate the construct of peer victimisation and developed a multidimensional self-report scale based on responses of 812 English children aged from 11 to 16 years. Their analyses resulted in four subscales, including physical victimisation, verbal victimisation, social manipulation, and attacks on property. Learning Disabilities and Academic Performance When compared to their peers without learning disabilities, students with learning disabilities are typically below grade level (Cawley & Miller, 1989), have a deficit in reading skills, and poorer grades. Peleg also discovered that students with learning disabilities experienced higher levels of test anxiety and lower levels of self-esteem than their peers without learning disabilities. The distress linked with test anxiety and low self-esteem also can impair their academic performance. The frustration associated with a constant struggle for academic success can result in students with learning disabilities developing maladaptive behaviours, including learned helplessness, lowered academic performance expectations, and negative affect, which can contribute to further academic difficulties. Academic Performance and Victimisation Researchers have found a relationship between low academic performance and increased peer victimisation. Thijs and Verkuyten studied 1,895 ethnically diverse 6th graders in 108 classrooms. While no significant results were found for ethnicity and peer victimisation, a negative relationship between academic achievement and victimisation was found. Similarly, Schwartz, Farver, Chang, and Lee-Shin also discovered that children with academic underachievement are often victimised. To clarify the dynamics involved, we tested the role of academic performance as a mediator between having a learning disability and experiencing higher rates of victimisation. Culture and Peer Victimisation Over the last two decades, researchers in China and Hong Kong have increasingly researched peer victimi-sation. Although severe school violence (e.g., mass shootings) is infrequent, direct bullying, such as insulting, taunting or hitting, is common, with estimates ranging from 13% (Wong, Lok, Lo, & Ma, 2008) to 66% (Qiao, Xing, Ji, & Zhang, 2009) depending on the area, socio-demographic characteristics, time frame the researchers asked participants to reflect upon, and type of peer victimisation (e.g., insults, exclusion, physical). Generally, males are more likely than females to be victimised by their peers in China and Hong Kong (Huang, Hong, & Espelage, 2013). Peer victimisation rates tend to be highest in elementary school and decrease as students progress into middle and high school, but peer victimisation is more common among schools with lower academic banding. In a study conducted by Wong et al., 62% of the participants in 5th and 6th grade, were verbally bullied, 32% physically attacked, 28% socially excluded, and 13% experienced extortion. These are similar estimates to Wong's finding, with 31.7% of primary school students being physically attacked. Wong also provided further evidence that peer victimisation decreases as children age, with percentages of physical bullying victimisation dropping to 18.3% in a sample of secondary school students. Interestingly, these estimates appear to be higher than physical bullying estimates in the United States (10.6%; ). Tam and Taki proposed that bullying may occur in Hong Kong due to competition in large classrooms. Although they did not state this specifically, it is possible that individuals with learning disabilities are at an increased risk for being victimised by peers due to poor academic performance. Individuals in the classroom may be able to present themselves as doing better academically compared to others when they highlight the poorer academic success of individuals with learning disabilities, and they are motivated to do so because of the competition within the classroom. The relation between peer victimisation and learning disabilities will be further explored in subsequent sections. Gender and Peer Victimisation In the validation study of the Multidimensional Peer Victimization Scale, Mynard and Joseph examined the experience of victimisation among their respondents. In this sample, boys scored higher than girls on physical victimisation and attacks on property, while girls reported greater experiences of social manipulation. Boys and girls, however, did not vary in verbal victimisation. Previous studies have confirmed that male and female students are susceptible to different types of victimisation such that males reported higher levels of physical victimisation and females reported higher levels of relational and verbal victimisation (James & Owens, 2004;Owens, Daly, & Slee, 2005;Scheithauer, Hayer, Petermann, & Jugert, 2006). Interestingly, Hoglund purported that the perceived cost of experiencing different subtypes of victimisation served as a better indicator of gender differences. The researcher stated that girls may be disproportionately distressed by relational forms of victimisation as the loss of relationships is assigned greater value to them than for boys. Similarly, the loss of appearing dominant or strong holds a greater meaning for boys than for girls. Such perceptions may affect the proportions of subtypes reported. Turning to boys and girls with learning disabilities, Vogel reviewed the research and concluded that females with learning disabilities as compared to boys had lower IQ scores and poorer academic achievement in mathematics and reading. This suggests a gender difference in the learning disability experience that may affect the incidence and type of victimisation for this population. Mishna pointed out the significance of the cooccurrence of bullying and learning disabilities, which she called a 'double jeopardy' (p. 336), meaning that students with learning disabilities often have an impaired ability to read social cues and respond prosocially. This leaves them prone to victimisation and social isolation by mainstream peers that can lead to further emotional and psychological problems. Research purports that a snowball effect quickly forms, where the emotional and psychological problems quickly lead to worsening academic performance from a combination of demoralisation, more frequent disruptive behaviours, and increased distractibility, which again makes students with learning disabilities more visible targets for victimisation (Epstein, Cullinan, & Lloyd, 1986;Kavale & Forness, 1996;Mishna, 2003;Pearl & Bay, 1999). Thus, academic performance may work as a mechanism to heighten the experience of victimisation for children with learning disabilities. Learning Disabilities and Victimisation Along with few studies on the causes of peer victimisation for students with learning disabilities, there is limited research on how such persons are victimised (i.e., physically, verbally, relationally). For example, while Sabornie examined physical attacks and attacks on property of peers of students with learning disabilities, other possible ways of bullying (e.g., social rejection or verbal attacks) were not studied. More recently, however, victimisation has been evaluated, with reports substantiating elevated levels of direct and indirect aggression among teens with learning disabilities (McNamara, Willoughby, & Chalmers, 2005). Further, Rose, Espelage, and Monda-Amaya found increased rates of physical, verbal, and social peer victimisation for students enrolled in special education programs, as well as higher rates of bullying perpetration and fighting indicative of a cycle of deleterious behaviours. While studies have examined the relationship of learning disabilities and academic performance, and academic performance and victimisation, to our knowledge no one has studied this performance as a mediator for victimisation of students with learning disabilities. Given this gap, this study explored whether students with learning disabilities were more likely to be victimised and, if so, how. That is, if they were victimised, was it the result of social manipulation, verbal or physical victimisation, attacks on property, or some combination of these behaviours? The current study also examined whether victimisation differed by gender. Finally, we investigated whether academic performance mediated the relationship between students' status of having learning disabilities or not and the victimisation they experienced. We hypothesised that students with learning disabilities would be more likely to be victimised compared to students without learning disabilities. Further, we wanted to assess whether children with learning disabilities were more susceptible to one or more of the particular subtypes of victimisation. We also predicted that males with learning disabilities would experience more victimisation than females with learning disabilities. Finally, we hypothesised that academic performance would act as a mediating factor, whereby academic performance might partially explain the relationship between learning disabilities and peer victimisation. Participants Participants were 324 students aged from 8 to 15 years (M = 9.85, SD = 1.18) from seven elementary schools in Hong Kong. Despite the age range, based on one of the authors' experiences, it was assumed students encountered similar difficulties at school (e.g., stress related to academic performance, parental expectations, peer pressure). Students with and without learning disabilities were matched. Students with learning disabilities were an average age of 10.5 years (123 males and 39 females); students without learning disabilities were an average age of 10.3 years (118 males and 44 females). These two groups were matched for school, grade, and class, further controlling for potential contextual differences. That is, by matching for school, grade, and class, the academic environment, including educational resources and social factors, was highly similar for each pair of children. Procedures Upon approval from the University Ethical Board, Hong Kong elementary schools were invited to participate in the study as part of a leadership training program during the 2009-10 academic year. Students in Grades 4 through 6 were invited to participate. Parental consent was obtained by sending parents a letter and asking them to reply. Following consent, students completed electronic surveys during class. Parent surveys were also given to students' parents to gain insight from the parents' perspectives. A total of 3,665 students participated in this program. Of this sample, 1,985 pairs of parents and students (54% of the total sample) completed both the parent and student surveys. Parents were asked about their children's JOURNAL OF PACIFIC RIM PSYCHOLOGY history of learning disabilities by indicating whether their child was diagnosed with any learning disabilities, and if so, what kind. Of the 1,985 pairs, parents of 162 students clearly indicated their child had a learning disability. It is important to note that while identifying students with a learning disability was based on parent report, Chinese cultural norms would inhibit parents from falsely reporting a learning disability in their child. Additionally, the parents had no known reason to falsely report that their child had a learning disability, as they were not offered additional services or any monetary compensation if they had made such a claim. Because there were unequal cell sizes for students with and without learning disabilities, we further matched students with learning disabilities with their peers using their school, grade, and class. We carried out the matching process by randomly choosing students without learning disabilities in the same school, grade, and class as those with learning disabilities. By matching and controlling for these key variables, we were able to more confidently evaluate whether learning disabilities had a role in victimisation. Multidimensional Peer Victimisation Scale (MPVS). The MPVS (Mynard & Joseph, 2000) is a 16-item, self-report scale that assesses four different forms of victimisation: physical (e.g., 'Punched me'), verbal (e.g., 'Called me names'), social manipulation (e.g., 'Tried to get me into trouble with my friends'), and attacks on property (e.g., 'Took something of mine without permission'). Each form consists of four items. Frequency of victimisation is reported using a 5-point Likert scale with 0 as never, 1 as once, 2 as twice, 3 as thrice, 4 as four times or above. Mynard and Joseph reported internal consistency estimates using Cronbach's alpha as.85 for physical victimisation,.75 for verbal victimisation,.77 for social manipulation, and.73 for attacks on property. The coefficient alpha reliability estimate found for the current sample total score was.90, while the subscales had reliabilities of.85 (physical victimisation),.79 (verbal victimisation),.83 (social manipulation), and.77 (attacks on property). Students in our sample were given the MPVS. Academic performance. We obtained students' academic performance, defined as the mean score of the final term examination in the past academic year, from their respective schools. Because schools could vary in their student composition and backgrounds, we classified students into 'poor academic results' and 'satisfactory academic results' using the 25th percentile of individual schools' academic scores as cutoff points. Given that final examination scores were not generated from public but rather internal examinations, we thought this to be a more accurate reflection of students' relative status in academic performance. For example, a student with an average final examination score of 60 out of 100 could be regarded as having poor academic performance in a high-ranked school, but a good academic performance in a low-ranked school. In our sample, of the 162 students with learning disabilities, 114 had poor academic results while 52 matched students without learning disabilities had poor academic results. Results Variables were examined for the assumptions of multivariate statistics. The MPVS total and subscale scores were found to violate some of the assumptions and were transformed using the square root method. To test the hypotheses, three sets of analyses were performed. For the first hypothesis, a multivariate analysis of covariance (MANCOVA) with learning disabilities (learning disability vs. non-learning disability) as the between-subject factor, gender (male vs. female) as a covariate, and the four types of victimisation as the dependent variables was computed. A multivariate analysis of variance (MANOVA) was used to test the second hypothesis: gender difference in different subtypes of victimisation among students with learning disabilities. Baron and Kenny's article on distinguishing mediators and moderators guided the test of the third hypothesis. The mediation analysis involved learning disability/non-learning disability as the independent variable (IV), academic performance as the mediator, and peer victimisation as the dependent variable (DV). Since this mediation analysis involved the use of a dichotomous mediator (academic performance: poor vs. satisfactory), we followed guidelines provided by MacKinnon and Dwyer on testing a mediation model with a dichotomous mediator and/or DV. Among different types of peer victimisation, verbal victimisation (M = 4.21, SD = 4.40) was the most prevalent, followed by social manipulation (M = 3.07, SD = 3.99), physical victimisation (M = 2.86, SD = 4.19), and attacks on property (M = 2.47, SD = 3.46). Prior to the main analysis, the assumptions of multivariate analysis were investigated. To reduce skewness and kurtosis of the four subtypes of victimisation, a squared-root transformation was applied. Effect of Learning Disabilities on Types of Victimisation To examine the first hypothesis that students with as compared to without learning disabilities would be more likely to be victimised, a one-way MANCOVA was performed on the four DVs (physical victimisation, verbal victimisation, social manipulation, and attacks on property). Gender was a covariate and the IV was learning disabilities (learning disability and non-learning disability). The overall effect of learning disabilities was found to be significant, Wilks's =.96, F = 2.97, p <.05, partial 2 =.04; that is, there were more victimisations in the learning disability group. An overall significant effect for gender was found as well, Wilks's =.95, F = 4.65, p <.001, partial 2 =.06. Univariate tests for learning disabilities showed that students with learning disabilities reported significantly more verbal victimisation than students without learning disabilities, F = 9.12, p <.01, partial 2 =.028. The mean scores and standard deviations for different types of victimisation behaviours between students with and without learning disabilities are reported in Table 1. To test the second hypothesis that males with learning disabilities would be more likely to be victimised by peers than females with learning disabilities, a one-way MANOVA was employed. The overall effect of gender was significant, Wilks's =.93, F = 3.20, p <.05, partial 2 =.08; that is, boys with learning disabilities experienced more victimisation compared to girls. Univariate tests for gender indicated that boys with learning disabilities reported significantly more physical victimisation than girls with learning disabilities, F = 7.57, p =.01, partial 2 =.045. The mean scores and standard deviations for different types of victimisation behaviours between boys and girls with learning disabilities are reported in Table 2. A mediation analysis was performed to test the third hypothesis that academic performance would mediate the relationship between learning disabilities and peer victimisation. Because we found that the only significant difference between students with and without learning disabilities was linked with verbal victimisation, we used this variable in the analysis. However, after following the steps recommended by Sobel and Preacher and Hayes, the results of the Sobel z test failed to support the mediation model (z = -.383, p >.05). In addition, the relationship between academic performance and verbal victimisation in our sample was not significant. Academic performance in our sample did not significantly predict verbal victimisation (p =.701). This does not satisfy the mediation criteria by Baron and Kenny. Discussion We proposed that students with learning disabilities would be more likely to be victimised compared to students without learning disabilities. Our results partially supported this prediction, such that children with learning disabilities experienced more verbal victimisation compared to children without learning disabilities. Children with and without learning disabilities reported similar experiences of physical victimisation, social manipulation, and attacks on property. A plausible explanation for the increased rate of verbal victimisation toward Hong Kong students with learning disabilities could be described as a labelling effect whereby explicitly being classified as having learning disabilities also bears implicit meanings of being less capable, having lower social status, and poorer social relationships. This explanation is consistent with Reid and Button, who found that children with learning disabilities felt unappreciated and misunderstood by peers and teachers. It is also congruent with a call for education systems to recognise the deficit in proper training for teachers of this population. Further study is needed to enhance our understanding of the dynamics connected to students with learning disabilities' heightened susceptibility to peer victimisation. We were also interested in the relationship between gender and victimisation. Results partially supported our prediction that boys compared to girls would report more victimisation as male participants experienced more physical aggression than girls. While our overall hypothesis was not confirmed, the victimisation of the physical type for males was in accordance with the literature and our hypothesis. This is consistent with previous research (Mynard & Joseph, 2000), as well as Card, Stucky, Sawalani, and Little's meta-analysis, in which they found direct aggression at higher rates in males, but indirect aggression was not significant by gender. Our significant results have important theoretical implications. Given that we found significant gender effects, it would be important to continue to assess the effect of gender on victimisation in future victimisation research in Hong Kong and not assume that victimisation is the same for each gender. Additionally, our results were similar to findings obtained in the United States (Baumeister, Storch, & Geffken, 2008;Carter & Spencer, 2006). This provides evidence that the increased likelihood of being victimised if a student has a learning disability may be a cross-cultural phenomenon. As such, students in Hong Kong may benefit from comparable intervention programs implemented in the United States. However, as other researchers have recommended (Rose, Monda-Maya, & Espelage, 2011) specific interventions need to be created to prevent individuals with learning disabilities from being victimised, given that they are at an increased risk of victimisation. Simple prevention programs are not enough; prevention programs tailored to protect individuals with learning disabilities are warranted (). Our results did not support the mediation model we hypothesised. Academic achievement did not mediate the link between learning disability status and susceptibility to victimisation. Recall that academic performance in our sample failed to predict verbal victimisation (p =.701). This result seemed to indicate that academic performance in this group of students may not be the contributing factors to verbal victimisation, regardless of their learning disability status. Academic performance thus may not be a factor in explaining the mechanism between learning disabilities and verbal victimisation from peers in our sample. Additionally, the model may have failed because the changes adopted by the Hong Kong schools in recognition of learning disabilities may have played a stronger role in demarcating children than poor grades. That is, children with learning disabilities may have received a modified education plan that included separate special education classes or one-on-one classroom assistance. These modifications may be more immediately apparent to other classmates than poor academic performance. Such modifications might even be viewed as differential treatment that would likely serve as a more powerful instigator of discrimination and maltreatment than a more easily hidden report card. Given the role of other psychological constructs related to having a learning disability (e.g., low self-esteem, anxiety, and difficulty with cognitive self-regulation), professionals are unsure how student victimisation is provoked and what can be done to prevent it. The prevention of student victimisation becomes particularly complex when special education needs must be considered alongside delivery and setting of special education services. Salend and Garrick Duhaney reported on a 1995 national study by the National Center for Educational Restructuring and Inclusion, which provided evidence that receiving individualised assistance while remaining in the general education classroom aided students with learning disabilities in improving academic motivation and performance, obtaining higher standardised test scores and bettering classroom behaviour. Of particular relevance to our findings, students in these inclusion programs also demonstrated improved interactions with peers and better attitudes toward school when compared to students who spent more time in special education classrooms. As our findings suggest, academic performance alone does not seem to play a role in students' vulnerability to victimisation. Rather, differences perceived by peers in how education is delivered likely play a greater role. Students with learning disabilities are at risk of increased victimisation by their peers. Stated bluntly, their peers have identified them as targets for bullying (Martlew & Hodson, 1991;Nabuzoka & Smith, 1993;;). Consequently, mental health professionals, researchers, and educators must develop and implement programs and policies designed to ensure their safety and allow for a healthier environment more conducive to learning. As Bender and Wall pointed out, to reach the full benefits of inclusive classrooms, children with learning disabilities must be supported in obtaining meaningful participation in social and academic activities. While a compelling explanation for victimisation of students with learning disabilities remains unknown, extant research, including this study, provides support for prevention and intervention programs. Our results can be understood as implicating the need for acceptance and understanding of students with learning disabilities. Well implemented inclusion programs may expose students without learning disabilities to those with learning disabilities, allowing for differences to be diminished and misunderstandings linked with leaving for pull-out classes to be reduced. Saylor and Leach insisted, however, that simply having students with learning disabilities in the same classroom is insufficient. Rather, teachers, aides, and psychologists, along with parents and families, must work to facilitate full social inclusion. In other words, students with learning disabilities can often be excluded to a separate table at lunch or a corner of the classroom where social opportunities are still limited to engaging aides or other students with learning disabilities. A successful inclusion program must offer integrated social opportunities that improve social skills and confidence while negating the risk of victimisation (). Cook et al. argued that principals are in a key position to implement effective inclusion policies as they have control over educational resources and stand in a supervisory position allowing for direct influence over the implementation of such programs. Our study further confirmed that verbal forms of victimisation occur at higher rates for Hong Kong students with learning disabilities, and facing physical aggression is more common for males. The study also revealed that academic performance does not seem to mediate learning disability status and victimisation. Implications for inclusion policies can be derived from our results. Wellintentioned inclusion programs may not provide students with learning disabilities an equivalent educational experience. Programs are needed to ensure full social inclusion that transcends simply sharing the same learning space.
|
The elegant and enjoyably disorienting French drama "La Moustache" is the story of Marc (Vincent Lindon), a handsome, successful Parisian whose life begins to unravel after he impulsively decides to shave off the moustache he's had for several years.
First, his live-in girlfriend, Agnes (Emmanuelle Devos), doesn't even notice his facial hair is missing. Then, when he grows frustrated by her oversight and angrily calls her attention to the change, she claims he's never had a moustache.
After that, he finds pictures of himself with the moustache and tries to show her. But she can't or won't see it, and when their best friends back her up, he begins to suspect that everyone he knows is in on an elaborate practical joke.
It soon becomes apparent that it's no joke -- and the movie is no comedy -- when other elements of his life begin to slip away, and his friends suspect he's going out of his mind and they conspire to have him committed to a mental institution.
As he takes flight, the film becomes a curiously riveting existential thriller that, on the one hand, fits rather snugly into the growing cycle of films about memory loss that have filled the screen in the wake of "Memento" six years ago. On the other hand, it pays tribute to the French New Wave of the '50s and '60s, specifically the great works of Alain Resnais ("Last Year at Marienbad") that take place in a fractured world in which reality seems to be endlessly shifting between parallel planes of existence.
However you want to interpret it, "La Moustache" is a satisfying psychological adventure that powers along nicely on its movie-star performances, the graceful craftsmanship of Emmanuel Carrere's direction and a haunting violin concerto by Philip Glass.
|
JERUSALEM, July 8 (Reuters) - Several thousand ultra-Orthodox protesters effectively blocked Jewish women activists campaigning for equal worship rights at the Western Wall from holding a monthly prayer session on Monday at the holy site.
Israeli police spokesman Micky Rosenfeld said members and supporters of the Women of the Wall group were escorted by police to a spot a short distance from the Western Wall "to make sure there would be no incidents".
A spokeswoman for the movement, which is challenging the Orthodox monopoly over rites at the Western Wall, called the incident a setback after a court decided in April the women could legally don prayer shawls that Orthodox ritual says are meant for men only.
Prayer rites at the site, revered by Jews as a perimeter wall of the Biblical Temple, are part of a long struggle between Israel's secular majority and ultra-Orthodox minority over lifestyle in the Jewish state, where institutions such as marriage, divorce and burial are controlled by rabbis.
Women pray at a separate section, set apart from men. Women of the Wall want to be able to practice the rituals reserved by Orthodox law for men - such as wearing prayer shawls and reading out loud from the Torah, or holy scriptures - in their section.
"It's the first time in 25 years we could not reach the plaza," of the wall, Shira Pruce, a group spokeswoman said. "They (police) held up back. It's our right to go there."
The 300 activists instead prayed some 50 metres (yards) from the Western Wall. Some of the ultra-Orthodox protesters, who included women, threw eggs at the group, and cursed them and police. Rosenfeld said four of the ultra-Orthodox demonstrators were arrested.
Tensions were running high at the Western Wall, a day after the Israeli cabinet approved a draft law to abolish wholesale military draft exemptions for Jewish seminary students.
"We hope soldiers will die," one ultra-Orthodox youth shouted at a member of the paramilitary border police trying to block him from entering the Western Wall plaza.
Prime Minister Benjamin Netanyahu has asked former cabinet minister and Jewish leader Natan Sharansky to seek a compromise to permit the Women of the Wall to hold prayers without exacerbating tensions with the ultra-Orthodox Jews.
Sharansky has proposed a formula to widen a separate zone at the Western Wall once designated for egalitarian prayer, a suggestion neither side nor the government has yet embraced.
Also spurring Israel's drive to resolve the dispute is the support for the Women of the Wall movement in the United States in the influential Conservative and Reform movements of Judaism, which do not adhere to the Orthodox practice of gender separation in prayer.
Shmuel Rabinowitz, an Orthodox rabbi officially in charge of the Western Wall, told Reuters he objected to the activists trying to "impose their own customs" at the Western Wall, but voiced support for government efforts to seek a compromise.
"The Western Wall should be a unifying site. Everyone needs to give in a little," he said.
|
// createWallet prompts the user for information needed to generate a new wallet
// and generates the wallet accordingly. The new wallet will reside at the
// provided path. The bool passed back gives whether or not the wallet was
// restored from seed, while the []byte passed is the private password required
// to do the initial sync.
func createWallet(cfg *config) error {
dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
stakeOptions := &loader.StakeOptions{
VotingEnabled: cfg.EnableVoting,
AddressReuse: cfg.ReuseAddresses,
TicketAddress: cfg.TicketAddress,
TicketFee: cfg.TicketFee.ToCoin(),
}
loader := loader.NewLoader(activeNet.Params, dbDir, stakeOptions,
cfg.AddrIdxScanLen, cfg.AllowHighFees, cfg.RelayFee.ToCoin())
reader := bufio.NewReader(os.Stdin)
privPass, pubPass, seed, err := prompt.Setup(reader,
[]byte(wallet.InsecurePubPassphrase), []byte(cfg.createPass), []byte(cfg.WalletPass))
if err != nil {
return err
}
fmt.Println("Creating the wallet...")
_, err = loader.CreateNewWallet(pubPass, privPass, seed)
if err != nil {
return err
}
fmt.Println("The wallet has been created successfully.")
return nil
}
|
<reponame>daa/auditwheel<filename>tests/unit/test_policy.py
from unittest.mock import patch
import pytest
from auditwheel.policy import get_arch_name, get_policy_name, get_priority_by_name
TEST_POLICIES = [
{'name': 'linux_x86_64', 'priority': 0, 'symbol_versions': {}, 'lib_whitelist': []},
{'name': 'manylinux1_x86_64', 'priority': 100, 'symbol_versions':
{'GLIBC': ['2.0', '2.1', '2.1.1', '2.1.2', '2.1.3', '2.2', '2.2.1', '2.2.2',
'2.2.3', '2.2.4', '2.2.5', '2.2.6', '2.3', '2.3.2', '2.3.3', '2.3.4',
'2.4', '2.5'], 'CXXABI': ['1.3', '1.3.1'],
'GLIBCXX': ['3.4', '3.4.1', '3.4.2', '3.4.3', '3.4.4', '3.4.5', '3.4.6', '3.4.7',
'3.4.8'],
'GCC': ['3.0', '3.3', '3.3.1', '3.4', '3.4.2', '3.4.4', '4.0.0', '4.2.0']},
'lib_whitelist': ['libpanelw.so.5', 'libncursesw.so.5', 'libgcc_s.so.1',
'libstdc++.so.6', 'libm.so.6', 'libdl.so.2', 'librt.so.1',
'libcrypt.so.1', 'libc.so.6', 'libnsl.so.1', 'libutil.so.1',
'libpthread.so.0', 'libX11.so.6', 'libXext.so.6',
'libXrender.so.1', 'libICE.so.6', 'libSM.so.6', 'libGL.so.1',
'libgobject-2.0.so.0', 'libgthread-2.0.so.0', 'libglib-2.0.so.0',
'libresolv.so.2']},
{'name': 'manylinux2010_x86_64', 'priority': 90, 'symbol_versions': {
'GLIBC': ['2.2.5', '2.2.6', '2.3', '2.3.2', '2.3.3', '2.3.4', '2.4', '2.5', '2.6',
'2.7', '2.8', '2.9', '2.10', '2.11', '2.12'],
'CXXABI': ['1.3', '1.3.1', '1.3.2', '1.3.3'],
'GLIBCXX': ['3.4', '3.4.1', '3.4.2', '3.4.3', '3.4.4', '3.4.5', '3.4.6', '3.4.7',
'3.4.8', '3.4.9', '3.4.10', '3.4.11', '3.4.12', '3.4.13'],
'GCC': ['3.0', '3.3', '3.3.1', '3.4', '3.4.2', '3.4.4', '4.0.0', '4.2.0',
'4.3.0']},
'lib_whitelist': ['libgcc_s.so.1', 'libstdc++.so.6', 'libm.so.6', 'libdl.so.2',
'librt.so.1', 'libcrypt.so.1', 'libc.so.6', 'libnsl.so.1',
'libutil.so.1', 'libpthread.so.0', 'libX11.so.6', 'libXext.so.6',
'libXrender.so.1', 'libICE.so.6', 'libSM.so.6', 'libGL.so.1',
'libgobject-2.0.so.0', 'libgthread-2.0.so.0', 'libglib-2.0.so.0',
'libresolv.so.2']}]
@patch("auditwheel.policy._platform_module.machine")
@pytest.mark.parametrize("arch", [
"armv6l",
"armv7l",
"ppc64le",
"x86_64",
])
def test_arch_name(machine_mock, arch):
machine_mock.return_value = arch
machine = get_arch_name()
assert machine == arch
@patch("auditwheel.policy._platform_module.machine")
@patch("auditwheel.policy.bits", 32)
def test_unknown_arch_name(machine_mock):
machine_mock.return_value = "mipsel"
machine = get_arch_name()
assert machine == "i686"
class TestPolicyAccess:
@patch("auditwheel.policy._POLICIES", TEST_POLICIES)
def test_get_by_priority(self):
assert get_policy_name(100) == 'manylinux1_x86_64'
assert get_policy_name(0) == 'linux_x86_64'
@patch("auditwheel.policy._POLICIES", TEST_POLICIES)
def test_get_by_priority_missing(self):
assert get_policy_name(101) is None
@patch("auditwheel.policy._POLICIES", TEST_POLICIES * 2)
def test_get_by_priority_duplicates(self):
"""Duplicate priorities raise RuntimeError"""
with pytest.raises(RuntimeError):
get_policy_name(0)
@patch("auditwheel.policy._POLICIES", TEST_POLICIES)
def test_get_by_name(self):
assert get_priority_by_name("manylinux1_x86_64") == 100
@patch("auditwheel.policy._POLICIES", TEST_POLICIES)
def test_get_by_name_missing(self):
assert get_priority_by_name("nosuchpolicy") is None
@patch("auditwheel.policy._POLICIES", TEST_POLICIES * 2)
def test_get_by_name_duplicate(self):
"""Duplicate priorities raise RuntimeError"""
with pytest.raises(RuntimeError):
get_policy_name(0)
|
Angiotensin II, via angiotensin receptor type 1/nuclear factor-B activation, causes a synergistic effect on interleukin-1--induced inflammatory responses in cultured mesangial cells Introduction: The nuclear factor-B (NF-B) is an important regulator of the inflammatory response. Angiotensin II (Ang II) activates the NF-B pathway linked to renal inflammation. Although both AT1 and AT2 receptors are involved in Ang II-mediated NF-B activation, the biological processes mediated by each receptor are not fully characterized. Interleukin-1 (IL-1) is an important macrophage-derived cytokine that regulates immune and inflammatory processes, activating intracellular pathways shared with Ang II, including the NF-B. Materials and methods: In vitro studies were done in primary cultured rat mesangial cells. NF-B pathway was evaluated by phosphorylated levels of p65/IB and DNA binding activity. The Ang II receptor subtype was determined by pretreatment with AT1 and AT2 antagonists. Results: In mesangial cells the simultaneous presence of Ang II and IL-1 caused a synergistic activation of the NF-B pathway and a marked upregulation of proinflammatory factors under NF-B control, including monocyte chemoattractant protein-1. The AT1, but not AT2, antagonist abolished the synergistic effect on NF-B activation and proinflammatory genes caused by coincubation of Ang II and IL-1. Conclusions: These data indicates that Ang II, via AT1/NF-B pathway activation, cooperates with IL- to increase the inflammatory response in mesangial cells.
|
<filename>03-1D_Heat_Conduction.py<gh_stars>0
# Getting the numpy module
import numpy as np
# Getting the matplotbib module
import matplotlib.pyplot as plt
# Number of grid points
N = 11
# Domain size
L = 1
# Corresponding grid spacing
h = np.float64(L / (N - 1))
# Iteration number
iterations = 0
# Initializing temperature field
T = np.zeros(N)
T[N-1] = 1.
# Initializing iterated temperature
T_new = np.zeros(N)
T_new[N-1] = 1.
# Error related variables
epsilon = 1.E-8
numerical_error = 1 # Set as 1 in order to satisfy the while loop condition
# Checking the error tolerance
while numerical_error > epsilon:
# Computing for all interior points
for i in range(1, N-1):
T_new[i] = 0.5 * (T[i-1] + T[i+1])
# Resetting the numerical error and recalculate
numerical_error = 0
for i in range(1, N-1):
numerical_error = numerical_error + abs(T[i] - T_new[i])
# Iteration advancement and reassignment
iterations = iterations + 1
T = T_new.copy()
# Plotting numerical error
plt.figure(1)
plt.plot(iterations, numerical_error, 'ko')
# plt.pause(0.01) # Residual plot on fly Ansys Fluent like
plt.show()
# Plotting the results
plt.figure(2)
# Defining the position from indexes
x_dom = np.arange(N) * h
# Plotting the variation with customization
plt.plot(x_dom, T, 'bx--', linewidth=2, markersize=10)
# Displaying the gridlines
plt.grid(True, color='k')
# Labelling and providing a title to the plot
plt.xlabel('Position', size=15)
plt.ylabel('Temperature', size=15)
plt.title('T(x)')
# plt.margins(0)
# Showing the plot on screen
plt.show()
|
/**
* This activity is used to display the layout for the barcode scanner activity in order to add items
* to the shopping cart. Validation checks are performed as required to update the database and cart
* as required.
*/
public class ScanActivity extends AppCompatActivity {
Button acceptScannerButton;
Button cancelScannerButton;
EditText upcBarcode;
CheckBox checkBox;
GlutenDatabase dbOpener;
SQLiteDatabase db;
CodeScanner codeScanner;
CodeScannerView scannerView;
Product barcodeCheck;
Toolbar scannerTbar;
AlertDialog.Builder glutenToCartDialog;
AlertDialog.Builder glutenDatabaseMismatchDialog;
boolean cameraPermission;
int CAMERA_PERMISSION_CODE;
// Adding six second delay between scans, https://github.com/journeyapps/zxing-android-embedded/issues/59
static final int DELAY = 6000;
long delayTimeStamp = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scannerTbar = (Toolbar)findViewById(R.id.scannerToolbar);
checkBox = (CheckBox) findViewById(R.id.glutenCheckBox);
upcBarcode = (EditText) findViewById(R.id.barcodeEditText);
acceptScannerButton = (Button) findViewById(R.id.acceptScannerButton);
cancelScannerButton = (Button) findViewById(R.id.cancelScannerButton);
dbOpener = new GlutenDatabase(this);
db = dbOpener.getWritableDatabase();
glutenToCartDialog = new AlertDialog.Builder(this);
glutenDatabaseMismatchDialog = new AlertDialog.Builder(this);
/**
* Logic to request camera permissions from the user if not already granted.
*/
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
cameraPermission = false;
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
} else {
cameraPermission = true;
}
scannerView = (CodeScannerView) findViewById(R.id.barcodeScanner);
codeScanner = new CodeScanner(this, scannerView);
codeScanner.getCamera();
/**
* Set the camera to continuously scan for barcodes
*/
codeScanner.setScanMode(ScanMode.CONTINUOUS);
/**
* Enable all barcode formats to be suitable for API queries to Edamam
*/
codeScanner.setFormats(CodeScanner.ALL_FORMATS);
/**
* Code example taken from the following github repository:
* @link https://github.com/yuriy-budiyev/code-scanner
*
* Enables the camera to constantly refresh and wait until a barcode image is found.
* Once a barcode is found and decoded, send it to the runQuery() method and perform validation
* checks.
*/
codeScanner.setDecodeCallback(new DecodeCallback() {
@Override
public void onDecoded(@NonNull final Result result) {
ScanActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* Logic to delay the time between scans. Currently set to 6 seconds
* as we currently have limitations with the current API (10 lookups per minute)
*/
if (System.currentTimeMillis() - delayTimeStamp < DELAY){
return;
} else {
ScanActivity.this.runQuery(parseLong(result.getText()), checkBox.isChecked());
delayTimeStamp = System.currentTimeMillis();
}
}
});
}
});
/**
* Logic for the accept button, pass the barcode from the EditText field and
* CheckBox if pressed.
*/
if (acceptScannerButton != null) {
acceptScannerButton.setOnClickListener(acceptClick -> {
if (upcBarcode.getText().toString().length() > 0) {
this.runQuery(getUPCEditText(), checkBox.isChecked());
}
});
}
/**
* Logic for the cancel button, return to previous activity if pressed.
*/
if (cancelScannerButton != null) {
cancelScannerButton.setOnClickListener(cancelClick -> {
finish();
});
}
/**
* Logic to enable/disable the flashlight
*/
if (codeScanner.isFlashEnabled()) {
codeScanner.setFlashEnabled(true);
} else {
codeScanner.setFlashEnabled(false);
}
}
/**
Performs verification checks and performs the necessary actions:
1. If the item is in the cart, do not perform database or API query to Edamam.
2. If the item is not in the cart but it exists in the database, perform the following:
A) Retrieve the item from the database
B) Ask the user if they want to add the item to the cart.
3. If the item does not exist in the cart or database, perform an API query to Edamam and
retrieve the item if it exists.
@param upc - Barcode value retrieved from Edamam or the database
@param isGlutenFree - parameter passed from the Check Box to declare if the item is gluten free or not
*/
private void runQuery(long upc, boolean isGlutenFree) {
boolean boolCartItem = false;
db = dbOpener.getReadableDatabase();
barcodeCheck = dbOpener.selectProductByID(upc);
/**
* Logic to confirm if the item has already been added to the cart. If it has,
* simply display a message to the user.
*/
boolCartItem = productInCart(upc);
/**
* Verify if the item was previously scanned (added to the database)
*/
if (barcodeCheck !=null) {
if (barcodeCheck.isGlutenFree() != isGlutenFree) {
showGlutenMismatchDialog();
} else if (barcodeCheck.isGlutenFree() == isGlutenFree) {
if (boolCartItem == false) {
if (barcodeCheck.isGlutenFree()) {
CartActivity.getProductsArrayList().add(barcodeCheck);
Toast.makeText(ScanActivity.this, barcodeCheck.getProductName() + " added to the cart", Toast.LENGTH_LONG).show();
} else if (!barcodeCheck.isGlutenFree()) {
showGlutenToCartDialog();
}
} else if (boolCartItem == true) {
Toast.makeText(ScanActivity.this, barcodeCheck.getProductName() + " already exists in the cart", Toast.LENGTH_LONG).show();
}
}
/**
* Perform API query to Edamam
*/
} else if (barcodeCheck == null) {
new EdamamQuery(ScanActivity.this, upc, isGlutenFree).execute();
barcodeCheck = dbOpener.selectProductByID(upc);
if (!isGlutenFree && barcodeCheck != null) {
showGlutenToCartDialog();
}
}
}
/**
* Return Edit text field value
*/
private long getUPCEditText() {
return Long.valueOf(upcBarcode.getText().toString());
}
/**
* Overwrite onResume method, used to display camera only if camera permissions
* were accepted.
*/
@Override
protected void onResume() {
super.onResume();
if (cameraPermission){
codeScanner.startPreview();
}
}
/**
* Method used to release resources used by CodeScanner when this method is called
*/
@Override
protected void onPause() {
codeScanner.releaseResources();
super.onPause();
}
/**
* Method to hide the icons of the currently selected activity (ScanActivity.java)
*
* @param menu instance of the menu for the top toolbar
* @return
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toolbar, menu);
menu.findItem(R.id.scannerButton).setVisible(false);
menu.findItem(R.id.search_view).setVisible(false);
return true;
}
/**
* Method used to change activities when clicking/tapping on the toolbar icons
*
* @param item Item clicked/tapped on the main toolbar
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scannerButton:
setResult(MainMenuActivity.RESULT_CODE_NAVIGATE_TO_SCANNER);
finish();
break;
case R.id.cartButton:
setResult(MainMenuActivity.RESULT_CODE_NAVIGATE_TO_CART);
finish();
break;
case R.id.receiptButton:
setResult(MainMenuActivity.RESULT_CODE_NAVIGATE_TO_RECEIPT);
finish();
break;
case R.id.reportButton:
setResult(MainMenuActivity.RESULT_CODE_NAVIGATE_TO_REPORT);
finish();
break;
}
return true;
}
/**
*
* @param alertDialog AlertDialog.Builder object that will be configured through this method
* @param title Title that will be given at the top of the alert dialog box
* @param message Message that will be given in the alert dialog box
* @param listener Specifies the listener that will be used in order to perform specific actions
* @return Returns the dialog box objects
*/
public AlertDialog.Builder setAlertDialog(AlertDialog.Builder alertDialog, String title, String message, DialogInterface.OnClickListener listener) {
return alertDialog.setTitle(title)
.setMessage(message)
.setPositiveButton("Yes", listener).setNegativeButton("No", listener);
}
/**
* Method creating the message box to ask if users want to add the gluten item to the cart, calls the setAlertDialog() method
*/
public void showGlutenToCartDialog() {
setAlertDialog(glutenToCartDialog, "Add gluten item to cart", "Would you like to add this gluten item to the cart? By default, only gluten-free items are added.", glutenToCartListener);
glutenToCartDialog.create().show();
}
/**
* Method creating the message box when gluten item values mismatch, calls the setAlertDialog() method
*/
public void showGlutenMismatchDialog() {
setAlertDialog(glutenDatabaseMismatchDialog, "Mismatching gluten value", "The item previously retrieved does not match the selected item, would you like to change this?", glutenMismatchListener);
glutenDatabaseMismatchDialog.show();
}
/**
* Method used to change the gluten value of a product retrieved from the database. If the item exists in the cart, it will also update this item.
*/
DialogInterface.OnClickListener glutenMismatchListener = (dialog, which) -> {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
dbOpener.getWritableDatabase();
barcodeCheck.setIsGlutenFree(checkBox.isChecked());
dbOpener.updateProductById(barcodeCheck);
boolean itemInCart = false;
int index;
String glutenString = "";
if (checkBox.isChecked()) {
glutenString = "gluten-free";
} else {
glutenString = "gluten";
}
Toast.makeText(ScanActivity.this, barcodeCheck.getProductName() + " successfully changed to " + glutenString, Toast.LENGTH_LONG).show();
/**
* Verify if the item exists in the cart. If it does, update the item in the cart.
*/
if (CartActivity.getProductsArrayList().size() != 0){
for (Product prod : CartActivity.getProductsArrayList()) {
index = 0;
if (prod.getId() == barcodeCheck.getId()) {
itemInCart = true;
CartActivity.getProductsArrayList().set(index, barcodeCheck).setLinkedProduct(null);
break;
}
index++;
}
}
if (!barcodeCheck.isGlutenFree() && !productInCart(barcodeCheck.getId())) {
showGlutenToCartDialog();
} else if (barcodeCheck.isGlutenFree() && !productInCart(barcodeCheck.getId())) {
CartActivity.getProductsArrayList().add(barcodeCheck);
Toast.makeText(ScanActivity.this, barcodeCheck.getProductName() + " successfully added to cart ", Toast.LENGTH_LONG).show();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(ScanActivity.this, barcodeCheck.getProductName() + " was not changed", Toast.LENGTH_LONG).show();
if (!barcodeCheck.isGlutenFree() && !productInCart(barcodeCheck.getId())) {
showGlutenToCartDialog();
}
break;
}
};
/**
* Listener to perform actions when users click yes/no for the glutenToCart alert dialog
*/
DialogInterface.OnClickListener glutenToCartListener = (dialog, which) -> {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
CartActivity.getProductsArrayList().add(barcodeCheck);
Toast.makeText(ScanActivity.this, barcodeCheck.getProductName() + " successfully added to the cart", Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(ScanActivity.this, barcodeCheck.getProductName() + " was not added to the cart", Toast.LENGTH_LONG).show();
break;
}
};
/**
* Method to verify if the item exists in the cart.
* @param upc Barcode to compare in the cart
* @return Return true if the product is found in the cart, return false if the item is not found.
*/
public boolean productInCart(long upc) {
if (CartActivity.getProductsArrayList().size() != 0){
for (Product prod : CartActivity.getProductsArrayList()) {
if (prod.getId() == upc) {
return true;
}
}
}
return false;
};
/**
* Overwritten method used to enable/disable camera based on permissions selected
* by the user.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
cameraPermission = true;
codeScanner.startPreview();
} else {
cameraPermission = false;
}
}
}
|
Pasadena is fast-tracking construction of 65 to 70 units of permanent supportive housing at Heritage Square — but it could still take three years before the project for homeless seniors breaks ground.
The City Council on Monday approved a preliminary plan to develop the southern portion of the city-owned Heritage Square in Northwest Pasadena. To develop the site, the council selected Bridge Housing, the nonprofit that built and manages the 70-unit Heritage Square Senior Apartments located on the northern part of the 2.8-acre block at Fair Oaks Avenue and Orange Grove Boulevard.
The alternative was for the city to solicit bids for the project, which would have added at least another year to the project timeline. The existing Heritage Square development, for which Bridge Housing was selected through a competitive bid, took 5 1/2 years to break ground, according to city Housing Director William Huang.
There are many lengthy steps needed to prepare for construction, including the sometimes arduous task of securing funding, officials said. But City Manager Steve Mermell said he expects the lead time to construction will actually be less than three years.
Homeless advocates celebrated the fast-tracking.
“Californians, in particularly Angelenos, have been working for years to cut red tape when it comes to building supportive housing because of the crisis we’re in,” said Annie Fox of interfaith group LA Voice.
There were 677 homeless people living on Pasadena streets and shelters at last year’s count, up 18 percent from the year before. Of that, 253 were people older than 50 — making that demographic the largest portion of Pasadena’s homeless population as well as its fastest growing. The number of homeless people over 50 living in Pasadena is up 65 percent since 2016, according to Huang.
City Council members and city officials said Bridge Housing’s track record of delivering projects on time and on budget makes it the best choice for this project.
Plus the developer would be able to efficiently combine resources, such as management efforts at the north and south projects, Mermell said.
The exact details of the new project will be worked out in the coming years. But Heritage plans to build as many as 70 units of permanent supportive housing for seniors on the building’s upper floors and space for two to four retail tenants on the ground level.
A working group consisting of Huang, Northwest commissioners and business representatives will provide input on project design, retail tenant preferences, house rules and security. Then, Bridge will conduct community outreach and negotiate a development agreement before more concrete plans are sent through the city approval process, including a final OK by the council.
The development will cost roughly $30 million, Huang estimated, and can be paid for with county and state grants, tax credits and tax-exempt bonds. Pasadena’s contribution could be the land, appraised at $5 million, which will remain under city ownership, he said.
Rents would likely be funded by Section 8 vouchers, while on-site services could could be paid for with county Measure H dollars, he said.
Bridge Housing officials said they would use a bare minimum of 20 percent local hires and subcontracting, though the already-built project used much more than that.
|
<filename>make_csv.py
from dataset.mirapri_retriever import MiraPriRetriever
START=4000
END=20000
INTERVAL=1000
for head in range(START, END, INTERVAL):
retriever = MiraPriRetriever(1)
retriever.get(range(head, head + INTERVAL))
filename="data/{}_{}.csv".format(head, head + INTERVAL)
retriever.to_csv(filename)
|
Leading through crisis The COVID-19 pandemic, societal racial reckonings, and pressure from parents and the media have put education leaders in a crisis. Carole Learned-Miller of the Leadership Academy in New York spoke with school and education organization leaders who saw their organizations through a variety of challenges, including the pandemic, racial inequities, a teacher strike, and a financial crisis. These leaders shared some of the principles that helped them through. These include building relationships, communicating clearly, listening to other views, having trusted advisers, being true to their values, and staying hopeful. Leaders describe how these principles helped them weather difficult times.
|
Amazon's Alexa personal assistant is super useful in the Echo and lot of fun to use. But if you don't have an Echo or can't buy one because you're outside of the US, it can be hard to appreciate Alexa's skill set. In light of this, Amazon has created a web app that lets you play with Alexa right in your browser.
You can access the web app at echosim.io and it lets you ask Alexa all kinds of questions. What it doesn't let you experience is the always listening nature of the Echo device and its far field microphone array — you have to click and hold a button on the site before you speak to it. (That makes it closer to the experience you get with the Amazon Tap than the Echo itself.)
The real purpose of this simulator is to let international devs see what Alexa is capable of, since Amazon doesn't yet sell the Echo or other Alexa devices outside of the US. Amazon says it was inspired by a project from a hackathon last year. Still, it's open to anyone with an Amazon account, so fire it up and start pelting Alexa with questions.
|
// Connects to the database
// Sets up all the prepared statements
// Requires the PGUSER, PGPASSWORD, PGHOST, PGPORT, and PGDATABASE environment variables to be set
func (Db *Database) connect() error {
var connStr string
connStr = "user=" + os.Getenv("PGUSER") + " "
connStr += "password=" + os.Getenv("PGPASSWORD") + " "
connStr += "host=" + os.Getenv("PGHOST") + " "
connStr += "port=" + os.Getenv("PGPORT") + " "
connStr += "dbname=" + os.Getenv("PGDATABASE") + " "
connStr += "search_path=tweetwatcher"
var err error
Db.db, err = sql.Open("postgres", connStr)
if err != nil {
return err
}
if err := Db.connected(); err != nil {
return nil
} else {
return err
}
if err := Db.setupStatements(); err != nil {
Db.Disconnect()
return err
}
return nil
}
|
Tumour-specific enhancement of thermoradiotherapy at mild temperatures by the vascular targeting agent 5,6-dimethylxanthenone-4-acetic acid The effect of combining the vascular targeting agent 5,6-dimethylxanthenone-4-acetic acid (DMXAA) with both radiation and hyperthermia treatments was investigated in a transplanted C3H mouse mammary carcinoma and a normal mouse tissue. Tumours were grown on the right rear foot of female CDF1 mice and treated when sized 200mm3. The foot skin of non-tumour-bearing CDF1 mice was used to assess normal tissue damage. Radiation and hyperthermia were given locally to the tumour/skin of restrained non-anaesthetized animals. DMXAA (20mg/kg) was dissolved in saline and injected intraperitoneally 1h after irradiating and then heating started 3h later. The endpoints were local tumour control within 90 days or the development of moist desquamation in skin between 11 and 23 days after treatment. The radiation dose (±95% confidence intervals) producing local tumour control in 50% of treated animals was 53 Gy for radiation alone. This value was significantly (Chi-squared test; p < 0.05) decreased to 47 Gy by DMXAA and to 47 Gy by heating (41.5°C/60min) 4h after irradiation. Combining both DMXAA and heating further reduced this to 30 Gy. When the heating temperature was decreased to 40.5°C, the effect of the triple combination was decreased but was still significant compared with radiation + DMXAA or radiation + hyperthermia. However, this enhancement disappeared at 39.5°C. Radiation damage of normal foot skin was not enhanced by combining DMXAA and hyperthermia at 41.5°C. In conclusion, adding DMXAA to thermoradiotherapy at 40.541.5°C significantly improved local tumour control without enhancing normal tissue damage. Thus, including a vascular targeting agent in a mild thermoradiotherapy treatment regimen is a useful approach that may lead to a re-evaluation of the use of hyperthermia in cancer treatment.
|
Ranks of amputees have risen steadily in 8 years of war
By Christian Davenport
Washington Post Staff Writer
Sunday, March 21, 2010; C01
Aug. 11, 2009, Afghanistan: After the blast, something didn't feel right, so 1st Lt. Joe Guyton looked down. Through the swirling dust, he glimpsed the white of his left shinbone. His right leg was gone, instantly vaporized, his uniform abruptly ending at the knee.
The pain would hit at any moment. He knew that. But for now, just after a bomb rocked his convoy while on patrol in Kandahar province, he was so amped up on adrenaline that he felt nothing more than an odd discomfort.
Don't look down, he told himself. Don't think about it.
Guyton, a recently married 28-year-old with soft blue eyes and red hair, had to hurry before he would be overwhelmed with agony. He shouted to his fellow soldiers to keep moving through the danger zone, to keep an eye out for the enemy, to report their wounds -- as he finally did himself. Soon, two soldiers were wrapping his legs in tourniquets.
He woke up in a military hospital in Germany.
Guyton, from Burke, became one of nearly 1,000 service members who have suffered amputations in the wars in Iraq and Afghanistan -- wars that, thanks to advances in battlefield medicine, are measured as much by wheelchairs and prosthetics as tombstones.
In the years since the Sept. 11, 2001, attacks, 967 American service members have lost at least one limb, as of March 1. Of them, 229 have lost more than one. The number of amputees mounted steadily as the U.S. military stormed into Afghanistan in late 2001, then focused on Iraq -- with an invasion in 2003 and a "surge" in 2007. More recently, the number has edged up again as the Obama administration has pumped more troops into Afghanistan.
These amputees are a fraternity of survivors whose private battles on the road, from blood-fresh wound to leather-tough scar, span the eight years of war. From Ground Zero to Baghdad to Afghanistan's Marja, their stories are reminders of conflicts that have lasted long enough for some amputees to be running marathons now, even as their newest brethren struggle with their prosthetics. Some are immobilized by depression, while others boldly venture into a world where children point at them and adults avert their gaze.
* * *
Dec. 16, 2001, Afghanistan: Cpl. Chris Chandler and his fellow Marines were among the first troops to arrive in Afghanistan. They had watched the twin towers fall while aboard a ship in Australia, then powered across the globe, and now they were here to get al-Qaeda leader Osama bin Laden and rout the Taliban.
"Everyone knew why we were there, what we were doing," Chandler said. "It was good to have some action."
For months, they helped secure villages and gather intelligence. And when there was a call to clear out some buildings, Chandler and his fellow scouts volunteered. Walking through what was supposed to be a cleared minefield in Kandahar province, Chandler stepped on an explosive and lost his left foot.
He became one of three amputees to land at Walter Reed Army Medical Center that month -- the war's first such casualties.
What he wanted most was for life to get back to normal again, to simply resume. He wanted to run. He wanted to stay in the Corps, maybe even return to Afghanistan.
Was any of that possible?
He had no idea. This was all new -- for him and for a country that had been jolted into combat and was unprepared to handle a generation of wounded warriors.
* * *
July 14, 2003, Iraq: Ryan Kelly thought that he had missed the war. He landed in Iraq in April, a month after the military launched its "shock and awe" push into the country and just before President George W. Bush declared that "major combat operations in Iraq have ended."
Kelly, 29, had served in Bosnia and thought his Iraq tour was going to end similarly, a combat-free mission focused on peacekeeping and nation-building. Troops would erect schools and hospitals, without worry, and then head home.
"We missed the initial invasion, and a lot of us were disappointed that we missed the big show," he said. "The war was over."
Iraq didn't feel terribly dangerous. Rarely did insurgents open fire; when they did, troops would joke about the errant potshots. The words "improvised explosive device" had only recently crept into soldiers' lingo.
"We went through Ramadi and Fallujah in unarmored Humvees day and night," Kelly said. "I didn't feel threatened."
But after a couple of months, soldiers started getting hit. There were stories of bombs buried along roads, hidden amid trash, even stuffed into dog carcasses. A rocket-propelled grenade nearly screamed into the window of Kelly's makeshift office.
Then, while he drove on a highway south of Baghdad, a makeshift bomb exploded near his Humvee, which didn't even have doors let alone protective armor. A piece of shrapnel the size of a TV remote control took his right leg off below the knee.
By then, a small but growing group of amputees had assembled at Walter Reed, which had taken on the feel of a wartime hospital. Patients took it upon themselves to let the new arrivals know that they were not alone. Which is exactly why the Air Force officer popped by Kelly's room.
He wore a pilot's flight suit and walked with no perceptible limp; he had to show Kelly his prosthetic before Kelly believed that the officer, too, had lost a leg. Kelly told him that he had wanted desperately to fly helicopters in the Army but was denied because of poor eyesight. The officer said he'd flown before he lost his leg, and would again.
That didn't seem impossible to Kelly, who at the time harbored his own ambition: to get back to his fellow soldiers in Iraq before their tour ended. It was perhaps delusional, but "that's what got me up in the morning," he said.
But then he needed more surgery, and the Army wasn't keen on sending a one-legged soldier to the front line. When his unit came home without him, it finally hit Kelly that he was no longer going to be a soldier.
But maybe he could fly.
His friends and family thought this was another quixotic quest that would end in disappointment. But it gave him a new purpose. In civilian life, he would be a pilot. This was another reason to get well.
Once he was discharged from Walter Reed and out of the Army, he had Lasik surgery to fix his eyesight. Then, a few months after learning to walk again, he began to learn how to fly.
Now the retired staff sergeant lives near Austin and flies helicopters for oil companies, ferrying supplies and equipment to rigs in the Gulf of Mexico. The jagged piece of shrapnel that took his leg off -- and still has a bit of his uniform melted to it -- hangs on his wall like a trophy.
* * *
May 7, 2007, Iraq: By the time Lt. Col. Gregory Gadson got to Iraq, it was not merely dangerous but out of control. Bush had ordered a surge as a last-ditch effort to tamp down the violence. Gadson's unit would play a key role in that.
By now, the Army had incorporated extensive training on IEDs into pre-deployment exercises, turning soldiers into human bomb detectors who could spot disturbed patches of earth, a protruding wire, anything suspicious.
"The first time we drove into Baghdad, I was like, 'Holy cow,' " said Gadson, who is now 44 and lives at Fort Belvoir. "Suspicious? I mean, everything is suspicious. It seemed like you could spend a whole day just trying to figure out what was a threat and what wasn't, and you wouldn't get anything done. You couldn't let it preoccupy you. It just became part of the environment. Like loud noise."
It wasn't surprising, then, that when Gadson got hit, he was on his way back to base after attending a memorial service for two soldiers killed by a makeshift bomb.
The first few months at Walter Reed, he didn't care that he had survived; he couldn't live like this, not without his legs. He'd lost both because of the blast and suddenly weighed 150 pounds instead of 210.
There had been huge advancements in prosthetic technology since the start of the war, and eventually he would be outfitted with the latest bionic, battery-powered legs that had sensors that help correct missteps. But at first, the depression was devastating. At his lowest point, he said, he cried for what seemed like 24 hours straight. He assured his family members that he wasn't suicidal, but he also told them that he had given up, that they should move on without him: "You guys just live. Just leave me in the corner in my wheelchair, and I'll manage."
Slowly, his wounds healed, and so did his psyche. There was no epiphany, no single event that turned him around. Just a vague notion that maybe today wouldn't be as bad as yesterday.
By August, three months after the explosion, he started to venture out of the hospital.
Among the first places he went to were his son's Pop Warner football games and his daughter's field hockey sessions. He didn't go into the stands like the other parents but cheered from his wheelchair on the sidelines, as close to the action as he could get.
* * *
February 2010, Walter Reed: In Germany, the doctors had told Guyton, the redhead from Burke, that they were sorry but that there was nothing they could do. They had to take his left leg as well, leaving him with two stumps.
Drugs had replaced his adrenaline, and still he didn't feel any pain. But his battlefield instincts were still switched on.
Don't look down, he told himself again. Don't think about it.
At Walter Reed, though, there was nothing to do but think about it. Reality sank in slowly. At first, he told himself he would master his new legs. Soon he would be walking. Then he would run. "And life will be normal again," he said.
But there's nothing normal about realizing that your wheelchair doesn't fit through the bathroom doorway at your parents' house. So you have to scoot through on your hands and then hoist yourself on top of the toilet bowl -- a gymnastic feat that takes strength and leverage and is precarious even with practice.
There's nothing normal about watching the muscles on your stump atrophy away, or the stares from other diners when he fell last year at 2 Amys pizzeria in Cleveland Park. And there's nothing normal about what he called "the sick jealousies" at Walter Reed, where he looks at other patients and thinks, "If I only had one leg."
"You see people out walking around, and it seems easy enough," he said. "But what you don't see is them at home using a wheelchair or scooting around. Try being at that level for a while. It's degrading. It's like being a child again. And you know this isn't a temporary situation. It's going to be like this for the rest of your life."
Chandler, one of the first amputees, felt the same way in the early weeks of his recovery. He was now officially handicapped, and people treated him as such.
"There's a huge stigma about what you can and can't do," he said.
Eventually, he met some older Navy SEALs who had lost limbs in motorcycle accidents and helped show him the way. He was told that he could no longer be a Marine, but with help from fellow Marines, he persuaded the Corps to keep him. Then he served three more tours, all in Iraq. He was told that he couldn't parachute out of airplanes, but he completed airborne school. He was told that he couldn't run a marathon, but in 2007 he did that, too.
Now Chandler works with other amputees at a San Diego military sports program affiliated with the U.S. Paralympic team. His experience as an amputee makes him something of a sage. Anger and frustration are normal, he tells them. So are nightmares, and although they might become more infrequent, they don't entirely go away. At least they haven't for him.
But just because life is forever changed, he tells the athletes, doesn't mean it's over. There is an after.
At times, that has been hard for Guyton to imagine. He's still getting used to his wife pushing him around in his chair. He's still adjusting to his new legs, which he says are "like walking on stilts."
But through the guys who came before, Guyton, now 29, has caught glimpses of his future -- and who he might become. After so much time stuck in the past, reliving that day, he has started to look forward.
He has got eight more months or so at Walter Reed, a long way to go before he's fully in the after. But he has started to think about what he'll do next. Maybe law school.
In December, Guyton bought a prep book for the entrance exams, but he hasn't opened it yet. He will, he says. Any day now.
Staff researcher Meg Smith contributed to this report.
© 2010 The Washington Post Company
|
Preparation, Characterization, and Optimization of Folic Acid-Chitosan-Methotrexate Core-Shell Nanoparticles by Box-Behnken Design for Tumor-Targeted Drug Delivery The objective of this study was to investigate the combined influence of independent variables in the preparation of folic acid-chitosan-methotrexate nanoparticles (FA-Chi-MTX NPs). These NPs were designed and prepared for targeted drug delivery in tumor. The NPs of each batch were prepared by coaxial electrospray atomization method and evaluated for particle size (PS) and particle size distribution (PSD). The independent variables were selected to be concentration of FA-chitosan, ratio of shell solution flow rate to core solution flow rate, and applied voltage. The process design of experiments (DOE) was obtained with three factors in three levels by Design expert software. Box-Behnken design was used to select 15 batches of experiments randomly. The chemical structure of FA-chitosan was examined by FTIR. The NPs of each batch were collected separately, and morphologies of NPs were investigated by field emission scanning electron microscope (FE-SEM). The captured pictures of all batches were analyzed by ImageJ software. Mean PS and PSD were calculated for each batch. Polynomial equation was produced for each response. The FE-SEM results showed the mean diameter of the core-shell NPs was around 304 nm, and nearly 30% of the produced NPs are in the desirable range. Optimum formulations were selected. The validation of DOE optimization results showed errors around 2.5 and 2.3% for PS and PSD, respectively. Moreover, the feasibility of using prepared NPs to target tumor extracellular pH was shown, as drug release was greater in the pH of endosome (acidic medium). Finally, our results proved that FA-Chi-MTX NPs were active against the human epithelial cervical cancer (HeLa) cells.
|
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* String.h (C) 2000-2015 */
/* */
/* Chaîne de caractère unicode. */
/*---------------------------------------------------------------------------*/
#ifndef ARCANE_UTILS_STRING_H
#define ARCANE_UTILS_STRING_H
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arccore/base/String.h"
#include "arcane/utils/UtilsTypes.h"
#include "arcane/utils/Limits.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace Arcane
{
typedef String String128;
typedef String String1024;
typedef String String4096;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#endif
|
package com.mishin870.exforbidden.forestrycomp.frame_analyzer;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlockWithMetadata;
import net.minecraft.item.ItemStack;
public class ItemBlockFrameAnalyzer extends ItemBlockWithMetadata {
public ItemBlockFrameAnalyzer(Block b) {
super(b, b);
}
/*@Override
public String getUnlocalizedName(ItemStack is) {
return this.getUnlocalizedName() + "_" + is.getItemDamage();
}*/
}
|
Water heaters designed for commercial, industrial and institutional applications are generally classified in one of three categories, instantaneous, semi-instantaneous and storage. A water heater falling in the instantaneous category is characterized by the absence of any significant storage capacity and by the fact that the heat exchanger occupies substantially all of the vessel or jacket. Instantaneous water heaters present difficult temperature control problems, inasmuch as cold water is delivered to the water heater and flows essentially straight through and out with no opportunity for blending and thus no opportunity for smoothing temperature variants that result from variations in demand, and the heat is supplied at a high rate, relative to the rate of water flow, thus emphasizing the lags between changes in draw and changes in heat input.
The semi-instantaneous category of water heaters is generally characterized by a relatively small tank which serves primarily as a mixing and blending zone in which water delivered from the heat exchanger is blended with water in the vessel. It is possible to obtain very close temperature control in semi-instantaneous water heaters, inasmuch as the blending principle tends to smooth out temperature gradients of water coming from the heat exchanger and thus makes the temperature of the delivered hot water less subject to variations in demand. The semi-instantaneous types often use heat anticipators or forward feed devices for further enhancement of temperature uniformity.
The storage-type water heaters are characterized by large tanks and relatively small heat exchangers and rely upon slow rates of heating of large volumes of water in the tank to maintain the water at a desired temperature. Of the three types, the storage types have the slowest recovery, and present problems of temperature control that often cannot readily be solved particularly in applications involving frequent large draws of hot water.
Each of the three types has various advantages and disadvantages, and the type selected is, of course, dependent upon the requirements of the particular installation. The present invention provides a solution to the problem, on the one hand, of the relatively high cost of presently known semi-instantaneous type water heaters, as compared to the instantaneous type, which results primarily from the large vessel required for presently known semi-instantaneous water heaters, and overcomes the disadvantage of relatively poor temperature control characteristic of instantaneous type water heaters. Accordingly, a water heater embodying the invention offers the size advantage of an instantaneous water heater and the temperature control advantage of a semi-instantaneous water heater.
Further, the present invention improves upon the operation of the hot water heater described in my patent referred to above by locating the control thermostat immediately above an apertured partition immediately above the heat exchanger in a tunnel having two side outlets with the circulating inlet opening into the tunnel for accurate and prompt control of the heating fluid on failure of the circulating pump to prevent overheating water from leaving the heater. The apertured partition or plate and the tunnel with two side outlets acts to stratify the heated water in the storage volume and blend it preventing excessively hot water from appearing at the top of the storage volume.
|
The Timing of portfolio Adjustments: a regime-Switching Approach The fact that the relationships among the returns of financial assets tend to be nonlinear and time-varying has important implications for asset allocation. To describe these two features, this paper first combines a copula function with the Markov switching technique to model the dependence structure across assets and then builds on this Markov Switching Copula model to present a procedure for the timing of portfolio adjustments. Our empirical evidence confirms that the dependence structure between high-risk and low-risk stocks in the Shanghai and Shenzhen markets is not static but switches between regimes over the course of the sample horizon considered in this paper. More importantly, as a result of such regime-switching characteristics of their dependence structure, our analysis of the out-of-sample asset allocation performance indicates that employing the procedure proposed in this paper to identify regime changes and decide when to adjust portfolio weights allows investors with the Constant Relative Risk Aversion utility to achieve both higher realized returns and higher certainty equivalent rate of returns than does the use of strategies based on static models.
|
Thermoneutral housing exacerbates non-alcoholic fatty liver disease in mice and allows for sex-independent disease modeling Non-alcoholic fatty liver disease (NAFLD), a common prelude to cirrhosis and hepatocellular carcinoma, is the most common chronic liver disease worldwide. Defining the molecular mechanisms underlying the pathogenesis of NAFLD has been hampered by a lack of animal models that closely recapitulate the severe end of the human disease spectrum, including bridging hepatic fibrosis. Here, we demonstrate that a novel experimental model employing thermoneutral housing, as opposed to standard housing, resulted in lower stress-driven production of corticosterone, augmented mouse proinflammatory immune responses and markedly exacerbated high fat diet (HFD)-induced NAFLD pathogenesis. Disease exacerbation at thermoneutrality was conserved across multiple mouse strains and was associated with augmented intestinal permeability, an altered microbiome and activation of inflammatory pathways associated with human disease. Depletion of Gram-negative microbiota, hematopoietic cell deletion of Toll-like receptor 4 (TLR4) and inactivation of the interleukin-17 (IL-17) axis resulted in altered immune responsiveness and protection from thermoneutral housing-driven NAFLD amplification. Finally, female mice, typically resistant to HFD-induced obesity and NAFLD, develop full-blown disease at thermoneutrality. Thus, thermoneutral housing provides a sex-independent model of exacerbated NAFLD in mice and represents a novel approach for interrogation of the cellular and molecular mechanisms underlying disease pathogenesis. Introduction NAFLD, a leading precursor of hepatocellular carcinoma (HCC) and liver transplantation 1,2, encompasses a disease spectrum ranging from benign steatosis to nonalcoholic steatohepatitis (NASH) to cirrhosis 3. Despite the clinical and public health significance, few effective therapies exist. Experimental and clinical evidence 4 suggests a complex interplay of multiple biological processes in disease development, including obesity, dysbiosis of the intestinal microbiome 5,6, heightened intestinal barrier permeability 7, metabolic endotoxemia and various inflammatory processes 5. Notably, the combination of HFD feeding, intestinal microbiome dysbiosis, augmented intestinal permeability and metabolic endotoxemia/ bacterial endotoxin (lipopolysaccharide; LPS) recognition all contribute to activation of both innate and adaptive immune responses central to the pathogenesis of NAFLD 5. TLR4 polymorphisms and elevated hepatic TLR4 expression have been associated with human NAFLD 8,9. In addition to innate immune system activation, TLR4 signaling also modulates multiple adaptive immune effector functions, including IL-17 axis activation 10. Notably, IL-17 levels correlate with obesity and NAFLD progression in mouse models 11, and the transition from steatosis to NASH in humans is associated with hepatic infiltration of IL-17 producing cells 12. Inactivation of the IL-17 axis inhibits progression from steatosis to NASH in mouse models 11. However, while existing mouse NAFLD models employing both genetic (leptin deficiency) and dietary interventions (high fat, carbohydrate and/or cholesterol diets) have proven informative, a closer recapitulation of parameters relevant to human disease is still desired. Specifically, mouse NAFLD models are associated with a sex bias and limited progression to bridging hepatic fibrosis-something not observed in human NAFLD. These limitations, and the overall lack of representative animal models for preclinical testing, may be contributing to the paucity of therapeutic approaches for NAFLD 13. The temperature at which mice are typically housed in research laboratories is associated with chronic cold stress that dramatically alters mouse physiology and immune responses 14. The thermoneutral zone (T N ), or temperature of metabolic homeostasis, for Mus musculus is 30-32°C 15. However, the standard temperature (T S ) range that mice are usually housed is between 20-23°C, a range chosen primarily for human comfort 14. Housing mice at T S, as opposed to T N, conditions leads to remarkable physiological changes, including a heart rate increase of over 200 beats per minute, a 30% increase in mean arterial blood pressure 16, an overall increase in energy expenditure (50-60%) 16,17 and sustained upregulation of catecholamine and corticosteroid production 18. Alleviating cold stress, through T N housing, alters immune function in a variety of mouse models, including basal cytokine production 19, responses to bacterial 20 and viral 21,22 infection and tumor immunity 14,23. Further, mice housed at T S fail to develop fever after LPS challenge, while T N housing promotes febrile responses following LPS challenge 20. In context of metabolic diseases, T N housing is required for modeling obesity in nude mice 17, exacerbates adipose tissue inflammation 24 and induces atherosclerosis in C57BL/6 WT mice 19. Importantly atherosclerosis, the number one cause of mortality in NAFLD patients 25, is a disease poorly modeled in WT mice. The relevance of T N housing to the modeling of human disease is emerging. The majority of people in developed nations, where obesity is classified as a disease, tend to spend most of their day within their thermoneutral zone via utility of climate control inside their dwellings. Further, exposure to non-thermoneutral conditions, profoundly impacts both immune response and metabolic disease in humans. Specifically, exposure to sustained cold stress leads to a dampened immune responsiveness to LPS challenge 26, and improves glucose tolerance in type 2 diabetics 27. Thus, given its role in both metabolism and inflammation, we hypothesized that T N housing would allow for development of an improved, exacerbated and more "human-like" mouse model of NAFLD. T N housing alters BAT function and immune responsiveness Adaptation to cold stress involves, among other things, heightened brown adipose tissue (BAT) activity, energy expenditure and glucocorticoid production 28. Compared to the mild cold stress associated with T S (22°C) housing, wild-type (WT) C57BL/6 mice at T N (30°C) resulted in lower total body energy expenditure 29 and expression of genes central to BAT activity, including glucocorticoid receptor (GR; N3cr1), beta 3 adrenergic receptor (3AR; Adrb3; catecholamine receptor), peroxisome proliferator-activated receptor gamma coactivator 1 alpha (Ppargc1a) and uncoupling protein 1 (Ucp1) (Fig. 1a). Further, compared to T S housing, T N housing resulted in lower serum concentrations of corticosterone (an immunosuppressive glucocorticoid 30 ) and splenic expression of genes known to inhibit inflammatory responses including, GR, beta 2 adrenergic receptor (2AR; Adrb2; catecholamine receptor), Ppargc1a, and uncoupling protein 2 (Ucp2) 31 (Fig. 1b,c). Notably, immune cells deficient in GR, 2AR or UCP-2 exhibit exacerbated proinflammatory cytokine production following LPS stimulation. These effects were not unique to splenic cells, as an unbiased approach employing RNA sequencing of peripheral blood mononuclear cells (PBMCs) revealed that T S housing, compared to T N, resulted in greater levels of gene expression in pathways known to negatively regulate the immune responses, including pathways responsible for decreased inflammatory responses, increased susceptibility to infection, and decreased acute inflammation ( Fig. 1d and Supplementary Table 1a). We next examined the functional relevance of altered immune gene expression observed with differences in housing temperature on proinflammatory cytokine production. In vivo analysis revealed that T N, compared to T S, housing exacerbated systemic TNF and IL-6 levels at baseline and after LPS challenge (Fig. 1e). These effects persisted ex vivo, as LPS stimulation of splenocytes and bone marrow-derived dendritic cells (BMDCs) from T Nhoused, as compared to T S -housed, mice resulted in heightened TNF and IL-6 production (Fig. 1f). Changes observed at T N, compared to T S, were found to be independent of alterations in bone marrow, PBMC, spleen and thymus cellularity and composition (Supplementary Fig. 1a-d). These findings indicate T N housing reverses the inhibition of immune responsiveness seen under standard housing conditions. The anti-inflammatory effects of glucocorticoids and corticosterone are well established. We thus examined the relevance of the corticosterone axis on immune responsiveness at T N. Administration of corticosterone to T N -housed mice was sufficient to reverse the exacerbated proinflammatory cytokine production associated with T N, as compared to T S, housing (Fig. 1g), suggesting that the corticosterone axis is functional at T N and plays a role in regulation of inflammatory vigor. Conserved effects were observed in humans following stimulation of human PBMCs with LPS in the presence of GR and 2AR agonists (data not shown) 35. In sum, these results suggest that ambient temperature profoundly alters BAT function, glucocorticoid production and the host innate immune responses in male C57BL/6 mice, and are congruent with reports indicating that T N housing promotes a more "humanlike" immune response 20. T N housing exacerbates HFD-driven NAFLD pathogenesis As the immune system plays a central role in the pathogenesis of obesity-associated sequelae, we hypothesized that T N housing, compared to T S housing, would exacerbate such effects in male, C57BL/6 WT mice. T N housing combined with HFD feeding initially accelerated weight gain compared to T S -housed HFD-fed animals, however prolonged dietary exposure nullified differences in weight gain, body lean or fat mass (Fig. 2a,b). Similar weight gain occurred despite a lower extent of food intake at T N (Fig. 2c), likely due to lower energy expenditure at T N 16,17. However, despite similar body weight and adiposity, at the time of harvest, T N -housed mice displayed heightened visceral adipose tissue immune cell infiltration and adipose tissue macrophage activation, compared to T S -housed, HFD-fed mice ( Supplementary Fig. 2a-c)-in agreement with a previous report 24. Given the role of obesity and adipose tissue inflammation in glucose dysmetabolism 36 we next evaluated the impact of T N housing on glucose homeostasis. T N housing, compared to T S, exacerbated glucose intolerance only when differences in body weights existed ( Supplementary Fig. 2d). These differences in glucose tolerance diminished once body weights were normalized ( Supplementary Fig. 2e). Further, with similar weight gain, both T N and T S mice displayed similar insulin sensitivity ( Supplementary Fig. 2f) which correlated with similar islet sizes and hepatic levels of AKT phosphorylation (data not shown). These data agree with previous reports describing the role of T N housing in modulation of glucose metabolism and insulin resistance in obesity 24. The impact of T N housing on NAFLD development and progression was examined next. Despite similar serum triglyceride and serum and hepatic cholesterol levels (Supplementary Fig. 2g-i), T N -housed, compared to T S -housed, obese mice had exacerbated liver weight and hepatic steatosis as quantified by hepatic triglyceride levels, Oil Red O staining and NAFLD activity score 37 ( Fig. 2d-h). Histological analysis, used to quantify NAFLD activity score, suggested that hepatocytes from T N -housed, as compared to T S -housed, obese mice exhibited elevated steatosis, and hepatocyte ballooning characterized by cellular swelling, rarefaction of the hepatocytic cytoplasm and clumped strands of intermediate filaments (Fig. 2g). These findings also correlated with lower gene expression of key lipid mediators known to be reduced during NASH (Fig. 2i) 38,39. Progression to, and the severity of, NASH under T N housing was examined next. Modest changes in expression of genes related to lipid handling, chemokine production and fibrosis were observed in mice fed a chow diet ( Supplementary Fig. 3a-c). In the context of HFD feeding, however, T N -housed mice exhibited robust exacerbation of hepatic chemokine expression ( Fig. 2j) 3, macrophage infiltration ( Fig. 2k), and bacterial translocation to the liver, compared to T S -housed mice (Fig. 2l). Further, T N -housed, as compared to T S -housed, obese mice, also displayed elevated expression of genes associated with hepatic fibrosis induction (Fig. 2m) and a 3-fold induction in hepatocellular damage as measured by serum alanine transaminase (ALT) levels ( Fig. 2n). However, despite such robust changes, the induction of overt bridging hepatic fibrosis was not observed in WT C57BL/6 mice ( Supplementary Fig. 3d). To begin to examine the effect of T N housing on hepatic gene expression in the presence or absence of dietary modulation, an unbiased approach utilizing RNASeq analysis of liver tissue was performed. Although T N, compared to T S housing, altered hepatic gene expression in chow fed mice, exposure to HFD exacerbated differential gene expression ( Supplementary Fig. 3e). In chow fed mice, analysis of differential gene expression revealed alterations in liver metabolism, including elevated expression of gene pathways associated with lipid metabolism and fatty acid oxidation ( Supplementary Fig. 3e,f and Supplementary Table 1b). In contrast, analysis of differential gene expression in HFD-fed mice revealed heightened expression of genes and gene pathways associated with collagen formation, apoptosis and HCC induction ( Fig. 2o and Supplementary Table 1c). Further, comparison of hepatic gene expression changes induced by T N versus T S housing on HFD to known gene expression changes induced by human NASH 40, revealed that T N drove similar changes in expression of genes associated with a variety of NAFLD-related pathways (e.g., Inflammatory response, Response to reactive oxygen species and Leukocyte activation; Supplementary Fig. 3g). Next, we compared whether changes in HFD-induced hepatic gene expression at T N or T S are more likely to predict gene expression patterns induced by human NASH 40. Utility of support vector machine analysis 41 determined that the gene expression differences induced by HFD feeding at T N allowed for an improved prediction of human NASH, over T S housing and HFD (Fig. 2p). These findings verify markedly exacerbated HFD-driven NAFLD pathogenesis and hepatocellular damage at T N and suggest an improved model for human disease. Although most commonly used for obesity and NAFLD modeling, the C57BL/6 mouse strain is highly resistant to induction of hepatic fibrosis. Thus, we next determined if the lack of overt hepatic fibrosis observed in C57BL/6 mice was strain specific. Notably, the AKR strain of mice develop robust obesity and NAFLD when fed a HFD 42. When housed at T N, as opposed to T S, and fed a HFD, AKR mice gained more weight but maintained similar visceral and subcutaneous adiposity ( Supplementary Fig. 4a,b). T N -housed, obese AKR mice exhibited greater liver weight, hepatic steatosis, and NAFLD activity scores compared to T S -housed AKR controls (Supplementary Fig. 4c-f). The lower NAFLD activity scores observed in AKR mice, compared to C57BL/6 mice, may be mouse strain dependent and/or due to shortened HFD exposure. The NAFLD activity score in AKR mice was associated with greater lobular inflammation and steatosis at T N, but limited hepatocyte ballooning was observed in either group at this time. This correlated with higher hepatic chemokine gene expression, macrophage infiltration, and hepatocellular damage (Supplementary Fig. 4g-i) in T N -housed, compared to T S -housed, AKR mice. Importantly, unlike in C57BL/6 mice, HFD feeding under conditions of T N housing, but not T S housing, was sufficient to induce fibrosis in AKR mice, as quantified by hepatic gene expression and Trichrome staining (Supplementary Fig. 4j-k). Together, these data indicate that the effects of T N housing on NAFLD pathogenesis are conserved across different mouse strains, and suggest that the use of obese AKR mice at T N may provide a novel and accelerated model for mechanistic interrogation of NAFLD-induced hepatic fibrosis. Adrenal glands are a central production site of circulating corticosterone and catecholamines. Immune responsiveness under cold stress is, in part, modulated by corticosterone and catecholamine levels. C57BL/6 adrenalectomized male mice fed a HFD exhibited similar weight gain and visceral and subcutaneous adiposity at either housing temperature ( Supplementary Fig. 5a-d). Unlike C57BL/6 mice with intact adrenal glands, adrenalectomized C57BL/6 mice housed at T N or T S exhibited similar liver weights, hepatic steatosis, lipid handling and chemokine gene expression, macrophage infiltration, expression of genes associated with induction of fibrosis and hepatocellular damage (Supplementary Fig. 5e-l). Notably, the lack of adrenal glands at T S housing, in combination with HFD, exacerbated hepatocellular damage compared to non-adrenalectomized mice at T S and resulted in levels similar to those observed in T N -housed mice ( Supplementary Fig. 5m). These data suggest that mediators produced by the adrenal glands play an important role in suppressing NAFLD progression during cold stress. Intestinal permeability and microbiome in T N -driven NAFLD Augmented intestinal permeability 7 and dysbiosis of the intestinal microbiome 6 contribute to human and mouse NAFLD progression. Although, histological analysis of the small intestine revealed no housing temperature or diet driven differences in immune cell infiltration ( Supplementary Fig. 6a), T N housing, compared to T S, exacerbated para-cellular intestinal permeability, as evidenced by translocation of FITC-dextran across the epithelium, and lowered trans-epithelial resistance on both chow and HFD ( Fig. 3a and Supplementary Fig. 6b). Further, T N housing, compared to T S housing, changed intestinal microbiome in as little as 2 weeks, prior to being placed on HFD ( Supplementary Fig. 6c,d). Extended exposure (12 weeks) of randomly separated WT C57BL/6 mice to differential ambient temperatures or HFD further exacerbated these differences, with obvious differences observed in every phyla analyzed after 24 weeks of exposure ( Fig. 3b and Supplementary Figs. 6e-k). Notably, T N housing enriched the representation of Bacteroidetes, while T S housing preferentially enriched for Firmicutes. Linear discriminant analysis effect size (LEfSe) analysis, which was employed to analyze data with specificity to the genus level, revealed congruent differences beyond the phylum level ( Supplementary Fig. 7). While the microbiome plays a role in NAFLD in both humans and mice, the two species display an inherently different microbial composition. Nevertheless, we examined whether the mouse microbiome at T N correlated more closely with microbiomes reported in NASH patients 6. Comparison of 16S rRNA sequences demonstrated that T N housing of mice on a HFD led to greater similarity of their gut microbiome to that observed in patients with NASH 6. Notably, this was seen in both phyla level alterations (Fig. 3c) and principle component analysis (Fig. 3d), where an upward shift (PC2) corresponds with a more NASHlike metagenome. T N housing in combination with HFD stress promoted expansion of Gram-negative Bacteriodetes (Fig. 3b). Antibiotic-mediated depletion of the Gram-negative microbiome in HFD-fed mice housed at T S and T N, did not alter total body weight gain, visceral and subcutaneous adiposity, hepatic weight or hepatic triglyceride accumulation, although T Shoused, antibiotic-treated mice displayed elevated glucose intolerance (Supplementary Fig. 8a-g). However, antibiotic treatment obviated the greater intestinal permeability observed in HFD fed mice housed at T N, compared to Ts (Fig. 3e), lowered NAFLD activity inflammation score (Fig. 3f,g), and protected from hepatocellular damage only at T N (Fig. 3h). Of note, these protective effects in NAFLD were specific to obese T N -housed mice and were not observed in obese, antibiotic-treated, T S -housed mice (Fig. 3f-h and Supplementary Fig. 8g). These data indicate that changes in intestinal microbiome composition are associated with T N -driven amplification of NAFLD. Hematopoietic TLR4 and IL-17 axis in T N -driven NAFLD LPS from Gram-negative bacteria activates TLR4. Our data indicate that TLR4 responsiveness is elevated at thermoneutrality (Fig. 1e,f). Additionally, TLR4 polymorphisms and TLR4 expression have been correlated with the progression of human NAFLD 9. Whether T N -driven modulation of innate immune responses is maintained on HFD has not been examined. RNASeq analysis of PBMCs from WT, C57BL/6 mice challenged with HFD, revealed greater levels of gene expression in pathways associated with cytokine production and TLR responsiveness ( Fig. 4a and Supplementary Table 1d). To determine the functional relevance of differential immune cell TLR4 expression, TLR4 fl/fl mice were utilized. Congruent with a previous report 43, Vav1-Cre-driven hematopoietic cell deletion of TLR4 in T S -housed mice did not hinder the progression of HFD-induced NAFLD (Fig. 4b-d). However, under T N housing, such deletion was sufficient to protect from HFD-driven increases in weight gain, visceral and subcutaneous adiposity, glucose intolerance, liver weight, histologically identifiable steatosis, hepatocyte ballooning and lobular inflammation and hepatocellular damage (Fig. 4b-d and Supplementary Fig. 9). These data indicate that TLR4 signaling is fundamentally modulated by ambient temperature in the context of HFD feeding, and that removing suppression of TLR4 signaling through T N housing can contribute to NAFLD pathogenesis. Induction of IL-6, IL-1 and IL-23 production is associated with Th17 cell polarization and IL-17 axis activation 10. Hepatic IL-6 expression is elevated in human NAFLD, and serum concentrations of IL-1 levels are higher in patients with metabolic syndrome 44,45. RNAseq analysis of PBMCs from WT C57BL/6 mice provided initial suggestions that T N housing, compared to T S housing, coupled with HFD resulted in greater expression of genes related to IL-17 production ( Fig. 5a and Supplementary Table 1d). We next examined whether T N housing altered TLR4 signaling-driven induction of mediators associated with activation of the IL-17 axis. LPS stimulation of BMDCs from T N -housed, compared to T S -housed, obese mice resulted in greater IL-6, IL-1 production and Il23a gene expression ( Supplementary Fig. 10a-c). Elevated production of these mediators correlated with exacerbated hepatic infiltration of CD4 + T cells capable of both single IL-17 + and dual IL-17 + /TNF + production, in T N -housed, obese mice (Fig. 5b,c). Notably, dual IL-17 + /TNF + producing CD4 + T cells exacerbate pathogenesis in mouse experimental autoimmune encephalomyelitis models 46 and have been associated with higher severity of Crohn's disease in humans 46,47. Hence, the contribution of IL-17 axis activation to T N -driven NAFLD pathogenesis was examined. Despite similar weight gain, visceral and subcutaneous adiposity, hepatic steatosis, and NAFLD activity score analysis (Fig. 5d,e and Supplementary Fig. 10d-h), T N -housed, obese, IL-17 axis-deficient mice (IL-17RA −/− and IL-17A −/− ) were protected from glucose intolerance, exacerbated liver weight and hepatocellular damage, compared to T N -housed WT controls ( Fig. 5f and Supplementary Fig. 10i,j). These findings suggest that IL-17 axis is a relevant factor in regulation of NAFLD pathogenesis and that, unlike TLR4 signaling, a role for IL-17 axis in NAFLD is conserved across housing temperatures. Serum amyloid A (SAA), an acute phase protein produced largely in the liver, is known to both activate TLR4 and promote Th17 cell differentiation via antigen presenting cells 48. T Nhoused, obese mice exhibited greater hepatic SAA 1 and 2 expression, compared to T S -housed mice ( Supplementary Fig. 11a), while deletion of IL-17RA, IL-17A or hematopoietic TLR4 was associated with lower hepatic expression of SAA1 ( Supplementary Fig. 11b,c). These data suggest that T N -mediated modulation of SAA production might represent a link between the activation of the TLR4 and IL-17 axes. T N housing allows for disease modeling in female mice Human NAFLD equally affects men and women 49. However, protection from severe HFDinduced obesity and NAFLD in C57BL/6 female mice precludes the interrogation of disease pathogenesis in a sex-independent manner. Hence we asked whether T N housing would allow for the induction of obesity and NAFLD in C57BL/6 female mice. As expected, T Shoused female mice fed HFD, as compared to chow, displayed mild weight gain over time (Fig. 6a). However, T N -housed female mice fed HFD, as compared to chow, exhibited robust obesity and total body adiposity (Fig. 6a,b)-to the levels observed in T N -housed male mice (Fig. 2). Further, in agreement with data in male mice, under conditions of robust weight gain, obese, T N -housed female mice displayed exacerbated glucose intolerance ( Supplementary Fig. 12a). Similarly, T N -housed, obese female mice exhibited greater liver weight, hepatic steatosis, hepatic chemokine expression 3, macrophage infiltration, and hepatic infiltration of both single IL-17 + and dual IL-17 + /TNF + producing Th17 cells, compared to T S-housed, HFDfed mice (Fig. 6c-i). Further, as in WT C57BL/6 male mice, these physiological changes in the liver correlated with greater expression of fibrosis-associated genes (Acta2, Col1a1 and Col1a2) and a greater degree of hepatocellular damage (Fig. 6j,k) but did not induce overt bridging hepatic fibrosis ( Supplementary Fig. 12b) in obese T N-housed compared to T S-housed female mice. Notably, T N -housed, compared to T S -housed, obese WT female mice exhibited greater SAA1 gene expression ( Supplementary Fig. 12c). Thus, T N housing allows for development of robust obesity and NAFLD in WT C57BL/6 female mice and, importantly, removes the sex bias typically associated with experimental modeling of mouse obesity and NAFLD. In sum, these findings demonstrate that T N housing-driven NAFLD pathogenesis represents a novel disease model associated with altered corticosterone levels, immune responses, metabolism, intestinal barrier integrity and intestinal microbiome (Fig. 6l). Discussion NAFLD research often involves the use of mouse models housed at a suboptimal, cold stress-inducing, ambient temperature (typically 22°C) that fails to comprehensively recapitulate human disease. In the case of NAFLD, current models in mice include a fundamental sex bias, unlike in humans; an inability to study the interplay between atherosclerosis and NAFLD; limited induction of pathways associated with development of hepatic fibrosis and hepatocellular carcinoma; and altered immune responsiveness compared to humans with this condition. While previous reports have demonstrated that housing mice at a thermoneutral temperature (T N ; 30°C) affects the pathogenesis of multiple infectious and metabolic complications, whether T N housing allows for an improved mouse NAFLD model has not been previously interrogated. Here, we demonstrate, in accordance with previous reports, that the cold stress associated with standard mouse housing procedures inhibits immune responses 14. Housing mice at T N upregulated immune responsiveness both in vivo and ex vivo, something suppressed by exogenous administration of corticosterone. Further, T N housing exacerbates cellular responsiveness to inflammatory ligands, without alteration of the cell type composition or numbers. Additional studies, however, are required to functionally examine the pathways central to altered immune cell responsiveness at T N. As such changes are sustained ex vivo, T N -driven modulation of cellular metabolism and epigenetics are likely to play a role and warrant further investigation. Robust exacerbation of NAFLD pathogenesis in context of T N housing and HFD-stress correlated with heightened hepatic steatosis, hepatic immune cell infiltration, elevated expression of genes associated with hepatic fibrosis and HCC, and hepatocellular damage. Therefore, T N -driven amplification of disease-propagating processes may allow for in-depth interrogation and improved definition of mechanisms central to NAFLD pathogenesis, including critical sites of inflammation, cell type(s), and immune mediators, using a genetically unbiased approach. However, despite robust disease exacerbation hepatic fibrosis was not observed in male or female WT C57BL/6 mice. Thus, additional examination of hepatic fibrosis development in C57BL/6 mice, using T N housing in combination with dietary challenges known to promote fibrosis (e.g., methionine choline deficient diets, high fat plus high cholesterol and high fat plus high fructose diets) 50 might offer a clear advantage over existing experimental NAFLD models for evaluating novel therapeutics. Notably, the induction of measureable hepatic fibrosis by HFD at T N is possible, as demonstrated in AKR mice. Employing these mice in future studies may provide a novel model for mechanistic interrogation of NAFLD-induced hepatic fibrosis. Lastly, T N housing appears to hold relevance to human disease and improve upon existing NAFLD models, even in C57BL/6 mice, as hepatic gene expression in this model provides improved prediction of human NASH. Interactions between the microbiome and the immune system are thought to play a key role in NAFLD. Augmented intestinal permeability also correlates with NASH severity 7. Notably, T N housing and HFD feeding resulted in heightened intestinal permeability and intestinal microbiome dysbiosis, which mirrors that observed with human obesity-and NASH-driven dysbiosis 6. Intestinal microbiome changes are certainly one of the many factors in the causal nexus that allow pronounced expression of the NAFLD phenotype in mice housed at thermoneutrality. However, given the consistency in the impact of T N housing in modulation of immune responses and metabolism among multiple research institutions, it is unlikely that a unique "microbiome mix", specific to a single institution, is driving observed differences independent of temperature effects. Notably, our data evoke several interesting questions and areas of future study, including: What are the bidirectional interactions between altered microbiome and altered immune responsiveness under T N housing? Does T N housing alter the immune response in gnotobiotic mice? Can protection from HFD-driven obesity in germ-free mice 51 be reversed utilizing T N housing? Are levels of specific microbial byproducts or microbial species thought to play a role in obesityassociated inflammation and NAFLD altered at T N 11,52 ? Our data suggest that TLR4 signaling, presumably via Gram-negative microbiome dysbiosis, plays a role in T N -driven NAFLD pathogenesis. Additionally, we demonstrate that this pathogenic role for Vav1-driven deletion of TLR4 expression is important only when mice are housed at T N. Of note, Vav1-cre can be activated in different cells, and the necessary hematopoietic and/or endothelial cell type should be evaluated 53. Also, whether TLR4's role is dependent on LPS or on induction of various endogenous TLR4 ligands (e.g., HMGB1, fibronectin, fibrinogen and resistin) that have been associated with NAFLD progression 43,54-56 is unknown. Our findings also highlight the functional effector relevance of the IL-17 axis in T N -housing driven NAFLD. The cellular and molecular mechanisms underlying IL-17 mediated effects in NAFLD are not well defined. IL-17-driven induction of chemokines (e.g., CXCL1 and CCL2) is associated with both macrophage and neutrophil hepatic infiltration and activation 57. Further, IL-17 has been demonstrated to play a significant role in liver fibrosis 58 Corticosterone levels are higher in mice housed at T S. Our findings demonstrated that exogenous administration of corticosterone in T N mice is sufficient to prevent augmented immune responsiveness. In contrast, adrenalectomy removes the inhibition of NAFLD pathogenesis associated with T S, as compared to T N, housing. These data suggest that specific signaling mediators released via the adrenal glands may play a suppressive role in NAFLD pathogenesis. Of note, chemical inhibition of -adrenergic receptor signaling exacerbates NAFLD progression in mice 60. However, -adrenergic receptors also play a homeostatic role in intestinal, liver and immune cells. Thus, future studies employing the use of 2AR, 3AR and/or GR cell type specific knockouts are required to better define contribution of these pathways to NAFLD pathogenesis. Human obesity and NAFLD are equally represented in males and females 49. The ability of T N housing to promote development of robust obesity and NAFLD in female mice further supports the relevance of T N housing to human physiology and allows for the realization of novel pathways associated with protection from HFD-driven obesity in female mice. Importantly, T N housing may allow for improved modeling of the contribution of maternal obesity on disease pathogenesis over generations of offspring. In addition, atherosclerosis, the most common cause of mortality in NAFLD patients 25, is another metabolic disease that lacks an appropriate mouse model that is similarly sex restrained. Importantly housing WT mice at T N in combination with a "western" diet allows for atherosclerosis induction in male C57BL/6 mice 19 and hence might provide for interrogation of pathways critical for the interplay of these two diseases as well as for removing sex bias in modeling atherosclerosis. Thus, housing temperature is an overlooked and very important variable in the modeling of human disease. Close attention to this variable has promise for discovery of novel mechanisms underlying disease pathogenesis and for improved modeling of the noncommunicable metabolic diseases that are causing an increasing burden of morbidity and mortality worldwide. Corticosterone Levels Serum corticosterone levels were detected by ELISA according to manufacturer's instructions (Arbor Assays). qRT-PCR Tissue samples were homogenized in TRIzol (Invitrogen), RNA was extracted, reverse transcribed to cDNA (Verso cDNA Synthesis Kit; Thermo Scientific) and subjected to qPCR analysis (Light Cycler 480 II; Roche) -all according to manufacturer's instruction as previously described 63 mRNA expression of each gene was compared to Beta-actin expression (endogenous housekeeping gene control). RNA sequencing and gene expression quantification PBMCs were collected from mice fed a chow or HFD for 8 weeks. Liver samples were collected from mice fed a chow or HFD for 24 weeks. Gene expression was determined by running 50 base pair single-end reads (~20 million reads per sample). All transcriptomic analyses were performed in StrandNGS. Following the removal of barcodes and primers, raw reads were aligned to the mm10 genome using annotations provided by UCSC with the following parameters: minimum percent identify = 90; maximum percent gaps = 5; minimum aligned read length = 25; number of matched to output per read = 1; and ignore reads with more than 5 matches. The proprietary aligner (COBWeb) is based on the Burrow Wheeler Transform method. Aligned reads were used to compute reads per kilobase per million (RPKM) using the Expectation-Maximization algorithm for the maximum likelihood estimation of expression. Further, RPKM were thresholded at 1 and normalized using the DESeq algorithm, which computes a normalization factor (NF) for each sample. Within each sample, each transcript is divided by that transcript's geometric mean across samples. The within-sample median of these values is that sample's NF. To obtain normalized counts, a sample's raw RPKM are divided by that sample's NF. Finally, normalized per-transcript RPKM were baselined to the median of all samples. Reasonably expressed transcripts (raw RPKM >3 in 100% of samples in at least one condition) were included for differential analysis. Differential expression was determined through 2-Way ANOVAs with an FDR-corrected p-value cutoff of 0.05 and a fold change requirement of >2. Raw data can be accessed at GSE80976. For pathway analysis, the database at toppgene.cchmc.org was employed, which amasses ontological data from over 30 individual repositories 64. We performed candidate gene prioritization on differentially regaled genes between T N and T S animals on HFD. Using the Toppgene Suite Candidate Prioritization tool, we ranked genes based on their functional similarity to NASH-related genes (extracted from the NASH-profiler; healthy obese v NASH at FDR-p-value<0.05 and FC>2). The top 20 ranked genes were submitted to ToppCluster and Cytoscape for ontological assessment and visualization (data depicted in Supplementary Fig. 3g). Further, using a human NASH cohort, we assessed the ability of genes differentially regulated under HFD conditions compared to chow in T S and T N housing conditions to discriminate between healthy obese controls and individuals with NASH. Using Support Vector Machine (SVM), we quantified the discriminative capabilities of the following gene sets: 1) differentially regulated between HFD and Chow in T N ; 2) differentially regulated between HFD and Chow in T S ; and 3) differentially regulated genes between healthy obese controls and NASH identified through the NASH-profiler 40. Model accuracy was compared between the three gene sets (data depicted in Fig. 2p). Cytokine Production Cytokines were detected employing biotinylated capture antibodies, detection antibodies and recombinant protein mouse standards. For in vivo production, in vivo cytokine capture assays were employed as previously described 11,65,66. Briefly, cytokines were detected using IVCCA employing biotinylated capture antibodies detection antibodies and recombinant protein mouse standards, all from eBioscience. Biotinylated capture antibodies were injected via tail vein or intraperitoneally and terminal serum collection was performed 24 hours later. For in vitro production, ELISAs were employed as previously described 11,65. For mice, cytokine levels of TNF and IL-6 were determined according to manufacturer's protocol (BD OptEIA). Cell culture and in vitro cytokine production Mouse BMDCs were differentiated as previously described 67. Mouse splenocytes and BMDCs were stimulated with ultrapure LPS (100 ng/mL; Invivogen) for 4 hours or with 1M norepinephrine or dexamethasone as noted. Obesity and NAFLD Model At 6 weeks of age mice were randomly separated into T S or T N housing facilities. After 2 weeks of acclimation, mice were fed either an irradiated high fat diet (HFD; Research Diets #D12492; 60% of calories from fat) or a chow diet (LAB Diet #5010; calories provided by carbohydrates , fat and protein )). All food was replaced weekly to avoid contamination. All mice were fasted overnight prior to, glucose metabolism testing, insulin tolerance testing, or terminal harvest (completed between 7-10am). Glucose and insulin tolerance tests were done as previously described 11. Briefly, following an overnight fast, glucose tolerance levels were determined by injecting mice with 10L of a 10% dextrose solution per gram of body weight and glucose levels were quantified kinetically at the times shown. For insulin tolerance testing, mice were given 10L of a 0.15 units/mL solution of insulin (Novolin) per gram of body weight. Hepatic triglyceride deposition, and serum alanine transaminase levels were quantified as previously described 11. NAFLD activity score (NAS) was determined from H&E staining by a certified pathologist according to standard practice 37. Total body fat, lean and water mass were determined by nuclear magnetic resonance (Whole Body Composition Analyzer; Echo MRI) 68. Histology Oil red O were performed on 5 m flash frozen tissue sections. Masson's Trichrome and hematoxylin and eosin staining were performed paraffin-embedded tissue blocks. Fibrosis quantification employed the use of an Aperio AT2 Slide Scanner, ImageScope (v. 12.3.1.5011), Color Deconvolution (v9) and Positive Pixel Count (v9; all Leica). Color deconvolution was used to identify the value of the positive stain. This value (0.622712) was subsequently identified in the slides using positive pixel count and percent positive area, which took into account the total number of pixels identified, was quantified. Flow Cytometry Single cell suspensions were derived from hepatic homogenate and stained with directly conjugated monoclonal antibodies or isotype controls. Staining for cytokine expression was completed after 4 hours of stimulation with 50 ng/mL Phorbol 12-Myristate 13-acetate (PMA; Promega), 1 g/mL Ionomycin (Calbiochem) and 10g/mL Brefeldin A (Gold Bio). Data collection and analysis were done as previously described 11,63. Briefly, cells were stained with Live/Dead stain (Zombie UV Dye: Biolegend) and with directly-conjugated monoclonal antibodies to CD45-AF700 Bacterial Translocation Liver tissue was homogenized in enriched thioglycollate medium, and subsequently cultured on TSA II/5% sheep blood plates (BD Bioscience). Intestinal Permeability 1 cm of freshly isolated jejunum was mounted in a U2500 dual Ussing chamber (Warner Instruments). The trans-epithelial resistance and FITC-dextran flux was determined as previously described 69. Microbiome Analysis Bacterial DNA was isolated from fecal material when mice arrived at the facility (-2 weeks), before they were placed on diet (0 weeks), and at 12 and 24 weeks after either diet was introduced. Partial 16S rRNA gene sequences were amplified targeting the hypervariable regions v1/v2 using primers 27f (AGAGTTTGATCCTGGCTCAG) and 338r (TGCTGCCTCCCGTAGGAGT). Equimolar amounts of all samples were subjected to sequencing using a MiSeq sequencer from Illumina. Data were then processed using mothur software 70 to determine phylotypes and operational taxonomic units (OTUs) and subjected to statistical analysis. LEfSe analysis was performed using the online tool at https:// huttenhower.sph.harvard.edu/galaxy/ 71. For comparison to the human microbiome, individual reads were assigned to taxonomy using the QIIME package 72. Similarly, raw human 16S sequencing data published by Zhu et al 6 were downloaded from http:// metagenomics.anl.gov/linkin.cgi?project=1195 and analyzed using the same QIIME assignment method and analytic pipeline as the mouse 16S read data. Taxonomic data was first analyzed using Mothur software to determine significantly different operational taxa units (OTUs). Similarly, GraphPad Prism (ver 6.07) was used to plot relative species abundance and compare between groups. The Mann-Whitney test was applied to the data to determine statistical significance of observed differences. Between-class principal component analysis was performed using the ade4 package (ver 5.12) in R, something available upon request from corresponding author. Mouse microbiome raw 16S rRNA can be accessed at http://metagenomics.anl.gov/linkin.cgi?project=mgp18319. Microbiome Manipulation For antibiotic mediated depletion of Gram-negative bacteria, a cocktail of neomycin and polymixin B sulfate (0.5 and 0.125 mg/mL, respectively) was added to the drinking water after 8 weeks of HFD feeding. Statistical Analysis Sample sizes were determined based on preliminary data, which with respect to obesity and NAFLD modeling included weight gain, hepatic triglyceride deposition, immune cell infiltration and hepatocellular damage. Statistical tests were employed for all data sets with similar variance. The test used was dependent on both the number of groups being compared and whether the data were normally distributed. For normally distributed data, Student's ttest was used when the comparison was two groups, while a one way ANOVA was employed for 3 or more groups, with Tukey's post hoc test to assess differences between specific groups. For non-parametric data sets the Mann-Whitney test was employed. Statistical analysis was completed using Prism 5a (GraphPad Software, Inc.). All values are represented as means + s.e.m. No animals were excluded from analysis. Studies were not blinded unless otherwise noted above. Supplementary Material Refer to Web version on PubMed Central for supplementary material. T N-housed (n = 29 per group) mice; LPS-stimulated, T S housed (n = 4 per group); and T N-housed (n = 3 per group) mice compared to unstimulated, T S-housed (n = 31 per group) mice. (f) Fold change in splenocyte or BMDC supernatants derived from T S -or T N -housed mice for TNF (n = 3 per group) and IL-6 (n = 5 per group). (g) Serum fold change for TNF in LPS-treated, T N-housed (n = 3 per group) and T N -housed mice also treated with 100mg/L corticosterone in drinking water (n = 4 per group) compared to LPS-treated, T S-housed mice (n = 4 per group). For bar graphs, data represents mean + s.e.m. Thermoneutral housing-driven modulation of hematopoietic TLR4 signaling regulates NAFLD progression. (a) 6 week-old WT C57BL/6 male mice were housed at T S (22°C) or T N (30°C) conditions for 2 weeks prior to initiation of 8 weeks of HFD. Upregulated gene expression pathways, and genes within pathways, determined by RNASeq analysis (n = 2 per group). (b-d) 6 week-old TLR4 fl/fl Vav1-Cre + and control TLR4 fl/fl Vav1-Cre − mice on a C57BL/6 background were housed at T S (22°C) or T N (30°C) for 24 weeks and fed a chow or HFD. (b) Representative liver histology by H&E staining at 40x magnification of TLR4 fl/fl Vav1-Cre − mice housed at 22°C (n = 3 per group) and 30°C (n = 5 per group) compared to TLR4 fl/fl Vav1-Cre + mice housed at 22°C (n = 4 per group) and 30°C (n = 4 per group). Scale bars, 50m. (c) NAFLD activity score as determined by histology. (d) Serum ALT levels of TLR4 fl/fl Vav1-Cre − mice housed at 22°C (n = 9 per group) and 30°C (n = 8 per group) compared to TLR4 fl/fl Vav1-Cre + mice housed at 22°C (n = 7 per group) and 30°C (n = 5 per group). Blue denotes T S (22°C); Red denotes T N (30°C). (a) A single experiment.
|
Oxides - Ultra Thin Oxides Gate oxide thickness is continuously scaled down to meet aggressive performance targets. Today a 6 nm oxide is called "thick" and 1.5 nm oxides are expected to hit manufacturing in less than 10 years according to the SIA roadmap. New aspects come into play when the oxide thickness is scaled down to only a few nm. Some of these aspects were put in a questionnaire which was available on the Internet and is reprinted in the appendix. The intention of the questionnaire was to get an idea of the background and opinion of the people in the group. Four responses to the questionnaire were received by e-mail before the workshop and 13 people answered the questionnaire at the first discussion session (total return: 17). The results of the questionnaire were reviewed on both evenings. Six out of the nine questions were used to initiate discussions. Additional topics came up during the discussion.
|
Antibodies to skeletal muscle actin and their reactivity with malignant melanoma of the choroid. Imprints of choroidal malignant melanoma cells were treated with serum containing antibodies to a purified preparation of actin derived from skeletal muscle. Evidence of a positive reaction, as shown by indirect immunofluorescence, substantiated an impression based on morphological criteria that choroidal melanoma cells contain actin protein. The significance of this protein in tumour biology is discussed, and a possible interference by antiactin antibodies in the immunodiagnosis of choroidal melanoma is highlighted.
|
/****************************************************************************
* libs/libc/net/lib_nametoindex.c
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <net/if.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <nuttx/net/netconfig.h>
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: if_nametoindex
*
* Description:
* The if_nametoindex() function returns the interface index corresponding
* to name ifname.
*
* Input Parameters:
* ifname - The interface name
*
* Returned Value:
* The corresponding index if ifname is the name of an interface;
* otherwise, zero. Although not specified, the errno value will be set.
*
****************************************************************************/
unsigned int if_nametoindex(FAR const char *ifname)
{
int sockfd = socket(NET_SOCK_FAMILY, NET_SOCK_TYPE, NET_SOCK_PROTOCOL);
if (sockfd >= 0)
{
struct ifreq req;
strlcpy(req.ifr_name, ifname, IF_NAMESIZE);
if (ioctl(sockfd, SIOCGIFINDEX, (unsigned long)&req) >= 0)
{
close(sockfd);
return req.ifr_ifindex;
}
close(sockfd);
}
return 0;
}
|
package io.datatok.djobi.exceptions;
import io.datatok.djobi.engine.stage.Stage;
public class StageException extends Exception {
private Stage stage;
public StageException(final Stage stage, final String message) {
super(message);
this.stage = stage;
}
public Stage getStage() {
return stage;
}
public StageException setStage(Stage stage) {
this.stage = stage;
return this;
}
}
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
int a=0,cmp;
char S[99];
gets(S);
cmp=strcmp("SUN",S);
if(cmp==0){
a=7;
}
cmp=strcmp("MON",S);
if(cmp==0){
a=6;
}
cmp=strcmp("TUE",S);
if(cmp==0){
a=5;
}
cmp=strcmp("WED",S);
if(cmp==0){
a=4;
}
cmp=strcmp("THU",S);
if(cmp==0){
a=3;
}
cmp=strcmp("FRI",S);
if(cmp==0){
a=2;
}
cmp=strcmp("SAT",S);
if(cmp==0){
a=1;
}
printf("%d \n",a);
return 0;
}
|
package pkg
import (
"github.com/go-logr/logr"
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
csibaremetalv1 "github.com/dell/csi-baremetal-operator/api/v1"
"github.com/dell/csi-baremetal-operator/api/v1/components"
)
const (
CSIName = "csi-baremetal"
// ports
PrometheusPort = 8787
LivenessPort = "liveness-port"
// timeouts
TerminationGracePeriodSeconds = 10
// volumes
LogsVolume = "logs"
CSISocketDirVolume = "csi-socket-dir"
// termination settings
defaultTerminationMessagePath = "/var/log/termination-log"
defaultTerminationMessagePolicy = corev1.TerminationMessageReadFile
)
type CSIDeployment struct {
node Node
controller Controller
extender SchedulerExtender
patcher SchedulerPatcher
}
func NewCSIDeployment(clientSet kubernetes.Clientset, log logr.Logger) CSIDeployment {
return CSIDeployment{
node: Node{
Clientset: clientSet,
Logger: log.WithValues(CSIName, "node"),
},
controller: Controller{
Clientset: clientSet,
Logger: log.WithValues(CSIName, "controller"),
},
extender: SchedulerExtender{
Clientset: clientSet,
Logger: log.WithValues(CSIName, "extender"),
},
patcher: SchedulerPatcher{
Clientset: clientSet,
Logger: log.WithValues(CSIName, "patcher"),
},
}
}
func (c *CSIDeployment) Update(csi *csibaremetalv1.Deployment, scheme *runtime.Scheme) error {
if err := c.node.Update(csi, scheme); err != nil {
return err
}
if err := c.controller.Update(csi, scheme); err != nil {
return err
}
if err := c.extender.Update(csi, scheme); err != nil {
return err
}
if err := c.patcher.Update(csi, scheme); err != nil {
return err
}
return nil
}
func GetNamespace(csi *csibaremetalv1.Deployment) string {
if csi.Namespace == "" {
return "default"
}
return csi.Namespace
}
func deploymentChanged(expected *v1.Deployment, found *v1.Deployment) bool {
if !equality.Semantic.DeepEqual(expected.Spec.Replicas, found.Spec.Replicas) {
return true
}
if !equality.Semantic.DeepEqual(expected.Spec.Selector, found.Spec.Selector) {
return true
}
if !equality.Semantic.DeepEqual(expected.Spec.Template, found.Spec.Template) {
return true
}
return false
}
func daemonsetChanged(expected *v1.DaemonSet, found *v1.DaemonSet) bool {
if !equality.Semantic.DeepEqual(expected.Spec.Selector, found.Spec.Selector) {
return true
}
if !equality.Semantic.DeepEqual(expected.Spec.Template, found.Spec.Template) {
return true
}
return false
}
func matchLogLevel(level components.Level) string {
switch level {
case components.InfoLevel:
return string(level)
case components.DebugLevel:
return string(level)
case components.TraceLevel:
return string(level)
default:
return string(components.InfoLevel)
}
}
func matchLogFormat(format components.Format) string {
switch format {
case components.JSONFormat:
return string(format)
case components.TextFormat:
return string(format)
default:
return string(components.TextFormat)
}
}
func constructFullImageName(image *components.Image, registry string) string {
var imageName string
if registry != "" {
imageName += registry + "/"
}
imageName += image.Name + ":" + image.Tag
return imageName
}
|
Photo: Archive
The economic, commercial, financial blockade imposed by the United States government on our country, for more than 50 years, constitutes a massive, flagrant, and systematic violation of the human rights of the Cuban people and an act of genocide, reads a statement issued by the Federation of Cuban Workers (CTC), approved by a meeting of its National Council this past weekend, October 21-22.
This hostile policy, that has caused billions of dollars in damages, interferes with the legitimate right of the Cuban people to live in peace, the document continued, and is intended to force the country to surrender to U.S. interests.
The CTC points out that maintaining the blockade affects the U.S. people as well, since they are denied the right to visit Cuba and learn about the reality here, while U.S. companies cannot maintain economic ties with the country.
Despite the damage caused by the blockade, the statement reads, it will "continue to be a useless attempt to defeat the Cuban Revolution."
"Cuban workers will continue to search for solutions to the difficulties, making every workplace and position a bastion of resistance … based on the intelligence, creativity, and collective ingenuity of our people."
The CTC statement also called on trade unions and friends around the world to condemn the blockade.
|
Immersion ultrasonic transducers The principles of operation and design of immersion ultrasonic transducers developed by the authors for excitation and reception of elastic vibrations in moving filament-like and plane-parallel materials, in particular, polymer fibbers and films, with an adjustable angle of input (reception) of probing signals into moving controlled object polymer fibbers and films at normal and high temperatures. The technical characteristics of the installation are given in which the converters developed by us are used, namely, sounding base (distance from the emitter to the receivers), the duration of the probing pulses, the frequency of filling and the duration of the probing pulses, the speed of the controlled object, the combined standard measurement uncertainties of the difference t of the propagation times of ultrasonic waves from the emitter to the first and second signal receivers, relative combined standard uncertainties of measurements of attenuation coefficient and velocity of propagation of ultrasonic waves.
|
/*
* LEGAL NOTICE
* This computer software was prepared by Battelle Memorial Institute,
* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830
* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE
* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY
* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this
* sentence must appear on any copies of this computer software.
*
* Copyright 2012 Battelle Memorial Institute. All Rights Reserved.
* Distributed as open-source under the terms of the Educational Community
* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php
*
* EXPORT CONTROL
* User agrees that the Software will not be shipped, transferred or
* exported into any country or used in any manner prohibited by the
* United States Export Administration Act or any other applicable
* export laws, restrictions or regulations (collectively the "Export Laws").
* Export of the Software may require some form of license or other
* authority from the U.S. Government, and failure to obtain such
* export control license may result in criminal liability under
* U.S. laws. In addition, if the Software is identified as export controlled
* items under the Export Laws, User represents and warrants that User
* is not a citizen, or otherwise located within, an embargoed nation
* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)
* and that User is not otherwise prohibited
* under the Export Laws from receiving the Software.
*
*/
package ModelInterface.PPsource.util;
import java.awt.geom.Point2D;
/**
* This class is used to convert from Goode's Homolosine mapping projection
* coodrinates (x, y) to latitude and longitude in degrees.
*/
public class HomolosineToDegreeConversion {
/**
* Number of regions in the Goode's Homolosine Projection
*/
private static int NUM_REGIONS = 12;
/**
* Private instance of this class.
*/
private static HomolosineToDegreeConversion thisConverter = new HomolosineToDegreeConversion();
/**
* Center meridians, one for each region.
*/
private double[] lon_center;
/**
* False easting, one for each region.
*/
private double[] feast;
/**
* Private constructor, this is a singleton class. Initialize the center meridians, and
* false eastings.
*/
private HomolosineToDegreeConversion() {
lon_center = new double[NUM_REGIONS];
feast = new double[NUM_REGIONS];
double rad;
double deg;
for(int i = 0; i < NUM_REGIONS; i++) {
// These are the degree locations for the various regions
switch(i) {
case 0:
deg = -100.0;
break;
case 1:
deg = -100.0;
break;
case 2:
deg = 30.0;
break;
case 3:
deg = 30.0;
break;
case 4:
deg = -160.0;
break;
case 5:
deg = -60.0;
break;
case 6:
deg = -160.0;
break;
case 7:
deg = -60.0;
break;
case 8:
deg = 20.0;
break;
case 9:
deg = 140.0;
break;
case 10:
deg = 20.0;
break;
case 11:
deg = 140.0;
break;
default:
deg = 0.0;
// error? how did it get here?
}
rad = Math.toRadians(deg);
lon_center[i] = rad;
// false easting should be location(radians) * radius
// radius is not available and thus this value must be
// access through the method getFalseEasting
feast[i] = rad;
}
}
/**
* Get the instance of this class.
* return The instance of this class.
*/
public static HomolosineToDegreeConversion getInstance() {
return thisConverter;
}
/**
* Get the central meridian for a region.
* param region The region for which to get the meridian.
* return The longitude of the meridian in radians.
*/
private double getCentralMeridian(int region) {
// put in checks to make sure this is a valid region?
return lon_center[region];
}
/**
* Get the false easting for a region, given the radius of the earth.
* param region The region for which to get the easting.
* param radius The radius of the earth.
* return The false easting in eastings? .. meters? .. something else?
*/
private double getFalseEasting(int region, double radius) {
// checks on regions and radius?
return feast[region] * radius;
}
/**
* Convert map projection (x, y) to latitude and longitude.
* param point Input map projection coordinates(x, y)
* param radius The radius of the earth used for the projection.
* return The corresponding degree coordinates (lat, long)
*/
public Point2D.Double convert(Point2D.Double point, double radius, boolean checkInt) {
// declare to throw exception if invalid point such as if it happens to
// fall in an interrupted zone?
double arg;
double theta;
int region;
double lat;
double lon;
// should I compute these values here instead of hard coding them?
if(point.getX() >= radius * 0.710987989993) { // above 40 44' 11.8"
if(point.getX() <= radius * -0.698131700798) { // left of -40
region = 0;
} else {
region = 2;
}
} else if(point.getY() >= 0.0) { // between 0 and 40 44'11.8"
if(point.getX() <= radius * -0.698131700798) { // left of -40
region = 1;
} else {
region = 3;
}
} else if(point.getY() >= radius * -0.710987989993) { // between 0 and -40 44' 11.8"
if(point.getX() <= radius * -1.74532925199) { // between -180 and -100
region = 4;
} else if(point.getX() <= radius * -0.349065850399) { // between -100 and -20
region = 5;
} else if(point.getX() <= radius * 1.3962634016) { // between -20 and 80
region = 8;
} else { // between 80 and 180
region = 9;
}
} else { // below -40 44' 11.8"
if(point.getX() <= radius * -1.74532925199) { // between -180 and -100
region = 6;
} else if(point.getX() <= radius * -0.349065850399) { // between -100 and -20
region = 7;
} else if(point.getX() <= radius * 1.3962634016) { // between -20 and 80
region = 10;
} else { // between 80 and 180
region = 11;
}
}
point = new Point2D.Double(point.getX() - getFalseEasting(region, radius), point.getY());
double piOverTwo = Math.PI / 2;
if(region == 1 || region == 2 || region == 3 || region == 4 || region == 5 ||
region == 8 || region == 9) {
lat = point.getY() / radius;
if(Math.abs(lat) > piOverTwo) {
// error?
System.out.println("dont know what this is, throwing null at x: "+point.x+" y: "+point.y);
return null;
}
// maybe give a little more flex the Double.MIN_VALUE
if(Math.abs(lat - piOverTwo) <= Double.MIN_VALUE) {
lon = getCentralMeridian(region);
} else {
lon = getCentralMeridian(region) + point.getX() / (radius * Math.cos(lat));
// adjust??
}
} else {
arg = (point.getY() + 0.0528035274542 * radius * Math.signum(point.getY())) / (Math.sqrt(2) * radius);
if(arg > 1.0) {
// this is an interrupted value throw exception?
System.out.println("got interrupted space, throwing null at x: "+point.x+" y: "+point.y);
return null;
}
theta = Math.asin(arg);
lon = getCentralMeridian(region) + (Math.PI * point.getX()) / (2 * Math.sqrt(2) * radius * Math.cos(theta));
if(lon < -1* Math.PI) {
// this is an interrupted value throw exception?
System.out.println("got interrupted space2, throwing null at x: "+point.x+" y: "+point.y);
return null;
}
arg = (2*theta + Math.sin(2*theta)) / Math.PI;
if(arg > 1.0) {
// this is an interrupted value throw exception?
System.out.println("got interrupted space3, throwing null at x: "+point.x+" y: "+point.y);
return null;
}
lat = Math.asin(arg);
}
// becuase of precision problems 180 and -180 may be switched
if(((point.getX() < 0) && ((Math.PI - lon) < Double.MIN_VALUE)) || ((point.getX() > 0) && ((Math.PI + lon) < Double.MIN_VALUE))) {
System.out.println("Did flip");
lon *= -1;
}
if(checkInt&&checkInInterrupted(lat, lon, region)) {
// this is an interrupted value throw exception?
System.out.println("got interrupted space4, throwing null at x: "+point.x+" y: "+point.y+" lat: "+Math.toDegrees(lat)+" lon: "+Math.toDegrees(lon)+" in region: "+region);
return null;
} else {
// we did it!!
return new Point2D.Double(Math.toDegrees(lat), Math.toDegrees(lon));
}
}
/**
* Check whether the calculated lat / long are in the interrupted space.
* param lat The lattitude to check.
* param lon The longitude to check.
* param region The region this point is supposed to be in.
* return True if it is in interrupted space, false otherwise.
*/
private boolean checkInInterrupted(double lat, double lon, int region) {
double pi = Math.PI;
double ep = Double.MIN_VALUE;
switch(region) {
case 0:
return (lon < -(pi+ep) || lon > -0.698131700798);
case 1:
return (lon < -(pi+ep) || lon > -0.698131700798);
case 2:
return (lon < -0.698131700798 || lon > (pi+ep));
case 3:
return (lon < -0.698131700798 || lon > (pi+ep));
case 4:
return (lon < -(pi+ep) || lon > -1.74532925199);
case 5:
return (lon < -1.74532925199 || lon > -0.349065850399);
case 6:
return (lon < -(pi+ep) || lon > -1.74532925199);
case 7:
return (lon < -1.74532925199 || lon > -0.349065850399);
case 8:
return (lon < -0.349065850399 || lon > 1.3962634016);
case 9:
return (lon < 1.3962634016 || lon > (pi+ep));
case 10:
return (lon < -0.349065850399 || lon > 1.3962634016);
case 11:
return (lon < 1.3962634016 || lon > (pi+ep));
default:
// error?
return true;
}
}
}
|
import { MailHeaderFooterTranslation } from "./MailHeaderFooterTranslation";
import { SalesChannel } from "../../system/sales-channel/SalesChannel";
/**
* @public
*/
export interface MailHeaderFooter {
name: string | null;
systemDefault: boolean;
description: string | null;
headerHtml: string | null;
headerPlain: string | null;
footerHtml: string | null;
footerPlain: string | null;
salesChannels: SalesChannel[] | null;
translations: MailHeaderFooterTranslation[] | null;
}
|
Valdet Gashi the Thai Kickboxing world champion. Photo: Islamic State social media.
ERBIL, Kurdistan Region — Former Thai kickboxing world champion turned ISIS recruiter Valdet Gashi has reportedly been killed among ISIS militants in Syria, Gashi’s immediate family said Tuesday.
A German of Albanian ancestry, Gashi was a two-time champion in world mixed martial arts and was from the German state of Bavaria. He became a jihadist and joined ISIS in Syria in July 2014.
Swiss TV channel SRF cited Gashi’s brother, who said his brother was killed last Saturday under vague circumstances in Syria.
In the interview Gashi said he was working for ISIS by patrolling the Euphrates River near the Turkish border and looking for smugglers bringing in illegal goods like cigarettes, alcohol or drugs.
Gashi travelled to Syria with three other Thai kickboxers. One of them was known to be a Kurdish Muslim named Hajan who was killed in a battle with the Kurdish People’s Protection Units (YPG) in the Rojava Kurdish region of Syria.
The four friends reportedly carried out many brutal punishments while serving in the jihadist ranks.
In May, the UN reported that some 20,000-22,000 foreign fighters had joined ISIS in Syria and Iraq.
My they all rest in piss, murdering bastards, only God knows how many people they have raped, tortured and murdered, well done YPG!
Oh,is He dead? Well I guess he found what He was looking for. Good for Him and even better for humanity though. One less.
Tags : ISIS, Syria, Valdet Gashi.
|
Refinements to a Procedure for Estimating Airfield Capacity This paper presents a method for obtaining airfield capacity estimates using historical data from FAA's Aviation System Performance Metrics (ASPM) database. The process first involves merging individual flights and quarter-hour airport runway operations data sets from ASPM to create a new data set. Data for Newark Liberty International Airport (EWR) in New Jersey and San Diego International Airport in California from 2006 to 2011 were used. Then, filters for meteorological condition, runway configuration, called rates, and fleet mix were applied to the two airport data sets. The filtered data sets were then used in a censored regression model of capacity that included queue length (number of aircraft waiting to arrive or depart) and arrivaldeparture throughput count splits as independent variables. These attributes were found to affect airfield capacity at statistically significant levels, and parameters had expected signs and magnitudes. Additionally, capacities under ideal conditions were found to be reasonably close to other sources. The model also confirmed that average capacities at EWR during hours when a ground delay program (GDP) was running were lower than when there was no GDP in effect. The method described in this paper could be used to more precisely quantify airfield capacities in specific conditions of particular interest to air traffic controllers and airport operators to better facilitate decisions that rely heavily on a good understanding of capacity in these conditions. The data exploration and preparation undertaken as part of the study reveal some of the finer points of the ASPM data and how they can be used in a more meaningful way for airfield capacity estimation.
|
/* do initial pass through args to check for options that affect driver */
void
check_for_driver_controls (int argc, char *argv[])
{
int i;
char *s;
for (i = 1; i < argc; i++) {
if (strncmp(argv[i], "-woff", 5) == 0) {
s = next_string_after("-woff",argv,&i);
if (strcmp(s, "options") == 0) {
print_warnings = FALSE;
} else if (strcmp(s, "all") == 0) {
print_warnings = FALSE;
}
}
else if (strcmp(argv[i], "-fullwarn") == 0) {
fullwarn = TRUE;
}
else if (strcmp(argv[i], "-v") == 0) {
fullwarn = TRUE;
}
else if (strcmp(argv[i], "-fbgen") == 0) {
Gen_feedback = TRUE;
}
else if (strcmp(argv[i], "-fbuse") == 0) {
Use_feedback = TRUE;
}
else if (strcmp(argv[i], "-E") == 0) {
last_phase = P_any_cpp;
}
else if (strcmp(argv[i], "-ignore_suffix") == 0) {
ignore_suffix = TRUE;
}
else if (strcmp(argv[i], "-i32") == 0) {
abi = ABI_I32;
}
else if (strcmp(argv[i], "-i64") == 0) {
abi = ABI_I64;
}
else if (strcmp(argv[i], "-ia32") == 0) {
abi = ABI_IA32;
}
}
}
|
Local mobilisations and the formation of environmental networks in a democratizing Tunisia ABSTRACT This study examines the environmental protests that occurred in Tunisia after the 2011 uprisings. It analyses the factors underpinning the rise of the environmental networks during the period of transition (20112014). It details the mobilising strategies that were crucial for the networks growth or survival during this period of institutional instability. The study shows how networks leaders were able to bring together social and political actors from different backgrounds and ideological orientations. It is argued that the ability of networks to develop new distinctive collective identities was crucial for network sustainability. Those networks and actors who did not develop new clearly defined environmental identities and continued to rely importantly on pre-existing (authoritarian) structures and practices were more negatively impacted by ideological cleavages and political calculations. Empirically, the contribution builds on interviews and observations, as well as documents collected from Tunisian municipalities between 2013 and 2015. Conceptually, the research proposes a bottom-up perspective that highlights the interplay between micro- and macro-dynamics and strategies during a political transition. The analysis details the actors capacity to build alliances via interpersonal relations at the micro level, and their strategies to engage with institutional actors and processes.
|
/**
* <p>
* Clase Java para anonymous complex type.
*
* <p>
* El siguiente fragmento de esquema especifica el contenido que se espera
* que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="SupportVAT" minOccurs="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="tNO"/>
* <enumeration value="tYES"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FormNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TransactionCategory" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {})
public static class StockTransferTaxExtension {
@XmlElement(namespace = "", name = "SupportVAT")
protected String supportVAT;
@XmlElement(namespace = "", name = "FormNumber")
protected String formNumber;
@XmlElement(namespace = "", name = "TransactionCategory")
protected String transactionCategory;
/**
* Obtiene el valor de la propiedad supportVAT.
*
* @return possible object is {@link String }
*
*/
public String getSupportVAT() {
return supportVAT;
}
/**
* Define el valor de la propiedad supportVAT.
*
* @param value allowed object is {@link String }
*
*/
public void setSupportVAT(String value) {
this.supportVAT = value;
}
/**
* Obtiene el valor de la propiedad formNumber.
*
* @return possible object is {@link String }
*
*/
public String getFormNumber() {
return formNumber;
}
/**
* Define el valor de la propiedad formNumber.
*
* @param value allowed object is {@link String }
*
*/
public void setFormNumber(String value) {
this.formNumber = value;
}
/**
* Obtiene el valor de la propiedad transactionCategory.
*
* @return possible object is {@link String }
*
*/
public String getTransactionCategory() {
return transactionCategory;
}
/**
* Define el valor de la propiedad transactionCategory.
*
* @param value allowed object is {@link String }
*
*/
public void setTransactionCategory(String value) {
this.transactionCategory = value;
}
}
|
<filename>examples/chat/main.cpp
#include <spdlog/spdlog.h>
#include <g6/http/client.hpp>
#include <g6/http/router.hpp>
#include <g6/http/server.hpp>
#include <g6/io/context.hpp>
#include <g6/ws/server.hpp>
#include <unifex/scope_guard.hpp>
#include <unifex/sync_wait.hpp>
#include <unifex/task.hpp>
#include <unifex/when_all.hpp>
#include <ranges>
using namespace g6;
namespace fs = std::filesystem;
namespace rng = std::ranges;
namespace js {
namespace detail {
#include <js_main.hpp>
inline const std::string_view main{reinterpret_cast<const char *>(main_js), main_js_len};
}// namespace detail
using detail::main;
}// namespace js
namespace html {
namespace detail {
#include <html_index.hpp>
inline const std::string_view index{reinterpret_cast<const char *>(index_html), index_html_len};
}// namespace detail
using detail::index;
}// namespace html
namespace {
inplace_stop_source g_stop_source{};
}
#include <csignal>
#include <list>
void terminate_handler(int) {
g_stop_source.request_stop();
spdlog::info("stop requested !");
}
std::string_view as_string_view(span<std::byte const> const &data) noexcept {
return {reinterpret_cast<char const *>(data.data()), data.size()};
}
int main(int argc, char **argv) {
#ifdef G6_WEB_DEBUG
spdlog::set_level(spdlog::level::debug);
#endif
io::context context{};
std::signal(SIGINT, terminate_handler);
std::signal(SIGTERM, terminate_handler);
auto server = web::make_server(context, web::proto::http, *net::ip_endpoint::from_string("127.0.0.1:0"));
auto server_endpoint = *server.socket.local_endpoint();
fs::path root_path = ".";
spdlog::info("server listening at: http://{}", server_endpoint.to_string());
async_scope scope{};
std::list<ws::server_session<net::async_socket> *> all_sessions{};
auto router = router::router{
std::make_tuple(),// global context
http::route::get<R"(/)">([&](router::context<http::server_session<net::async_socket>> session,
router::context<http::server_request<net::async_socket>> request) -> task<void> {
auto page = fmt::format(html::index, fmt::arg("address", server_endpoint.address().to_string()),
fmt::arg("port", server_endpoint.port()), fmt::arg("js_main", js::main));
co_await net::async_send(*session, http::status::ok, as_bytes(span{page.data(), page.size()}));
}),
http::route::get<R"(/chat)">([&](router::context<http::server_session<net::async_socket>> session,
router::context<http::server_request<net::async_socket>> request,
router::context<async_scope> scope) -> task<void> {
spdlog::info("got chat request on {}", session->remote_endpoint().to_string());
auto ws_session = co_await web::upgrade_connection(web::proto::ws, *session, *request);
spdlog::info("connection upgraded...");
scope->spawn(
[](auto session, auto &all_sessions) -> task<void> {
all_sessions.push_front(&session);
spdlog::info("websocket connection started...");
while (true) try {
auto message = co_await net::async_recv(session);
while (net::has_pending_data(message)) {
auto data = co_await net::async_recv(message);
spdlog::info("data from {}: {}", session.remote_endpoint().to_string(),
as_string_view(data));
spdlog::info("{} other connections", std::size(all_sessions) - 1);
for (auto other_session : all_sessions) {
if (*other_session != session) {
spdlog::info("sending data to: {}",
other_session->remote_endpoint().to_string());
co_await net::async_send(*other_session, data);
}
}
}
} catch (std::system_error const &error) {
if (error.code() != std::errc::connection_reset) {
spdlog::error("error on {}: {}", session.remote_endpoint().to_string(), error.what());
}
spdlog::error("connection reset: {}", session.remote_endpoint().to_string());
break;
}
std::erase_if(all_sessions, [&](auto const &other) { return other == &session; });
spdlog::info("{} remaining connections", std::size(all_sessions));
}(std::move(ws_session), all_sessions),
context.get_scheduler());
throw std::system_error{std::make_error_code(std::errc::connection_reset)};
}),
router::on<R"(.*)">([](router::context<http::server_session<net::async_socket>> session,
router::context<http::server_request<net::async_socket>> request) -> task<void> {
spdlog::info("unhandled: {} {}", request->url(), request->method());
std::string_view not_found = R"(<div><h6>Not found</h6><p>{}</p></div>)";
co_await net::async_send(*session, http::status::not_found,
as_bytes(span{not_found.data(), not_found.size()}));
})};
sync_wait(when_all(
[&]() -> task<void> {
co_await web::async_serve(server, g_stop_source, [&]<typename Session>(Session &session) {
return [root_path, &session, &router,
&scope = scope]<typename Request>(Request request) mutable -> task<void> {
co_await router(request.url(), request.method(), std::ref(session), std::ref(request),
std::ref(scope));
while (net::has_pending_data(request)) {
co_await net::async_recv(request);// flush unused body
}
};
});
spdlog::info("terminated !");
}(),
[&]() -> task<void> {
context.run(g_stop_source.get_token());
co_return;
}()));
sync_wait(cleanup(scope));
}
|
<reponame>factitious/hddm
"""
.. module:: HDDM
:platform: Agnostic
:synopsis: Definition of HDDM models.
.. moduleauthor:: <NAME> <<EMAIL>>
<NAME> <<EMAIL>>
"""
from collections import OrderedDict
import numpy as np
import pymc as pm
import pandas as pd
import hddm
import kabuki
import inspect
from kabuki.hierarchical import Knode
from scipy.optimize import fmin_powell, fmin
try:
from IPython import parallel
from IPython.parallel.client.asyncresult import AsyncResult
except ImportError:
pass
class AccumulatorModel(kabuki.Hierarchical):
def __init__(self, data, **kwargs):
# Flip sign for lower boundary RTs
data = hddm.utils.flip_errors(data)
self.std_depends = kwargs.pop('std_depends', False)
super(AccumulatorModel, self).__init__(data, **kwargs)
def _create_an_average_model(self):
raise NotImplementedError("This method has to be overloaded. See HDDMBase.")
def _quantiles_optimization(self, method, quantiles=(.1, .3, .5, .7, .9 ), n_runs=3):
"""
quantile optimization using chi^2.
Input:
quantiles <sequance> - a sequance of quantiles.
the default values are the one used by Ratcliff (.1, .3, .5, .7, .9).
Output:
results <dict> - a results dictionary of the parameters values.
The values of the nodes in single subject model is update according to the results.
The nodes of group models are not updated
"""
#run optimization for group model
if self.is_group_model:
#create an average model
average_model = self.get_average_model(quantiles)
#optimize
results, bic_info = average_model._optimization_single(method=method, quantiles=quantiles,
n_runs=n_runs, compute_stats=False)
#run optimization for single subject model
else:
results, bic_info = self._optimization_single(method=method, quantiles=quantiles,
n_runs=n_runs, compute_stats=True)
if bic_info is not None:
self.bic_info = bic_info
return results
def get_average_model(self, quantiles=(.1, .3, .5, .7, .9)):
#create an average model (avergae of all subjects)
try:
average_model = self._create_an_average_model()
average_model._is_average_model = True
except AttributeError:
raise AttributeError("User must define _create_an_average_model in order to use the quantiles optimization method")
#get all obs nodes
obs_db = self.get_observeds()
#group obs nodes according to their tag and (condittion)
#and for each group average the quantiles
for (tag, tag_obs_db) in obs_db.groupby(obs_db.tag):
#set quantiles for each observed_node
obs_nodes = tag_obs_db.node;
#get n_samples, freq_obs, and emp_rt
stats = [obs.get_quantiles_stats(quantiles) for obs in obs_nodes]
n_samples = sum([x['n_samples'] for x in stats])
freq_obs = sum(np.array([x['freq_obs'] for x in stats]),0)
emp_rt = np.mean(np.array([x['emp_rt'] for x in stats]),0)
#get p_upper
p_upper = np.mean(np.array([obs.empirical_quantiles(quantiles)[2] for obs in obs_nodes]),0)
#set average quantiles to have the same statitics
obs_knode = [x for x in self.knodes if x.name == 'wfpt'][0]
node_name = obs_knode.create_node_name(tag) #get node name
average_node = average_model.nodes_db.ix[node_name]['node'] #get the average node
average_node.set_quantiles_stats(quantiles, n_samples, emp_rt, freq_obs, p_upper) #set the quantiles
return average_model
def optimize(self, method, quantiles=(.1, .3, .5, .7, .9 ), n_runs=3, n_bootstraps=0, parallel_profile=None):
"""
Optimize model using ML, chi^2 or G^2.
:Input:
method : str
Optimization method ('ML', 'chisquare' or 'gsquare').
quantiles : tuple
A sequence of quantiles to be used for chi^2 and G^2.
Default values are the ones used by Ratcliff (.1, .3, .5, .7, .9).
n_runs : int <default=3>
Number of attempts to optimize.
n_bootstraps : int <default=0>
Number of bootstrap iterations.
parrall_profile : str <default=None>
IPython profile for parallelization.
:Output:
results <dict> - a results dictionary of the parameters values.
:Note:
The values of the nodes in single subject model is updated according to the results.
The nodes of group models are not updated
"""
results = self._run_optimization(method=method, quantiles=quantiles, n_runs=n_runs)
#bootstrap if requested
if n_bootstraps == 0:
return results
#init DataFrame to save results
res = pd.DataFrame(np.zeros((n_bootstraps, len(self.values))), columns=list(self.values.keys()))
#prepare view for parallelization
if parallel_profile is not None: #create view
client = parallel.Client(profile=parallel_profile)
view = client.load_balanced_view()
runs_list = [None] * n_bootstraps
else:
view = None
#define single iteration bootstrap function
def single_bootstrap(data,
accumulator_class=self.__class__, class_kwargs=self._kwargs,
method=method, quantiles=quantiles, n_runs=n_runs):
#resample data
new_data = data.ix[np.random.randint(0, len(data), len(data))]
new_data = new_data.set_index(pd.Index(list(range(len(data)))))
h = accumulator_class(new_data, **class_kwargs)
#run optimization
h._run_optimization(method=method, quantiles=quantiles, n_runs=n_runs)
return pd.Series(h.values, dtype=np.float)
#bootstrap iterations
for i_strap in range(n_bootstraps):
if view is None:
res.ix[i_strap] = single_bootstrap(self.data)
else:
# append to job queue
runs_list[i_strap] = view.apply_async(single_bootstrap, self.data)
#get parallel results
if view is not None:
view.wait(runs_list)
for i_strap in range(n_bootstraps):
res.ix[i_strap] = runs_list[i_strap].get()
#get statistics
stats = res.describe()
for q in [2.5, 97.5]:
stats = stats.append(pd.DataFrame(res.quantile(q/100.), columns=[repr(q) + '%']).T)
self.bootstrap_stats = stats.sort_index()
return results
def _run_optimization(self, method, quantiles, n_runs):
"""function used by optimize.
"""
if method == 'ML':
if self.is_group_model:
raise TypeError("optimization method is not defined for group models")
else:
results, _ = self._optimization_single(method, quantiles, n_runs=n_runs)
return results
else:
return self._quantiles_optimization(method, quantiles, n_runs=n_runs)
def _optimization_single(self, method, quantiles, n_runs, compute_stats=True):
"""
function used by chisquare_optimization to fit the a single subject model
Input:
quantiles <sequance> - same as in chisquare_optimization
compute_stats <boolean> - whether to copmute the quantile stats using the node's
compute_quantiles_stats method
Output:
results <dict> - same as in chisquare_optimization
"""
#get obs_nodes
obs_nodes = self.get_observeds()['node']
#set quantiles for each observed_node (if needed)
if (method != 'ML') and compute_stats:
[obs.compute_quantiles_stats(quantiles) for obs in obs_nodes]
#get all stochastic parents of observed nodes
db = self.nodes_db
parents = db[(db.stochastic == True) & (db.observed == False)]['node']
original_values = np.array([x.value for x in parents])
names = [x.__name__ for x in parents]
#define objective
#ML method
if method == 'ML':
def objective(values):
for (i, value) in enumerate(values):
parents[i].value = value
try:
return -sum([obs.logp for obs in obs_nodes])
except pm.ZeroProbability:
return np.inf
#chi^2 method
elif method == 'chisquare':
def objective(values):
for (i, value) in enumerate(values):
parents[i].value = value
score = sum([obs.chisquare() for obs in obs_nodes])
if score < 0:
kabuki.debug_here()
return score
#G^2 method
elif method == 'gsquare':
def objective(values):
for (i, value) in enumerate(values):
parents[i].value = value
return -sum([obs.gsquare() for obs in obs_nodes])
else:
raise ValueError('unknown optimzation method')
#optimze
best_score = np.inf
all_results = []
values = original_values.copy()
inf_objective = False
for i_run in range(n_runs):
#initalize values to a random point
values_iter = 0
while inf_objective:
values_iter += 1
values = original_values + np.random.randn(len(values))*(2**-values_iter)
self.set_values(dict(list(zip(names, values))))
inf_objective = np.isinf(objective(values))
#optimze
try:
res_tuple = fmin_powell(objective, values, full_output=True)
except Exception:
res_tuple = fmin(objective, values, full_output=True)
all_results.append(res_tuple)
#reset inf_objective so values be resampled
inf_objective = True
#get best results
best_idx = np.nanargmin([x[1] for x in all_results])
best_values = all_results[best_idx][0]
self.set_values(dict(list(zip(names, best_values))))
results = self.values
#calc BIC for G^2
if method == 'gsquare':
values = [x.value for x in parents]
score = objective(values)
penalty = len(results) * np.log(len(self.data))
bic_info = {'likelihood': -score, 'penalty': penalty, 'bic': score + penalty}
return results, bic_info
else:
return results, None
def _create_family_normal(self, name, value=0, g_mu=None,
g_tau=15**-2, std_lower=1e-10,
std_upper=100, std_value=.1):
"""Create a family of knodes. A family is a group of knodes
that belong together.
For example, a family could consist of the following distributions:
* group mean g_mean (Normal(g_mu, g_tau))
* group standard deviation g_std (Uniform(std_lower, std_upper))
* transform node g_std_trans for g_std (x -> x**-2)
* subject (Normal(g_mean, g_std_trans))
In fact, if is_group_model is True and the name does not appear in
group_only nodes, this is the family that will be created.
Otherwise, only a Normal knode will be returned.
:Arguments:
name : str
Name of the family. Each family member will have this name prefixed.
:Optional:
value : float
Starting value.
g_mu, g_tau, std_lower, std_upper, std_value : float
The hyper parameters for the different family members (see above).
:Returns:
OrderedDict: member name -> member Knode
"""
if g_mu is None:
g_mu = value
knodes = OrderedDict()
if self.is_group_model and name not in self.group_only_nodes:
g = Knode(pm.Normal, '%s' % name, mu=g_mu, tau=g_tau,
value=value, depends=self.depends[name])
depends_std = self.depends[name] if self.std_depends else ()
std = Knode(pm.Uniform, '%s_std' % name, lower=std_lower,
upper=std_upper, value=std_value, depends=depends_std)
tau = Knode(pm.Deterministic, '%s_tau' % name,
doc='%s_tau' % name, eval=lambda x: x**-2, x=std,
plot=False, trace=False, hidden=True)
subj = Knode(pm.Normal, '%s_subj' % name, mu=g, tau=tau,
value=value, depends=('subj_idx',),
subj=True, plot=self.plot_subjs)
knodes['%s'%name] = g
knodes['%s_std'%name] = std
knodes['%s_tau'%name] = tau
knodes['%s_bottom'%name] = subj
else:
subj = Knode(pm.Normal, name, mu=g_mu, tau=g_tau,
value=value, depends=self.depends[name])
knodes['%s_bottom'%name] = subj
return knodes
def _create_family_trunc_normal(self, name, value=0, lower=None,
upper=None, std_lower=1e-10,
std_upper=100, std_value=.1):
"""Similar to _create_family_normal() but creates a Uniform
group distribution and a truncated subject distribution.
See _create_family_normal() help for more information.
"""
knodes = OrderedDict()
if self.is_group_model and name not in self.group_only_nodes:
g = Knode(pm.Uniform, '%s' % name, lower=lower,
upper=upper, value=value, depends=self.depends[name])
depends_std = self.depends[name] if self.std_depends else ()
std = Knode(pm.Uniform, '%s_std' % name, lower=std_lower,
upper=std_upper, value=std_value, depends=depends_std)
tau = Knode(pm.Deterministic, '%s_tau' % name,
doc='%s_tau' % name, eval=lambda x: x**-2, x=std,
plot=False, trace=False, hidden=True)
subj = Knode(pm.TruncatedNormal, '%s_subj' % name, mu=g,
tau=tau, a=lower, b=upper, value=value,
depends=('subj_idx',), subj=True, plot=self.plot_subjs)
knodes['%s'%name] = g
knodes['%s_std'%name] = std
knodes['%s_tau'%name] = tau
knodes['%s_bottom'%name] = subj
else:
subj = Knode(pm.Uniform, name, lower=lower,
upper=upper, value=value,
depends=self.depends[name])
knodes['%s_bottom'%name] = subj
return knodes
def _create_family_invlogit(self, name, value, g_mu=None, g_tau=15**-2,
std_std=0.2, std_value=.1):
"""Similar to _create_family_normal_normal_hnormal() but adds a invlogit
transform knode to the subject and group mean nodes. This is useful
when the parameter space is restricted from [0, 1].
See _create_family_normal_normal_hnormal() help for more information.
"""
if g_mu is None:
g_mu = value
# logit transform values
value_trans = np.log(value) - np.log(1-value)
g_mu_trans = np.log(g_mu) - np.log(1-g_mu)
knodes = OrderedDict()
if self.is_group_model and name not in self.group_only_nodes:
g_trans = Knode(pm.Normal,
'%s_trans'%name,
mu=g_mu_trans,
tau=g_tau,
value=value_trans,
depends=self.depends[name],
plot=False,
hidden=True
)
g = Knode(pm.InvLogit, name, ltheta=g_trans, plot=True,
trace=True)
depends_std = self.depends[name] if self.std_depends else ()
std = Knode(pm.HalfNormal, '%s_std' % name, tau=std_std**-2,
value=std_value, depends=depends_std)
tau = Knode(pm.Deterministic, '%s_tau'%name, doc='%s_tau'
% name, eval=lambda x: x**-2, x=std,
plot=False, trace=False, hidden=True)
subj_trans = Knode(pm.Normal, '%s_subj_trans'%name,
mu=g_trans, tau=tau, value=value_trans,
depends=('subj_idx',), subj=True,
plot=False, hidden=True)
subj = Knode(pm.InvLogit, '%s_subj'%name,
ltheta=subj_trans, depends=('subj_idx',),
plot=self.plot_subjs, trace=True, subj=True)
knodes['%s_trans'%name] = g_trans
knodes['%s'%name] = g
knodes['%s_std'%name] = std
knodes['%s_tau'%name] = tau
knodes['%s_subj_trans'%name] = subj_trans
knodes['%s_bottom'%name] = subj
else:
g_trans = Knode(pm.Normal, '%s_trans'%name, mu=g_mu_trans,
tau=g_tau, value=value_trans,
depends=self.depends[name], plot=False, hidden=True)
g = Knode(pm.InvLogit, '%s'%name, ltheta=g_trans, plot=True,
trace=True )
knodes['%s_trans'%name] = g_trans
knodes['%s_bottom'%name] = g
return knodes
def _create_family_exp(self, name, value=0, g_mu=None,
g_tau=15**-2, std_lower=1e-10, std_upper=100, std_value=.1):
"""Similar to create_family_normal() but adds an exponential
transform knode to the subject and group mean nodes. This is useful
when the parameter space is restricted from [0, +oo).
See create_family_normal() help for more information.
"""
if g_mu is None:
g_mu = value
value_trans = np.log(value)
g_mu_trans = np.log(g_mu)
knodes = OrderedDict()
if self.is_group_model and name not in self.group_only_nodes:
g_trans = Knode(pm.Normal, '%s_trans' % name, mu=g_mu_trans,
tau=g_tau, value=value_trans,
depends=self.depends[name], plot=False, hidden=True)
g = Knode(pm.Deterministic, '%s'%name, eval=lambda x: np.exp(x),
x=g_trans, plot=True)
depends_std = self.depends[name] if self.std_depends else ()
std = Knode(pm.Uniform, '%s_std' % name, lower=std_lower, upper=std_upper,
value=std_value, depends=depends_std)
tau = Knode(pm.Deterministic, '%s_tau' % name, eval=lambda x: x**-2,
x=std, plot=False, trace=False, hidden=True)
subj_trans = Knode(pm.Normal, '%s_subj_trans'%name, mu=g_trans,
tau=tau, value=value_trans, depends=('subj_idx',),
subj=True, plot=False, hidden=True)
subj = Knode(pm.Deterministic, '%s_subj'%name, eval=lambda x: np.exp(x),
x=subj_trans,
depends=('subj_idx',), plot=self.plot_subjs,
trace=True, subj=True)
knodes['%s_trans'%name] = g_trans
knodes['%s'%name] = g
knodes['%s_std'%name] = std
knodes['%s_tau'%name] = tau
knodes['%s_subj_trans'%name] = subj_trans
knodes['%s_bottom'%name] = subj
else:
g_trans = Knode(pm.Normal, '%s_trans' % name, mu=g_mu_trans,
tau=g_tau, value=value_trans,
depends=self.depends[name], plot=False, hidden=True)
g = Knode(pm.Deterministic, '%s'%name, doc='%s'%name, eval=lambda x: np.exp(x), x=g_trans, plot=True)
knodes['%s_trans'%name] = g_trans
knodes['%s_bottom'%name] = g
return knodes
def _create_family_normal_normal_hnormal(self, name, value=0, g_mu=None,
g_tau=15**-2, std_std=2,
std_value=.1):
"""Create a family of knodes. A family is a group of knodes
that belong together.
For example, a family could consist of the following distributions:
* group mean g_mean (Normal(g_mu, g_tau))
* group standard deviation g_std (Uniform(std_lower, std_upper))
* transform node g_std_trans for g_std (x -> x**-2)
* subject (Normal(g_mean, g_std_trans))
In fact, if is_group_model is True and the name does not appear in
group_only nodes, this is the family that will be created.
Otherwise, only a Normal knode will be returned.
:Arguments:
name : str
Name of the family. Each family member will have this name prefixed.
:Optional:
value : float
Starting value.
g_mu, g_tau, std_lower, std_upper, std_value : float
The hyper parameters for the different family members (see above).
:Returns:
OrderedDict: member name -> member Knode
"""
if g_mu is None:
g_mu = value
knodes = OrderedDict()
if self.is_group_model and name not in self.group_only_nodes:
g = Knode(pm.Normal, '%s' % name, mu=g_mu, tau=g_tau,
value=value, depends=self.depends[name])
depends_std = self.depends[name] if self.std_depends else ()
std = Knode(pm.HalfNormal, '%s_std' % name, tau=std_std**-2,
value=std_value, depends=depends_std)
tau = Knode(pm.Deterministic, '%s_tau' % name,
doc='%s_tau' % name, eval=lambda x: x**-2, x=std,
plot=False, trace=False, hidden=True)
subj = Knode(pm.Normal, '%s_subj' % name, mu=g, tau=tau,
value=value, depends=('subj_idx',),
subj=True, plot=self.plot_subjs)
knodes['%s'%name] = g
knodes['%s_std'%name] = std
knodes['%s_tau'%name] = tau
knodes['%s_bottom'%name] = subj
else:
subj = Knode(pm.Normal, name, mu=g_mu, tau=g_tau,
value=value, depends=self.depends[name])
knodes['%s_bottom'%name] = subj
return knodes
def _create_family_gamma_gamma_hnormal(self, name, value=1, g_mean=1, g_std=1, std_std=2, std_value=.1):
"""Similar to _create_family_normal_normal_hnormal() but adds an exponential
transform knode to the subject and group mean nodes. This is useful
when the parameter space is restricted from [0, +oo).
See _create_family_normal_normal_hnormal() help for more information.
"""
knodes = OrderedDict()
g_shape = (g_mean**2) / (g_std**2)
g_rate = g_mean / (g_std**2)
if self.is_group_model and name not in self.group_only_nodes:
g = Knode(pm.Gamma, name, alpha=g_shape, beta=g_rate,
value=g_mean, depends=self.depends[name])
depends_std = self.depends[name] if self.std_depends else ()
std = Knode(pm.HalfNormal, '%s_std' % name, tau=std_std**-2,
value=std_value, depends=depends_std)
shape = Knode(pm.Deterministic, '%s_shape' % name, eval=lambda x,y: (x**2)/(y**2),
x=g, y=std, plot=False, trace=False, hidden=True)
rate = Knode(pm.Deterministic, '%s_rate' % name, eval=lambda x,y: x/(y**2),
x=g, y=std, plot=False, trace=False, hidden=True)
subj = Knode(pm.Gamma, '%s_subj'%name, alpha=shape, beta=rate,
value=value, depends=('subj_idx',),
subj=True, plot=False)
knodes['%s'%name] = g
knodes['%s_std'%name] = std
knodes['%s_rate'%name] = rate
knodes['%s_shape'%name] = shape
knodes['%s_bottom'%name] = subj
else:
g = Knode(pm.Gamma, name, alpha=g_shape, beta=g_rate, value=value,
depends=self.depends[name])
knodes['%s_bottom'%name] = g
return knodes
class HDDMBase(AccumulatorModel):
"""HDDM base class. Not intended to be used directly. Instead, use hddm.HDDM.
"""
def __init__(self, data, bias=False, include=(),
wiener_params=None, p_outlier=0., **kwargs):
self.default_intervars = kwargs.pop('default_intervars', {'sz': 0, 'st': 0, 'sv': 0})
self._kwargs = kwargs
self.include = set(['v', 'a', 't'])
if include is not None:
if include == 'all':
[self.include.add(param) for param in ('z', 'st','sv','sz', 'p_outlier')]
elif isinstance(include, str):
self.include.add(include)
else:
[self.include.add(param) for param in include]
if bias:
self.include.add('z')
possible_parameters = ('v', 'a', 't', 'z', 'st', 'sz', 'sv', 'p_outlier')
assert self.include.issubset(possible_parameters), """Received and invalid parameter using the 'include' keyword.
parameters received: %s
parameters allowed: %s """ % (tuple(self.include), possible_parameters)
#set wiener params
if wiener_params is None:
self.wiener_params = {'err': 1e-4, 'n_st':2, 'n_sz':2,
'use_adaptive':1,
'simps_err':1e-3,
'w_outlier': 0.1}
else:
self.wiener_params = wiener_params
wp = self.wiener_params
self.p_outlier = p_outlier
#set cdf_range
cdf_bound = max(np.abs(data['rt'])) + 1;
self.cdf_range = (-cdf_bound, cdf_bound)
#set wfpt class
self.wfpt_class = hddm.likelihoods.generate_wfpt_stochastic_class(wp, cdf_range=self.cdf_range)
super(HDDMBase, self).__init__(data, **kwargs)
def __getstate__(self):
d = super(HDDMBase, self).__getstate__()
del d['wfpt_class']
return d
def __setstate__(self, d):
self.wfpt_class = hddm.likelihoods.generate_wfpt_stochastic_class(d['wiener_params'], cdf_range=d['cdf_range'])
super(HDDMBase, self).__setstate__(d)
def _create_wfpt_parents_dict(self, knodes):
wfpt_parents = OrderedDict()
wfpt_parents['a'] = knodes['a_bottom']
wfpt_parents['v'] = knodes['v_bottom']
wfpt_parents['t'] = knodes['t_bottom']
wfpt_parents['sv'] = knodes['sv_bottom'] if 'sv' in self.include else self.default_intervars['sv']
wfpt_parents['sz'] = knodes['sz_bottom'] if 'sz' in self.include else self.default_intervars['sz']
wfpt_parents['st'] = knodes['st_bottom'] if 'st' in self.include else self.default_intervars['st']
wfpt_parents['z'] = knodes['z_bottom'] if 'z' in self.include else 0.5
wfpt_parents['p_outlier'] = knodes['p_outlier_bottom'] if 'p_outlier' in self.include else self.p_outlier
return wfpt_parents
def _create_wfpt_knode(self, knodes):
wfpt_parents = self._create_wfpt_parents_dict(knodes)
return Knode(self.wfpt_class, 'wfpt', observed=True, col_name='rt', **wfpt_parents)
def create_knodes(self):
knodes = self._create_stochastic_knodes(self.include)
knodes['wfpt'] = self._create_wfpt_knode(knodes)
return list(knodes.values())
def plot_posterior_predictive(self, *args, **kwargs):
if 'value_range' not in kwargs:
kwargs['value_range'] = np.linspace(-5, 5, 100)
kabuki.analyze.plot_posterior_predictive(self, *args, **kwargs)
def plot_posterior_quantiles(self, *args, **kwargs):
"""Plot posterior predictive quantiles.
:Arguments:
model : HDDM model
:Optional:
value_range : numpy.ndarray
Range over which to evaluate the CDF.
samples : int (default=10)
Number of posterior samples to use.
alpha : float (default=.75)
Alpha (transparency) of posterior quantiles.
hexbin : bool (default=False)
Whether to plot posterior quantile density
using hexbin.
data_plot_kwargs : dict (default=None)
Forwarded to data plotting function call.
predictive_plot_kwargs : dict (default=None)
Forwareded to predictive plotting function call.
columns : int (default=3)
How many columns to use for plotting the subjects.
save : bool (default=False)
Whether to save the figure to a file.
path : str (default=None)
Save figure into directory prefix
"""
hddm.utils.plot_posterior_quantiles(self, *args, **kwargs)
def _create_an_average_model(self):
"""
create an average model for group model quantiles optimization.
The function return an instance of the model that was initialize with the same parameters as the
original model but with the is_group_model argument set to False.
since it depends on the specifics of the class it should be implemented by the user for each new class.
"""
#this code only check that the arguments are as expected, i.e. the constructor was not change
#since we wrote this function
init_args = set(inspect.getargspec(self.__init__).args)
known_args = set(['wiener_params', 'include', 'self', 'bias', 'data', 'p_outlier'])
assert known_args.issuperset(init_args), "Arguments of the constructor are not as expected"
#create the avg model
avg_model = self.__class__(self.data, include=self.include, is_group_model=False, p_outlier=self.p_outlier, **self._kwargs)
return avg_model
if __name__ == "__main__":
import doctest
doctest.testmod()
|
/**Does destructive procedural parsing on parser results.
*
* @author ptc24
* @author dl387
*
*/
class ComponentGenerator {
/**
* Sort bridges such as the highest priority secondary bridges come first
* e.g. 1^(6,3).1^(15,13)
* rearranged to 1^(15,13).1^(6,3)
* @author dl387
*
*/
private static class VonBaeyerSecondaryBridgeSort implements Comparator<HashMap<String, Integer>> {
public int compare(HashMap<String, Integer> bridge1, HashMap<String, Integer> bridge2){
//first we compare the larger coordinate, due to an earlier potential swapping of coordinates this is always in "AtomId_Larger"
int largerCoordinate1 = bridge1.get("AtomId_Larger");
int largerCoordinate2 = bridge2.get("AtomId_Larger");
if (largerCoordinate1 >largerCoordinate2) {
return -1;
}
else if (largerCoordinate2 >largerCoordinate1) {
return 1;
}
//tie
int smallerCoordinate1 = bridge1.get("AtomId_Smaller");
int smallerCoordinate2 = bridge2.get("AtomId_Smaller");
if (smallerCoordinate1 >smallerCoordinate2) {
return -1;
}
else if (smallerCoordinate2 >smallerCoordinate1) {
return 1;
}
//tie
int bridgelength1 = bridge1.get("Bridge Length");
int bridgelength2 = bridge2.get("Bridge Length");
if (bridgelength1 >bridgelength2) {
return -1;
}
else if (bridgelength2 >bridgelength1) {
return 1;
}
else{
return 0;
}
}
}
//match a fusion bracket with only numerical locants. If this is followed by a HW group it probably wasn't a fusion bracket
private static final Pattern matchNumberLocantsOnlyFusionBracket = Pattern.compile("\\[\\d+(,\\d+)*\\]");
private static final Pattern matchCommaOrDot =Pattern.compile("[\\.,]");
private static final Pattern matchAnnulene = Pattern.compile("[\\[\\(\\{]([1-9]\\d*)[\\]\\)\\}]annulen");
private static final String elementSymbols ="(?:He|Li|Be|B|C|N|O|F|Ne|Na|Mg|Al|Si|P|S|Cl|Ar|K|Ca|Sc|Ti|V|Cr|Mn|Fe|Co|Ni|Cu|Zn|Ga|Ge|As|Se|Br|Kr|Rb|Sr|Y|Zr|Nb|Mo|Tc|Ru|Rh|Pd|Ag|Cd|In|Sn|Sb|Te|I|Xe|Cs|Ba|La|Ce|Pr|Nd|Pm|Sm|Eu|Gd|Tb|Dy|Ho|Er|Tm|Yb|Lu|Hf|Ta|W|Re|Os|Ir|Pt|Au|Hg|Tl|Pb|Po|At|Rn|Fr|Ra|Ac|Th|Pa|U|Np|Pu|Am|Cm|Bk|Cf|Es|Fm|Md|No|Lr|Rf|Db|Sg|Bh|Hs|Mt|Ds)";
private static final Pattern matchStereochemistry = Pattern.compile("(.*?)(SR|R/?S|r/?s|[Ee][Zz]|[RSEZrsezabx]|[cC][iI][sS]|[tT][rR][aA][nN][sS]|[aA][lL][pP][hH][aA]|[bB][eE][tT][aA]|[xX][iI]|[eE][xX][oO]|[eE][nN][dD][oO]|[sS][yY][nN]|[aA][nN][tT][iI]|M|P|Ra|Sa|Sp|Rp)");
private static final Pattern matchStar = Pattern.compile("\\^?\\*");
private static final Pattern matchRacemic = Pattern.compile("rac(\\.|em(\\.|ic)?)?-?", Pattern.CASE_INSENSITIVE);
private static final Pattern matchRS = Pattern.compile("[Rr]/?[Ss]?|[Ss][Rr]?");
private static final Pattern matchEZ = Pattern.compile("[EZez]|[Ee][Zz]");
private static final Pattern matchAlphaBetaStereochem = Pattern.compile("a|b|x|[aA][lL][pP][hH][aA]|[bB][eE][tT][aA]|[xX][iI]");
private static final Pattern matchCisTrans = Pattern.compile("[cC][iI][sS]|[tT][rR][aA][nN][sS]");
private static final Pattern matchEndoExoSynAnti = Pattern.compile("[eE][xX][oO]|[eE][nN][dD][oO]|[sS][yY][nN]|[aA][nN][tT][iI]");
private static final Pattern matchAxialStereo = Pattern.compile("M|P|Ra|Sa|Sp|Rp");
private static final Pattern matchLambdaConvention = Pattern.compile("(\\S+)?lambda\\D*(\\d+)\\D*", Pattern.CASE_INSENSITIVE);
private static final Pattern matchHdigit =Pattern.compile("H\\d");
private static final Pattern matchNonDigit =Pattern.compile("\\D+");
private static final Pattern matchAddedHydrogenLocantBracket = Pattern.compile("[1-9][0-9]*[a-g]?'*H(,[1-9][0-9]*[a-g]?'*H)*", Pattern.CASE_INSENSITIVE);
private static final Pattern matchRSLocantBracket = Pattern.compile("[RS]|R[,/]?S", Pattern.CASE_INSENSITIVE);
private static final Pattern matchSuperscriptedLocant = Pattern.compile("(" + elementSymbols +"'*)[\\^\\[\\(\\{~\\*\\<]*(?:[sS][uU][pP][ ]?)?([^\\^\\[\\(\\{~\\*\\<\\]\\)\\}\\>]+)[^\\[\\(\\{]*");
private static final Pattern matchIUPAC2004ElementLocant = Pattern.compile("(\\d+'*)-(" + elementSymbols +"'*)(.*)");
private static final Pattern matchGreek = Pattern.compile("alpha|beta|gamma|delta|epsilon|zeta|eta|omega", Pattern.CASE_INSENSITIVE);
private static final Pattern matchInlineSuffixesThatAreAlsoGroups = Pattern.compile("carbonyl|oxy|sulfenyl|sulfinyl|sulfonyl|selenenyl|seleninyl|selenonyl|tellurenyl|tellurinyl|telluronyl");
private final NameToStructureConfig n2sConfig;
ComponentGenerator(NameToStructureConfig n2sConfig) {
this.n2sConfig = n2sConfig;
}
/**
* Processes a parse result destructively adding semantic information by processing the various micro syntaxes.
* @param parse
* @throws ComponentGenerationException
*/
void processParse(Element parse) throws ComponentGenerationException {
List<Element> substituentsAndRoot = OpsinTools.getDescendantElementsWithTagNames(parse, new String[]{SUBSTITUENT_EL, ROOT_EL});
for (Element subOrRoot: substituentsAndRoot) {
/* Throws exceptions for occurrences that are ambiguous and this parse has picked the incorrect interpretation */
resolveAmbiguities(subOrRoot);
processLocants(subOrRoot);
convertOrthoMetaParaToLocants(subOrRoot);
formAlkaneStemsFromComponents(subOrRoot);
processAlkaneStemModifications(subOrRoot);//e.g. tert-butyl
processHeterogenousHydrides(subOrRoot);//e.g. tetraphosphane, disiloxane
processIndicatedHydrogens(subOrRoot);
processStereochemistry(subOrRoot);
processInfixes(subOrRoot);
processSuffixPrefixes(subOrRoot);
processLambdaConvention(subOrRoot);
}
List<Element> groups = OpsinTools.getDescendantElementsWithTagName(parse, GROUP_EL);
/* Converts open/close bracket elements to bracket elements and
* places the elements inbetween within the newly created bracket */
List<Element> brackets = new ArrayList<Element>();
findAndStructureBrackets(substituentsAndRoot, brackets);
for (Element subOrRoot: substituentsAndRoot) {
processHydroCarbonRings(subOrRoot);
handleSuffixIrregularities(subOrRoot);//handles quinone -->dioxo
}
for (Element group : groups) {
detectAlkaneFusedRingBridges(group);
processRings(group);//processes cyclo, von baeyer and spiro tokens
handleGroupIrregularities(group);//handles benzyl, diethylene glycol, phenanthrone and other awkward bits of nomenclature
}
for (Element bracket : brackets) {
moveDetachableHetAtomRepl(bracket);
}
}
/**
* Resolves common ambiguities e.g. tetradeca being 4x10carbon chain rather than 14carbon chain
* @param subOrRoot
* @throws ComponentGenerationException
*/
static void resolveAmbiguities(Element subOrRoot) throws ComponentGenerationException {
List<Element> multipliers = subOrRoot.getChildElements(MULTIPLIER_EL);
for (Element apparentMultiplier : multipliers) {
if (!BASIC_TYPE_VAL.equals(apparentMultiplier.getAttributeValue(TYPE_ATR)) && !VONBAEYER_TYPE_VAL.equals(apparentMultiplier.getAttributeValue(TYPE_ATR))){
continue;
}
int multiplierNum = Integer.parseInt(apparentMultiplier.getAttributeValue(VALUE_ATR));
Element nextEl = OpsinTools.getNextSibling(apparentMultiplier);
if (multiplierNum >=3){//detects ambiguous use of things like tetradeca
if(nextEl !=null){
if (nextEl.getName().equals(ALKANESTEMCOMPONENT)){//can ignore the trivial alkanes as ambiguity does not exist for them
int alkaneChainLength = Integer.parseInt(nextEl.getAttributeValue(VALUE_ATR));
if (alkaneChainLength >=10 && alkaneChainLength > multiplierNum){
Element isThisALocant = OpsinTools.getPreviousSibling(apparentMultiplier);
if (isThisALocant == null ||
!isThisALocant.getName().equals(LOCANT_EL) ||
isThisALocant.getValue().split(",").length != multiplierNum){
throw new ComponentGenerationException(apparentMultiplier.getValue() + nextEl.getValue() +" should not have been lexed as two tokens!");
}
}
}
}
}
if (multiplierNum >=4 && nextEl !=null && nextEl.getName().equals(HYDROCARBONFUSEDRINGSYSTEM_EL) && nextEl.getValue().equals("phen") && !"e".equals(nextEl.getAttributeValue(SUBSEQUENTUNSEMANTICTOKEN_ATR))){//deals with tetra phenyl vs tetraphen yl
Element possibleLocantOrMultiplierOrSuffix = OpsinTools.getNextSibling(nextEl);
if (possibleLocantOrMultiplierOrSuffix!=null){//null if not used as substituent
if (possibleLocantOrMultiplierOrSuffix.getName().equals(SUFFIX_EL)){//for phen the aryl substituent, expect an adjacent suffix e.g. phenyl, phenoxy
Element isThisALocant = OpsinTools.getPreviousSibling(apparentMultiplier);
if (isThisALocant == null || !isThisALocant.getName().equals(LOCANT_EL) || isThisALocant.getValue().split(",").length != 1){
String multiplierAndGroup =apparentMultiplier.getValue() + nextEl.getValue();
throw new ComponentGenerationException(multiplierAndGroup +" should not have been lexed as one token!");
}
}
}
}
if (multiplierNum > 4 && !apparentMultiplier.getValue().endsWith("a")){//disambiguate pent oxy and the like. Assume it means pentanoxy rather than 5 oxys
if (nextEl !=null && nextEl.getName().equals(GROUP_EL)&& matchInlineSuffixesThatAreAlsoGroups.matcher(nextEl.getValue()).matches()){
throw new ComponentGenerationException(apparentMultiplier.getValue() + nextEl.getValue() +" should have been lexed as [alkane stem, inline suffix], not [multiplier, group]!");
}
}
}
List<Element> fusions = subOrRoot.getChildElements(FUSION_EL);
for (Element fusion : fusions) {
String fusionText = fusion.getValue();
if (matchNumberLocantsOnlyFusionBracket.matcher(fusionText).matches()){
Element possibleHWRing = OpsinTools.getNextSiblingIgnoringCertainElements(fusion, new String[]{MULTIPLIER_EL, HETEROATOM_EL});
if (possibleHWRing !=null && HANTZSCHWIDMAN_SUBTYPE_VAL.equals(possibleHWRing.getAttributeValue(SUBTYPE_ATR))){
int heteroCount = 0;
int multiplierValue = 1;
Element currentElem = OpsinTools.getNextSibling(fusion);
while(currentElem != null && !currentElem.getName().equals(GROUP_EL)){
if(currentElem.getName().equals(HETEROATOM_EL)) {
heteroCount+=multiplierValue;
multiplierValue =1;
} else if (currentElem.getName().equals(MULTIPLIER_EL)){
multiplierValue = Integer.parseInt(currentElem.getAttributeValue(VALUE_ATR));
}
currentElem = OpsinTools.getNextSibling(currentElem);
}
String[] locants = fusionText.substring(1, fusionText.length() - 1).split(",");
if (locants.length == heteroCount){
boolean foundLocantNotInHwSystem =false;
for (String locant : locants) {
if (Integer.parseInt(locant) > (possibleHWRing.getAttributeValue(VALUE_ATR).length()-2)){
foundLocantNotInHwSystem =true;
}
}
if (!foundLocantNotInHwSystem){
throw new ComponentGenerationException("This fusion bracket is in fact more likely to be a description of the locants of a HW ring");
}
}
}
}
}
}
/**
* Removes hyphens from the end of locants if present
* Looks for locants of the form number-letter and converts them to letternumber
* e.g. 1-N becomes N1. 1-N is the IUPAC 2004 recommendation, N1 is the previous recommendation
* Strips indication of superscript
* Strips added hydrogen out of locants
* Strips stereochemistry out of locants
* Normalises case on greeks to lower case
*
* @param subOrRoot
* @throws ComponentGenerationException
*/
static void processLocants(Element subOrRoot) throws ComponentGenerationException {
List<Element> children = subOrRoot.getChildElements();
for (Element el : children) {
String elName = el.getName();
if (elName.equals(LOCANT_EL)) {
Element locantEl = el;
List<String> individualLocants = splitIntoIndividualLocants(StringTools.removeDashIfPresent(locantEl.getValue()));
for (int i = 0, locantCount = individualLocants.size(); i < locantCount; i++) {
String locantText = individualLocants.get(i);
char lastChar = locantText.charAt(locantText.length() - 1);
if(lastChar == ')' || lastChar == ']' || lastChar == '}') {
//stereochemistry or added hydrogen that result from the application of this locant as a locant for a substituent may be included in brackets after the locant
int bracketStart = -1;
for (int j = locantText.length() - 2; j >=0; j--) {
char ch = locantText.charAt(j);
if (ch == '(' || ch == '[' || ch == '{') {
bracketStart = j;
break;
}
}
if (bracketStart >=0) {
String brackettedText = locantText.substring(bracketStart + 1, locantText.length() - 1);
if (matchAddedHydrogenLocantBracket.matcher(brackettedText).matches()) {
locantText = StringTools.removeDashIfPresent(locantText.substring(0, bracketStart));//strip the bracket from the locantText
//create individual tags for added hydrogen. Examples of bracketed text include "9H" or "2H,7H"
String[] addedHydrogens = brackettedText.split(",");
for (String addedHydrogen : addedHydrogens) {
Element addedHydrogenElement = new TokenEl(ADDEDHYDROGEN_EL);
String hydrogenLocant = fixLocantCapitalisation(addedHydrogen.substring(0, addedHydrogen.length() - 1));
addedHydrogenElement.addAttribute(new Attribute(LOCANT_ATR, hydrogenLocant));
OpsinTools.insertBefore(locantEl, addedHydrogenElement);
}
if (locantEl.getAttribute(TYPE_ATR) == null){
locantEl.addAttribute(new Attribute(TYPE_ATR, ADDEDHYDROGENLOCANT_TYPE_VAL));//this locant must not be used as an indirect locant
}
}
else if (matchRSLocantBracket.matcher(brackettedText).matches()) {
locantText = StringTools.removeDashIfPresent(locantText.substring(0, bracketStart));//strip the bracket from the locantText
String rs = brackettedText.replaceAll("\\W", "");//convert R/S to RS
Element newStereoChemEl = new TokenEl(STEREOCHEMISTRY_EL, "(" + standardizeLocantVariants(locantText) + rs + ")");
newStereoChemEl.addAttribute(new Attribute(TYPE_ATR, STEREOCHEMISTRYBRACKET_TYPE_VAL));
OpsinTools.insertBefore(locantEl, newStereoChemEl);
}
//compounds locant e.g. 1(10). are left as is, and handled by the function that handles unsaturation
//brackets for superscripts are removed by standardizeLocantVariants e.g. N(alpha)
}
else{
throw new ComponentGenerationException("OPSIN bug: malformed locant text");
}
}
individualLocants.set(i, standardizeLocantVariants(locantText));
}
locantEl.setValue(StringTools.stringListToString(individualLocants, ","));
Element afterLocants = OpsinTools.getNextSibling(locantEl);
if(afterLocants == null) {
throw new ComponentGenerationException("Nothing after locant tag: " + locantEl.toXML());
}
if (individualLocants.size() == 1) {
ifCarbohydrateLocantConvertToAminoAcidStyleLocant(locantEl);
}
}
else if (elName.equals(COLONORSEMICOLONDELIMITEDLOCANT_EL)) {
//e.g. (1,2:3,4)
//This type of locant is typically used with pairs of locants e.g epoxides, anhydrides
String locantText = StringTools.removeDashIfPresent(el.getValue());
StringBuilder updatedLocantText = new StringBuilder();
StringBuilder sb = new StringBuilder();
for (int i = 0, len = locantText.length(); i < len; i++) {
char ch = locantText.charAt(i);
if (ch == ',' || ch == ':' || ch == ';') {
updatedLocantText.append(standardizeLocantVariants(sb.toString()));
sb.setLength(0);
updatedLocantText.append(ch);
}
else {
sb.append(ch);
}
}
updatedLocantText.append(standardizeLocantVariants(sb.toString()));
el.setValue(updatedLocantText.toString());
}
}
}
private static String standardizeLocantVariants(String locantText) {
if (locantText.contains("-")) {//avoids this regex being invoked typically
//rearranges locant to the older equivalent form
Matcher m = matchIUPAC2004ElementLocant.matcher(locantText);
if (m.matches()){
locantText = m.group(2) + m.group(1) + m.group(3);
}
}
if (Character.isLetter(locantText.charAt(0))) {
//remove indications of superscript as the fact a locant is superscripted can be determined from context e.g. N~1~ ->N1
Matcher m = matchSuperscriptedLocant.matcher(locantText);
if (m.lookingAt()) {
String replacementString = m.group(1) + m.group(2);
locantText = m.replaceFirst(replacementString);
}
if (locantText.length() >= 3){
//convert greeks to lower case
m = matchGreek.matcher(locantText);
while (m.find()) {
locantText = locantText.substring(0, m.start()) + m.group().toLowerCase(Locale.ROOT) + locantText.substring(m.end());
}
}
}
locantText = fixLocantCapitalisation(locantText);
return locantText;
}
/**
* Looks for locants of the form (<anotherLocant>)?<multiplier><locant>
* and converts them to <modifiedlocant><multiplier>
* e.g. 2,4,6 tri O- -->O2,O4,O6 tri
* @param locant
*/
private static void ifCarbohydrateLocantConvertToAminoAcidStyleLocant(Element locant) {
if (MATCH_ELEMENT_SYMBOL.matcher(locant.getValue()).matches()) {
Element possibleMultiplier = OpsinTools.getPreviousSibling(locant);
if (possibleMultiplier != null && possibleMultiplier.getName().equals(MULTIPLIER_EL)) {
int multiplierValue = Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR));
Element possibleOtherLocant = OpsinTools.getPreviousSibling(possibleMultiplier);
if (possibleOtherLocant != null) {
String[] locantValues = possibleOtherLocant.getValue().split(",");
if (locantValues.length == Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR))){
for (int i = 0; i < locantValues.length; i++) {
locantValues[i] = locant.getValue() + locantValues[i];
}
possibleOtherLocant.setValue(StringTools.arrayToString(locantValues, ","));
locant.detach();
}
}
else{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < multiplierValue - 1; i++) {
sb.append(locant.getValue());
sb.append(StringTools.multiplyString("'", i));
sb.append(',');
}
sb.append(locant.getValue());
sb.append(StringTools.multiplyString("'", multiplierValue - 1));
Element newLocant = new TokenEl(LOCANT_EL, sb.toString());
OpsinTools.insertBefore(possibleMultiplier, newLocant);
locant.detach();
}
}
}
}
/**
* Takes a string of locants and splits on commas, but taking into account brackets
* e.g. 1,2(1H,2H),3 becomes [1][2(1H,2H)][3]
* @param locantString
* @return
*/
private static List<String> splitIntoIndividualLocants(String locantString) {
List<String> individualLocants = new ArrayList<String>();
char[] charArray = locantString.toCharArray();
boolean inBracket =false;
int indiceOfLastMatch =0;
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
if (c==','){
if (!inBracket){
individualLocants.add(locantString.substring(indiceOfLastMatch, i));
indiceOfLastMatch = i+1;
}
}
else if (c == '(' || c == '[' || c == '{') {
inBracket =true;
}
else if(c == ')' || c == ']' || c == '}') {
inBracket =false;
}
}
individualLocants.add(locantString.substring(indiceOfLastMatch, charArray.length));
return individualLocants;
}
/**Converts ortho/meta/para into locants
* Depending on context para, for example, will either become para or 1,para
*
* @param subOrRoot
* @throws ComponentGenerationException
*/
private void convertOrthoMetaParaToLocants(Element subOrRoot) throws ComponentGenerationException{
List<Element> ompLocants = subOrRoot.getChildElements(ORTHOMETAPARA_EL);
for (Element ompLocant : ompLocants) {
String locantText = ompLocant.getValue();
String firstChar = locantText.substring(0, 1);
ompLocant.setName(LOCANT_EL);
ompLocant.addAttribute(new Attribute(TYPE_ATR, ORTHOMETAPARA_TYPE_VAL));
if (orthoMetaParaLocantIsTwoLocants(ompLocant)) {
if ("o".equalsIgnoreCase(firstChar)){
ompLocant.setValue("1,ortho");
}
else if ("m".equalsIgnoreCase(firstChar)){
ompLocant.setValue("1,meta");
}
else if ("p".equalsIgnoreCase(firstChar)){
ompLocant.setValue("1,para");
}
else{
throw new ComponentGenerationException(locantText + " was not identified as being either ortho, meta or para but according to the chemical grammar it should of been");
}
}
else{
if ("o".equalsIgnoreCase(firstChar)){
ompLocant.setValue("ortho");
}
else if ("m".equalsIgnoreCase(firstChar)){
ompLocant.setValue("meta");
}
else if ("p".equalsIgnoreCase(firstChar)){
ompLocant.setValue("para");
}
else{
throw new ComponentGenerationException(locantText + " was not identified as being either ortho, meta or para but according to the chemical grammar it should of been");
}
}
}
}
private boolean orthoMetaParaLocantIsTwoLocants(Element ompLocant) {
Element afterOmpLocant = OpsinTools.getNextSibling(ompLocant);
if (afterOmpLocant != null){
String elName = afterOmpLocant.getName();
if(elName.equals(MULTIPLIER_EL) && afterOmpLocant.getAttributeValue(VALUE_ATR).equals("2")){
//e.g. p-dimethyl
return true;
}
String outIds = afterOmpLocant.getAttributeValue(OUTIDS_ATR);
if (outIds != null && outIds.split(",").length > 1) {
//e.g. p-phenylene
return true;
}
if(elName.equals(GROUP_EL)){
Element multiplier = OpsinTools.getNextSibling(afterOmpLocant);
if(multiplier != null && multiplier.getName().equals(MULTIPLIER_EL) && multiplier.getAttributeValue(VALUE_ATR).equals("2")){
Element suffix = OpsinTools.getNextSiblingIgnoringCertainElements(multiplier, new String[]{INFIX_EL, SUFFIXPREFIX_EL});
if(suffix.getName().equals(SUFFIX_EL)){
//e.g. o-benzenediamine
return true;
}
}
}
}
return false;
}
/**
* Processes adjacent alkane stem component elements into a single alkaneStem group element with the appropriate SMILES
* e.g. dodecane would be "do" value=2 and "dec" value=10 -->alkaneStem with 12 carbons
*
* @param subOrRoot
*/
private void formAlkaneStemsFromComponents(Element subOrRoot) {
Deque<Element> alkaneStemComponents =new ArrayDeque<Element>(subOrRoot.getChildElements(ALKANESTEMCOMPONENT));
while(!alkaneStemComponents.isEmpty()){
Element alkaneStemComponent = alkaneStemComponents.removeFirst();
int alkaneChainLength =0;
StringBuilder alkaneName = new StringBuilder();
alkaneChainLength += Integer.parseInt(alkaneStemComponent.getAttributeValue(VALUE_ATR));
alkaneName.append(alkaneStemComponent.getValue());
while (!alkaneStemComponents.isEmpty() && OpsinTools.getNextSibling(alkaneStemComponent)==alkaneStemComponents.getFirst()) {
alkaneStemComponent.detach();
alkaneStemComponent = alkaneStemComponents.removeFirst();
alkaneChainLength += Integer.parseInt(alkaneStemComponent.getAttributeValue(VALUE_ATR));
alkaneName.append(alkaneStemComponent.getValue());
}
Element alkaneStem = new TokenEl(GROUP_EL, alkaneName.toString());
alkaneStem.addAttribute(new Attribute(TYPE_ATR, CHAIN_TYPE_VAL));
alkaneStem.addAttribute(new Attribute(SUBTYPE_ATR, ALKANESTEM_SUBTYPE_VAL));
alkaneStem.addAttribute(new Attribute(VALUE_ATR, StringTools.multiplyString("C", alkaneChainLength)));
alkaneStem.addAttribute(new Attribute(USABLEASJOINER_ATR, "yes"));
alkaneStem.addAttribute(new Attribute(LABELS_ATR, NUMERIC_LABELS_VAL));
OpsinTools.insertAfter(alkaneStemComponent, alkaneStem);
alkaneStemComponent.detach();
}
}
/**
* Applies the traditional alkane modifiers: iso, tert, sec, neo by modifying the alkane chain's SMILES
*
* @param subOrRoot
* @throws ComponentGenerationException
*/
private void processAlkaneStemModifications(Element subOrRoot) throws ComponentGenerationException {
List<Element> alkaneStemModifiers = subOrRoot.getChildElements(ALKANESTEMMODIFIER_EL);
for (Element alkaneStemModifier : alkaneStemModifiers) {
Element alkane = OpsinTools.getNextSibling(alkaneStemModifier);
if (alkane ==null || !CHAIN_TYPE_VAL.equals(alkane.getAttributeValue(TYPE_ATR))
|| !ALKANESTEM_SUBTYPE_VAL.equals(alkane.getAttributeValue(SUBTYPE_ATR))){
throw new ComponentGenerationException("OPSIN Bug: AlkaneStem not found after alkaneStemModifier");
}
String type;
if (alkaneStemModifier.getAttribute(VALUE_ATR)!=null){
type = alkaneStemModifier.getAttributeValue(VALUE_ATR);//identified by token;
}
else{
if (alkaneStemModifier.getValue().equals("n-")){
type="normal";
}
else if (alkaneStemModifier.getValue().equals("i-")){
type="iso";
}
else if (alkaneStemModifier.getValue().equals("s-")){
type="sec";
}
else{
throw new ComponentGenerationException("Unrecognised alkaneStem modifier");
}
}
alkaneStemModifier.detach();
int chainLength = alkane.getAttributeValue(VALUE_ATR).length();
String smiles;
String labels = NONE_LABELS_VAL;
if (type.equals("normal")){
//normal behaviour is default so don't need to do anything
//n-methyl and n-ethyl contain redundant information and are probably intended to mean N-methyl/N-ethyl
if ((chainLength==1 || chainLength ==2) && alkaneStemModifier.getValue().equals("n-")){
Element locant = new TokenEl(LOCANT_EL, "N");
OpsinTools.insertBefore(alkane, locant);
}
continue;
}
else if (type.equals("tert")){
if (chainLength <4){
throw new ComponentGenerationException("ChainLength to small for tert modifier, required minLength 4. Found: " +chainLength);
}
if (chainLength >8){
throw new ComponentGenerationException("Interpretation of tert on an alkane chain of length: " + chainLength +" is ambiguous");
}
if (chainLength ==8){
smiles = "C(C)(C)CC(C)(C)C";
}
else{
smiles ="C(C)(C)C" + StringTools.multiplyString("C", chainLength-4);
}
}
else if (type.equals("iso")){
if (chainLength <3){
throw new ComponentGenerationException("ChainLength to small for iso modifier, required minLength 3. Found: " +chainLength);
}
boolean suffixPresent = subOrRoot.getChildElements(SUFFIX_EL).size() > 0;
if (chainLength==3 && !suffixPresent){
throw new ComponentGenerationException("iso has no meaning without a suffix on an alkane chain of length 3");
}
if (chainLength ==8 && !suffixPresent){
smiles = "C(C)(C)CC(C)(C)C";
}
else{
smiles =StringTools.multiplyString("C", chainLength - 3) +"C(C)C";
StringBuilder sb = new StringBuilder();
for (int c = 1; c <= chainLength - 2; c++) {
sb.append(c);
sb.append('/');
}
sb.append('/');
labels = sb.toString();
}
}
else if (type.equals("sec")){
if (chainLength <3){
throw new ComponentGenerationException("ChainLength to small for sec modifier, required minLength 3. Found: " +chainLength);
}
boolean suffixPresent = subOrRoot.getChildElements(SUFFIX_EL).size() > 0;
if (!suffixPresent){
throw new ComponentGenerationException("sec has no meaning without a suffix on an alkane chain");
}
smiles ="C(C)C" + StringTools.multiplyString("C", chainLength-3);
}
else if (type.equals("neo")){
if (chainLength <5){
throw new ComponentGenerationException("ChainLength to small for neo modifier, required minLength 5. Found: " +chainLength);
}
smiles = StringTools.multiplyString("C", chainLength-5) + "CC(C)(C)C";
}
else{
throw new ComponentGenerationException("Unrecognised alkaneStem modifier");
}
alkane.getAttribute(VALUE_ATR).setValue(smiles);
alkane.removeAttribute(alkane.getAttribute(USABLEASJOINER_ATR));
alkane.getAttribute(LABELS_ATR).setValue(labels);
}
}
/**Form heterogeneous hydrides/substituents
* These are chains of one heteroatom or alternating heteroatoms and are expressed using SMILES
* They are typically treated in an analogous way to alkanes
* @param subOrRoot The root/substituents
* @throws ComponentGenerationException
*/
private void processHeterogenousHydrides(Element subOrRoot) throws ComponentGenerationException {
List<Element> multipliers = subOrRoot.getChildElements(MULTIPLIER_EL);
for (int i = 0; i < multipliers.size(); i++) {
Element m = multipliers.get(i);
if (m.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL)){
continue;
}
Element multipliedElem = OpsinTools.getNextSibling(m);
if(multipliedElem.getName().equals(GROUP_EL) &&
multipliedElem.getAttribute(SUBTYPE_ATR)!=null &&
multipliedElem.getAttributeValue(SUBTYPE_ATR).equals(HETEROSTEM_SUBTYPE_VAL)) {
int mvalue = Integer.parseInt(m.getAttributeValue(VALUE_ATR));
Element possiblyALocant = OpsinTools.getPreviousSibling(m);//detect rare case where multiplier does not mean form a chain of heteroatoms e.g. something like 1,2-disulfanylpropane
if(possiblyALocant !=null && possiblyALocant.getName().equals(LOCANT_EL)&& mvalue==possiblyALocant.getValue().split(",").length){
Element suffix = OpsinTools.getNextSibling(multipliedElem, SUFFIX_EL);
if (suffix !=null && suffix.getAttributeValue(TYPE_ATR).equals(INLINE_TYPE_VAL)){
Element possibleMultiplier = OpsinTools.getPreviousSibling(suffix);
if (!possibleMultiplier.getName().equals(MULTIPLIER_EL)){//NOT something like 3,3'-diselane-1,2-diyl
continue;
}
}
}
//chain of heteroatoms
String heteroatomSmiles=multipliedElem.getAttributeValue(VALUE_ATR);
if (heteroatomSmiles.equals("B") && OpsinTools.getPreviousSibling(m)==null){
Element possibleUnsaturator = OpsinTools.getNextSibling(multipliedElem);
if (possibleUnsaturator !=null && possibleUnsaturator.getName().equals(UNSATURATOR_EL) && possibleUnsaturator.getAttributeValue(VALUE_ATR).equals("1")){
throw new ComponentGenerationException("Polyboranes are not currently supported");
}
}
String smiles = StringTools.multiplyString(heteroatomSmiles, mvalue);
multipliedElem.getAttribute(VALUE_ATR).setValue(smiles);
m.detach();
multipliers.remove(i--);
}
}
for (Element m : multipliers) {
if (m.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL)){
continue;
}
Element multipliedElem = OpsinTools.getNextSibling(m);
if(multipliedElem.getName().equals(HETEROATOM_EL)){
Element possiblyAnotherHeteroAtom = OpsinTools.getNextSibling(multipliedElem);
if (possiblyAnotherHeteroAtom !=null && possiblyAnotherHeteroAtom.getName().equals(HETEROATOM_EL)){
Element possiblyAnUnsaturator = OpsinTools.getNextSiblingIgnoringCertainElements(possiblyAnotherHeteroAtom, new String[]{LOCANT_EL, MULTIPLIER_EL});//typically ane but can be ene or yne e.g. triphosphaza-1,3-diene
if (possiblyAnUnsaturator !=null && possiblyAnUnsaturator.getName().equals(UNSATURATOR_EL)){
StringBuilder newGroupName = new StringBuilder(m.getValue());
newGroupName.append(multipliedElem.getValue());
newGroupName.append(possiblyAnotherHeteroAtom.getValue());
//chain of alternating heteroatoms
if (possiblyAnUnsaturator.getAttributeValue(VALUE_ATR).equals("1")){
checkForAmbiguityWithHWring(multipliedElem.getAttributeValue(VALUE_ATR), possiblyAnotherHeteroAtom.getAttributeValue(VALUE_ATR));
}
int mvalue = Integer.parseInt(m.getAttributeValue(VALUE_ATR));
StringBuilder smilesSB= new StringBuilder();
Element possiblyARingFormingEl = OpsinTools.getPreviousSibling(m);
boolean heteroatomChainWillFormARing = false;
if (possiblyARingFormingEl!=null && (possiblyARingFormingEl.getName().equals(CYCLO_EL) || possiblyARingFormingEl.getName().equals(VONBAEYER_EL) || possiblyARingFormingEl.getName().equals(SPIRO_EL))){
heteroatomChainWillFormARing=true;
//will be cyclised later.
for (int j = 0; j < mvalue; j++) {
smilesSB.append(possiblyAnotherHeteroAtom.getAttributeValue(VALUE_ATR));
smilesSB.append(multipliedElem.getAttributeValue(VALUE_ATR));
}
}
else{
for (int j = 0; j < mvalue -1; j++) {
smilesSB.append(multipliedElem.getAttributeValue(VALUE_ATR));
smilesSB.append(possiblyAnotherHeteroAtom.getAttributeValue(VALUE_ATR));
}
smilesSB.append(multipliedElem.getAttributeValue(VALUE_ATR));
}
String smiles =smilesSB.toString();
smiles = matchHdigit.matcher(smiles).replaceAll("H?");//hydrogen count will be determined by standard valency
multipliedElem.detach();
Element addedGroup = new TokenEl(GROUP_EL, newGroupName.toString());
addedGroup.addAttribute(new Attribute(VALUE_ATR, smiles));
addedGroup.addAttribute(new Attribute(LABELS_ATR, NUMERIC_LABELS_VAL));
addedGroup.addAttribute(new Attribute(TYPE_ATR, CHAIN_TYPE_VAL));
addedGroup.addAttribute(new Attribute(SUBTYPE_ATR, HETEROSTEM_SUBTYPE_VAL));
if (!heteroatomChainWillFormARing){
addedGroup.addAttribute(new Attribute(USABLEASJOINER_ATR, "yes"));
}
OpsinTools.insertAfter(possiblyAnotherHeteroAtom, addedGroup);
possiblyAnotherHeteroAtom.detach();
m.detach();
}
else if (possiblyAnUnsaturator!=null && possiblyAnUnsaturator.getValue().equals("an") && HANTZSCHWIDMAN_SUBTYPE_VAL.equals(possiblyAnUnsaturator.getAttributeValue(SUBTYPE_ATR))){
//check for HWring that should be interpreted as a heterogenous hydride
boolean foundLocantIndicatingHwRingHeteroatomPositions =false;//allow formally incorrect HW ring systems if they have locants
Element possibleLocant = OpsinTools.getPreviousSibling(m);
if (possibleLocant !=null && possibleLocant.getName().equals(LOCANT_EL)){
int expected = Integer.parseInt(m.getAttributeValue(VALUE_ATR)) + 1;
if (expected == possibleLocant.getValue().split(",").length){
foundLocantIndicatingHwRingHeteroatomPositions = true;
}
}
if (!foundLocantIndicatingHwRingHeteroatomPositions){
checkForAmbiguityWithHeterogenousHydride(multipliedElem.getAttributeValue(VALUE_ATR), possiblyAnotherHeteroAtom.getAttributeValue(VALUE_ATR));
}
}
}
}
}
}
/**
* Throws an exception if the given heteroatoms could be part of a valid Hantzch-widman ring
* For this to be true the first heteroatom must be higher priority than the second
* and the second must be compatible with a HW ane stem
* @param firstHeteroAtomSMILES
* @param secondHeteroAtomSMILES
* @throws ComponentGenerationException
*/
private void checkForAmbiguityWithHWring(String firstHeteroAtomSMILES, String secondHeteroAtomSMILES) throws ComponentGenerationException {
Matcher m = MATCH_ELEMENT_SYMBOL.matcher(firstHeteroAtomSMILES);
if (!m.find()){
throw new ComponentGenerationException("Failed to extract element from heteroatom");
}
ChemEl atom1ChemEl = ChemEl.valueOf(m.group());
m = MATCH_ELEMENT_SYMBOL.matcher(secondHeteroAtomSMILES);
if (!m.find()){
throw new ComponentGenerationException("Failed to extract element from heteroatom");
}
ChemEl atom2ChemEl = ChemEl.valueOf(m.group());
if (AtomProperties.getHwpriority(atom1ChemEl) > AtomProperties.getHwpriority(atom2ChemEl)){
if (atom2ChemEl == ChemEl.O || atom2ChemEl == ChemEl.S || atom2ChemEl == ChemEl.Se || atom2ChemEl == ChemEl.Te
|| atom2ChemEl == ChemEl.Bi || atom2ChemEl == ChemEl.Hg){
if (!hasSiorGeorSnorPb(atom1ChemEl, atom2ChemEl)){
throw new ComponentGenerationException("Hantzch-widman ring misparsed as a heterogeneous hydride with alternating atoms");
}
}
}
}
/**
* Are either of the elements Si/Ge/Sn/Pb
* @param atom1ChemEl
* @param atom2ChemEl
* @return
*/
private boolean hasSiorGeorSnorPb(ChemEl atom1ChemEl, ChemEl atom2ChemEl) {
return (atom1ChemEl == ChemEl.Si || atom1ChemEl == ChemEl.Ge || atom1ChemEl == ChemEl.Sn || atom1ChemEl == ChemEl.Pb
|| atom2ChemEl == ChemEl.Si || atom2ChemEl == ChemEl.Ge || atom2ChemEl == ChemEl.Sn || atom2ChemEl == ChemEl.Pb);
}
/**
* Throws an exception if the given heteroatoms could be part of a heterogenous hydride
* For this to be true the second heteroatom must be higher priority than the first
* @param firstHeteroAtomSMILES
* @param secondHeteroAtomSMILES
* @throws ComponentGenerationException
*/
private void checkForAmbiguityWithHeterogenousHydride(String firstHeteroAtomSMILES, String secondHeteroAtomSMILES) throws ComponentGenerationException {
Matcher m = MATCH_ELEMENT_SYMBOL.matcher(firstHeteroAtomSMILES);
if (!m.find()){
throw new ComponentGenerationException("Failed to extract element from heteroatom");
}
String atom1Element = m.group();
m = MATCH_ELEMENT_SYMBOL.matcher(secondHeteroAtomSMILES);
if (!m.find()){
throw new ComponentGenerationException("Failed to extract element from heteroatom");
}
String atom2Element = m.group();
if (AtomProperties.getHwpriority(ChemEl.valueOf(atom2Element)) > AtomProperties.getHwpriority(ChemEl.valueOf(atom1Element))){
throw new ComponentGenerationException("heterogeneous hydride with alternating atoms misparsed as a Hantzch-widman ring");
}
}
/** Handle indicated hydrogen e.g. 1H- in 1H-pyrrole
*
* @param subOrRoot The substituent/root to looks for indicated hydrogens in.
* @throws ComponentGenerationException
*/
private void processIndicatedHydrogens(Element subOrRoot) throws ComponentGenerationException {
List<Element> indicatedHydrogens = subOrRoot.getChildElements(INDICATEDHYDROGEN_EL);
for (Element indicatedHydrogenGroup : indicatedHydrogens) {
String txt = StringTools.removeDashIfPresent(indicatedHydrogenGroup.getValue());
if (!StringTools.endsWithCaseInsensitive(txt, "h")){//remove brackets if they are present
txt = txt.substring(1, txt.length()-1);
}
String[] hydrogenLocants =txt.split(",");
for (String hydrogenLocant : hydrogenLocants) {
if (StringTools.endsWithCaseInsensitive(hydrogenLocant, "h")) {
String locant = fixLocantCapitalisation(hydrogenLocant.substring(0, hydrogenLocant.length() - 1));
Element indicatedHydrogenEl = new TokenEl(INDICATEDHYDROGEN_EL);
indicatedHydrogenEl.addAttribute(new Attribute(LOCANT_ATR, locant));
OpsinTools.insertBefore(indicatedHydrogenGroup, indicatedHydrogenEl);
}
else{
throw new ComponentGenerationException("OPSIN Bug: malformed indicated hydrogen element!");
}
}
indicatedHydrogenGroup.detach();
}
}
/** Handles stereoChemistry in brackets: R/Z/E/Z/a/alpha/b/beta and cis/trans
* Will assign a locant to a stereoChemistry element if one was specified/available
*
* @param subOrRoot The substituent/root to looks for stereoChemistry in.
* @throws ComponentGenerationException
*/
void processStereochemistry(Element subOrRoot) throws ComponentGenerationException {
List<Element> stereoChemistryElements = subOrRoot.getChildElements(STEREOCHEMISTRY_EL);
List<Element> locantedUnbrackettedEzTerms = new ArrayList<Element>();
for (Element stereoChemistryElement : stereoChemistryElements) {
if (stereoChemistryElement.getAttributeValue(TYPE_ATR).equals(STEREOCHEMISTRYBRACKET_TYPE_VAL)){
processStereochemistryBracket(stereoChemistryElement);
}
else if (stereoChemistryElement.getAttributeValue(TYPE_ATR).equals(CISORTRANS_TYPE_VAL)){
assignLocantUsingPreviousElementIfPresent(stereoChemistryElement);//assign a locant if one is directly before the cis/trans
}
else if (stereoChemistryElement.getAttributeValue(TYPE_ATR).equals(E_OR_Z_TYPE_VAL)){
stereoChemistryElement.addAttribute(new Attribute(VALUE_ATR, stereoChemistryElement.getValue().toUpperCase(Locale.ROOT)));
if (assignLocantUsingPreviousElementIfPresent(stereoChemistryElement)) {//assign a locant if one is directly before the E/Z
locantedUnbrackettedEzTerms.add(stereoChemistryElement);
}
}
else if (stereoChemistryElement.getAttributeValue(TYPE_ATR).equals(ENDO_EXO_SYN_ANTI_TYPE_VAL)){
processLocantAssigningForEndoExoSynAnti(stereoChemistryElement);//assign a locant if one is directly before the endo/exo/syn/anti. Don't neccesarily detach it
}
else if (stereoChemistryElement.getAttributeValue(TYPE_ATR).equals(ALPHA_OR_BETA_TYPE_VAL)){
processUnbracketedAlphaBetaStereochemistry(stereoChemistryElement);
}
else if (stereoChemistryElement.getAttributeValue(TYPE_ATR).equals(RELATIVECISTRANS_TYPE_VAL)){
processRelativeCisTrans(stereoChemistryElement);
}
}
if (locantedUnbrackettedEzTerms.size() > 0) {
duplicateLocantFromStereoTermIfAdjacentToEneOrYlidene(locantedUnbrackettedEzTerms);
}
}
private void processStereochemistryBracket(Element stereoChemistryElement) throws ComponentGenerationException {
String txt = stereoChemistryElement.getValue();
if (StringTools.startsWithCaseInsensitive(txt, "rel-")){
txt = txt.substring(4);
}
txt = StringTools.removeDashIfPresent(txt);
txt = matchStar.matcher(txt).replaceAll("");
boolean racemicStereo;
Matcher racemicMacher = matchRacemic.matcher(txt);
if (racemicMacher.lookingAt()) {
txt = txt.substring(racemicMacher.group().length());
racemicStereo = true;
}
else {
racemicStereo = false;
}
if (txt.length() > 0) {//if txt is just "rel- or rac-" then it will be length 0 at this point
List<String> stereoChemistryDescriptors = splitStereoBracketIntoDescriptors(txt);
boolean exclusiveStereoTerm = false;
if (stereoChemistryDescriptors.size() == 1){
String stereoChemistryDescriptor = stereoChemistryDescriptors.get(0);
if (stereoChemistryDescriptor.equalsIgnoreCase("rel")){
exclusiveStereoTerm = true;
}
if (matchRacemic.matcher(stereoChemistryDescriptor).matches()) {
racemicStereo = true;
exclusiveStereoTerm = true;
}
}
if (!exclusiveStereoTerm) {
for (String stereoChemistryDescriptor : stereoChemistryDescriptors) {
Matcher m = matchStereochemistry.matcher(stereoChemistryDescriptor);
if (m.matches()){
Element stereoChemEl = new TokenEl(STEREOCHEMISTRY_EL, stereoChemistryDescriptor);
String locantVal = m.group(1);
if (locantVal.length() > 0){
stereoChemEl.addAttribute(new Attribute(LOCANT_ATR, fixLocantCapitalisation(StringTools.removeDashIfPresent(locantVal))));
}
OpsinTools.insertBefore(stereoChemistryElement, stereoChemEl);
if (matchRS.matcher(m.group(2)).matches()) {
stereoChemEl.addAttribute(new Attribute(TYPE_ATR, R_OR_S_TYPE_VAL));
String symbol = m.group(2).toUpperCase(Locale.ROOT).replaceAll("/", "");
if (racemicStereo && symbol.length() == 1){
symbol = (symbol.equals("R")) ? "RS" : "SR";
}
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, symbol));
} else if (matchEZ.matcher(m.group(2)).matches()) {
stereoChemEl.addAttribute(new Attribute(TYPE_ATR, E_OR_Z_TYPE_VAL));
String symbol = m.group(2).toUpperCase(Locale.ROOT);
stereoChemEl.addAttribute(new Attribute(VALUE_ATR,symbol));
} else if (matchAlphaBetaStereochem.matcher(m.group(2)).matches()){
stereoChemEl.addAttribute(new Attribute(TYPE_ATR, ALPHA_OR_BETA_TYPE_VAL));
if (Character.toLowerCase(m.group(2).charAt(0)) == 'a'){
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, "alpha"));
}
else if (Character.toLowerCase(m.group(2).charAt(0)) == 'b'){
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, "beta"));
}
else if (Character.toLowerCase(m.group(2).charAt(0)) == 'x'){
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, "xi"));
}
else{
throw new ComponentGenerationException("Malformed alpha/beta stereochemistry element: " + stereoChemistryElement.getValue());
}
} else if (matchCisTrans.matcher(m.group(2)).matches()) {
stereoChemEl.addAttribute(new Attribute(TYPE_ATR, CISORTRANS_TYPE_VAL));
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, m.group(2).toLowerCase(Locale.ROOT)));
} else if (matchEndoExoSynAnti.matcher(m.group(2)).matches()) {
stereoChemEl.addAttribute(new Attribute(TYPE_ATR, ENDO_EXO_SYN_ANTI_TYPE_VAL));
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, m.group(2).toLowerCase(Locale.ROOT)));
} else if (matchAxialStereo.matcher(m.group(2)).matches()) {
stereoChemEl.addAttribute(new Attribute(TYPE_ATR, AXIAL_TYPE_VAL));
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, m.group(2)));
} else {
throw new ComponentGenerationException("Malformed stereochemistry element: " + stereoChemistryElement.getValue());
}
} else {
throw new ComponentGenerationException("Malformed stereochemistry element: " + stereoChemistryElement.getValue());
}
}
}
}
stereoChemistryElement.detach();
}
private List<String> splitStereoBracketIntoDescriptors(String stereoBracket) {
List<String> stereoDescriptors = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
//ignore first and last character (opening and closing bracket)
for (int i = 1, l = stereoBracket.length() - 1; i < l; i++) {
char ch = stereoBracket.charAt(i);
if (ch ==','){
stereoDescriptors.add(sb.toString());
sb.setLength(0);
}
else if (ch == '-'){
if (matchStereochemistry.matcher(sb.toString()).matches()){
//delimiter between stereochemistry
stereoDescriptors.add(sb.toString());
sb.setLength(0);
}
else{
//locanted stereochemistry term
sb.append(ch);
}
}
else{
sb.append(ch);
}
}
stereoDescriptors.add(sb.toString());
return stereoDescriptors;
}
private boolean assignLocantUsingPreviousElementIfPresent(Element stereoChemistryElement) {
Element possibleLocant = OpsinTools.getPrevious(stereoChemistryElement);
if (possibleLocant !=null && possibleLocant.getName().equals(LOCANT_EL) && possibleLocant.getValue().split(",").length==1){
stereoChemistryElement.addAttribute(new Attribute(LOCANT_ATR, possibleLocant.getValue()));
possibleLocant.detach();
return true;
}
return false;
}
private void processLocantAssigningForEndoExoSynAnti(Element stereoChemistryElement) {
Element possibleLocant = OpsinTools.getPrevious(stereoChemistryElement);
if (possibleLocant !=null && possibleLocant.getName().equals(LOCANT_EL) && possibleLocant.getValue().split(",").length==1){
stereoChemistryElement.addAttribute(new Attribute(LOCANT_ATR, possibleLocant.getValue()));
Element group = OpsinTools.getNextSibling(stereoChemistryElement, GROUP_EL);
if (group != null &&
(CYCLICUNSATURABLEHYDROCARBON_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))
|| OpsinTools.getPreviousSibling(group).getName().equals(VONBAEYER_EL))){
//detach locant only if we're sure it has no other meaning
//typically locants in front of endo/exo/syn/anti also indicate the position of a susbtituent/suffix e.g. 3-exo-amino
possibleLocant.detach();
}
}
}
private void processUnbracketedAlphaBetaStereochemistry(Element stereoChemistryElement) throws ComponentGenerationException {
String txt = StringTools.removeDashIfPresent(stereoChemistryElement.getValue());
String[] stereoChemistryDescriptors = txt.split(",");
List<String> locants = new ArrayList<String>();
boolean createLocantsEl =false;
for (String stereoChemistryDescriptor : stereoChemistryDescriptors) {
Matcher digitMatcher = MATCH_DIGITS.matcher(stereoChemistryDescriptor);
if (digitMatcher.lookingAt()){
String locant = digitMatcher.group();
String possibleAlphaBeta = digitMatcher.replaceAll("");
locants.add(locant);
Matcher alphaBetaMatcher = matchAlphaBetaStereochem.matcher(possibleAlphaBeta);
if (alphaBetaMatcher.matches()){
Element stereoChemEl = new TokenEl(STEREOCHEMISTRY_EL, stereoChemistryDescriptor);
stereoChemEl.addAttribute(new Attribute(LOCANT_ATR, locant));
OpsinTools.insertBefore(stereoChemistryElement, stereoChemEl);
stereoChemEl.addAttribute(new Attribute(TYPE_ATR, ALPHA_OR_BETA_TYPE_VAL));
if (Character.toLowerCase(possibleAlphaBeta.charAt(0)) == 'a'){
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, "alpha"));
}
else if (Character.toLowerCase(possibleAlphaBeta.charAt(0)) == 'b'){
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, "beta"));
}
else if (Character.toLowerCase(possibleAlphaBeta.charAt(0)) == 'x'){
stereoChemEl.addAttribute(new Attribute(VALUE_ATR, "xi"));
}
else{
throw new ComponentGenerationException("Malformed alpha/beta stereochemistry element: " + stereoChemistryElement.getValue());
}
}
else{
createLocantsEl =true;
}
}
}
if (!createLocantsEl){
//create locants unless a group supporting alpha/beta stereochem is within this substituent/root
createLocantsEl =true;
List<Element> groups = OpsinTools.getNextSiblingsOfType(stereoChemistryElement, GROUP_EL);
for (Element group : groups) {
if (group.getAttributeValue(ALPHABETACLOCKWISEATOMORDERING_ATR)!=null){
createLocantsEl=false;
break;
}
}
}
if (createLocantsEl){
Element newLocantEl = new TokenEl(LOCANT_EL, StringTools.stringListToString(locants, ","));
OpsinTools.insertAfter(stereoChemistryElement, newLocantEl);
}
stereoChemistryElement.detach();
}
private void processRelativeCisTrans(Element stereoChemistryElement) {
String value = StringTools.removeDashIfPresent(stereoChemistryElement.getValue());
StringBuilder sb = new StringBuilder();
String[] terms = value.split(",");
for (String term : terms) {
if (term.startsWith("c-")|| term.startsWith("t-") || term.startsWith("r-")){
if (sb.length() > 0){
sb.append(',');
}
sb.append(term.substring(2));
}
else{
throw new RuntimeException("Malformed relativeCisTrans element");
}
}
Element locantEl = new TokenEl(LOCANT_EL, sb.toString());
OpsinTools.insertAfter(stereoChemistryElement, locantEl);
}
/**
* If the e/z term is next to an ene or ylidene duplicate the locant
* e.g. 2E,4Z-diene --> 2E,4Z-2,4-diene
* 2E-ylidene --> 2E-2-ylidene
* @param locantedUnbrackettedEzTerms
*/
private void duplicateLocantFromStereoTermIfAdjacentToEneOrYlidene(List<Element> locantedUnbrackettedEzTerms) {
for (int i = 0, l = locantedUnbrackettedEzTerms.size(); i < l; i++) {
Element currentTerm = locantedUnbrackettedEzTerms.get(i);
List<Element> groupedTerms = new ArrayList<Element>();
groupedTerms.add(currentTerm);
while (i + 1 < l && locantedUnbrackettedEzTerms.get(i + 1).equals(OpsinTools.getNextSibling(currentTerm))) {
currentTerm = locantedUnbrackettedEzTerms.get(++i);
groupedTerms.add(currentTerm);
}
Element lastTermInGroup = groupedTerms.get(groupedTerms.size() - 1);
Element eneOrYlidene;
if (groupedTerms.size() > 1) {
Element multiplier = OpsinTools.getNextSibling(lastTermInGroup);
if (!(multiplier != null && multiplier.getName().equals(MULTIPLIER_EL) && String.valueOf(groupedTerms.size()).equals(multiplier.getAttributeValue(VALUE_ATR)))) {
continue;
}
eneOrYlidene = OpsinTools.getNextSibling(multiplier);
}
else {
eneOrYlidene = OpsinTools.getNextSibling(lastTermInGroup);
}
if (eneOrYlidene != null) {
String name = eneOrYlidene.getName();
if (name.equals(UNSATURATOR_EL) || name.equals(SUFFIX_EL)) {
if ((name.equals(UNSATURATOR_EL) && eneOrYlidene.getAttributeValue(VALUE_ATR).equals("2"))
|| (name.equals(SUFFIX_EL) && eneOrYlidene.getAttributeValue(VALUE_ATR).equals("ylidene"))) {
List<String> locants = new ArrayList<String>();
for (Element stereochemistryTerm : groupedTerms) {
locants.add(stereochemistryTerm.getAttributeValue(LOCANT_ATR));
}
Element newLocant = new TokenEl(LOCANT_EL, StringTools.stringListToString(locants, ","));
OpsinTools.insertAfter(lastTermInGroup, newLocant);
} else{
if (name.equals(UNSATURATOR_EL)){
throw new RuntimeException("After E/Z stereo expected ene but found: " + eneOrYlidene.getValue());
}
else {
throw new RuntimeException("After E/Z stereo expected yldiene but found: " + eneOrYlidene.getValue());
}
}
}
}
}
}
/**
* Looks for "suffixPrefix" and assigns their value them as an attribute of an adjacent suffix
* @param subOrRoot
* @throws ComponentGenerationException
*/
private void processSuffixPrefixes(Element subOrRoot) throws ComponentGenerationException {
List<Element> suffixPrefixes = subOrRoot.getChildElements(SUFFIXPREFIX_EL);
for (Element suffixPrefix : suffixPrefixes) {
Element suffix = OpsinTools.getNextSibling(suffixPrefix);
if (suffix==null || ! suffix.getName().equals(SUFFIX_EL)){
throw new ComponentGenerationException("OPSIN bug: suffix not found after suffixPrefix: " + suffixPrefix.getValue());
}
suffix.addAttribute(new Attribute(SUFFIXPREFIX_ATR, suffixPrefix.getAttributeValue(VALUE_ATR)));
suffixPrefix.detach();
}
}
/**
* Looks for infixes and assigns them to the next suffix using a semicolon delimited infix attribute
* If the infix/suffix block has been bracketed e.g (dithioate) then the infix is multiplied out
* If preceded by a suffixPrefix e.g. sulfono infixes are also multiplied out
* If a multiplier is present and neither of these cases are met then it is ambiguous as to whether the multiplier is referring to the infix or the infixed suffix
* This ambiguity is resolved in processInfixFunctionalReplacementNomenclature by looking at the structure of the suffix to be modified
* @param subOrRoot
* @throws ComponentGenerationException
*/
private void processInfixes(Element subOrRoot) throws ComponentGenerationException {
List<Element> infixes = subOrRoot.getChildElements(INFIX_EL);
for (Element infix : infixes) {
Element suffix = OpsinTools.getNextSiblingIgnoringCertainElements(infix, new String[]{INFIX_EL, SUFFIXPREFIX_EL, MULTIPLIER_EL});
if (suffix ==null || !suffix.getName().equals(SUFFIX_EL)){
throw new ComponentGenerationException("No suffix found next next to infix: "+ infix.getValue());
}
List<String> currentInfixInformation;
if (suffix.getAttribute(INFIX_ATR)==null){
suffix.addAttribute(new Attribute(INFIX_ATR, ""));
currentInfixInformation = new ArrayList<String>();
}
else{
currentInfixInformation = StringTools.arrayToList(suffix.getAttributeValue(INFIX_ATR).split(";"));
}
String infixValue =infix.getAttributeValue(VALUE_ATR);
currentInfixInformation.add(infixValue);
Element possibleMultiplier = OpsinTools.getPreviousSibling(infix);
Element possibleBracket;
boolean multiplierKnownToIndicateInfixMultiplicationPresent =false;
if (possibleMultiplier.getName().equals(MULTIPLIER_EL)){
//suffix prefix present so multiplier must indicate infix replacement
Element possibleSuffixPrefix = OpsinTools.getPreviousSiblingIgnoringCertainElements(infix, new String[]{MULTIPLIER_EL, INFIX_EL});
if (possibleSuffixPrefix!=null && possibleSuffixPrefix.getName().equals(SUFFIXPREFIX_EL)){
multiplierKnownToIndicateInfixMultiplicationPresent =true;
}
Element elementBeforeMultiplier = OpsinTools.getPreviousSibling(possibleMultiplier);
//double multiplier indicates multiple suffixes which all have their infix multiplied
//if currentInfixInformation contains more than 1 entry it contains information from an infix from before the multiplier so the interpretation of the multiplier as a suffix multiplier is impossible
if (elementBeforeMultiplier.getName().equals(MULTIPLIER_EL) || currentInfixInformation.size() > 1){
multiplierKnownToIndicateInfixMultiplicationPresent =true;
}
possibleBracket = elementBeforeMultiplier;
}
else{
possibleBracket=possibleMultiplier;
possibleMultiplier=null;
infix.detach();
}
if (possibleBracket.getName().equals(STRUCTURALOPENBRACKET_EL)){
Element bracket = OpsinTools.getNextSibling(suffix);
if (!bracket.getName().equals(STRUCTURALCLOSEBRACKET_EL)){
throw new ComponentGenerationException("Matching closing bracket not found around infix/suffix block");
}
if (possibleMultiplier!=null){
int multiplierVal = Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR));
for (int i = 1; i < multiplierVal; i++) {
currentInfixInformation.add(infixValue);
}
possibleMultiplier.detach();
infix.detach();
}
possibleBracket.detach();
bracket.detach();
}
else if (multiplierKnownToIndicateInfixMultiplicationPresent){//multiplier unambiguously means multiplication of the infix
int multiplierVal = Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR));
for (int i = 1; i < multiplierVal; i++) {
currentInfixInformation.add(infixValue);
}
possibleMultiplier.detach();
infix.detach();
}
else if (possibleMultiplier!=null && GROUP_TYPE_VAL.equals(possibleMultiplier.getAttributeValue(TYPE_ATR))){//e.g. ethanbisthioic acid == ethanbis(thioic acid)
infix.detach();
}
suffix.getAttribute(INFIX_ATR).setValue(StringTools.stringListToString(currentInfixInformation, ";"));
}
}
/**
* Identifies lambdaConvention elements.
* The elementsValue is expected to be a comma seperated lambda values and 0 or more locants. Where a lambda value has the following form:
* optional locant, the word lambda and then a number which is the valency specified (with possibly some attempt to indicate this number is superscripted)
* If the element is followed by heteroatoms (possibly multiplied) they are multiplied and the locant/lambda assigned to them
* Otherwise a new lambdaConvention element is created with the valency specified by the lambda convention taking the attribute "lambda"
* In the case where heteroatoms belong to a fused ring system a new lambdaConvention element is also created. The original locants are retained in the benzo specific fused ring nomenclature:
* 2H-5lambda^5-phosphinino[3,2-b]pyran --> 2H 5lambda^5 phosphinino[3,2-b]pyran BUT
* 1lambda^4,5-Benzodithiepin --> 1lambda^4 1,5-Benzodithiepin
* @param subOrRoot
* @throws ComponentGenerationException
*/
private void processLambdaConvention(Element subOrRoot) throws ComponentGenerationException {
List<Element> lambdaConventionEls = subOrRoot.getChildElements(LAMBDACONVENTION_EL);
boolean fusedRingPresent = false;
if (lambdaConventionEls.size()>0){
if (subOrRoot.getChildElements(GROUP_EL).size()>1){
fusedRingPresent = true;
}
}
for (Element lambdaConventionEl : lambdaConventionEls) {
boolean frontLocantsExpected =false;//Is the lambdaConvention el followed by benz/benzo of a fused ring system (these have front locants which correspond to the final fused rings numbering) or by a polycylicspiro system
String[] lambdaValues = StringTools.removeDashIfPresent(lambdaConventionEl.getValue()).split(",");
Element possibleHeteroatomOrMultiplier = OpsinTools.getNextSibling(lambdaConventionEl);
int heteroCount = 0;
int multiplierValue = 1;
while(possibleHeteroatomOrMultiplier != null){
if(possibleHeteroatomOrMultiplier.getName().equals(HETEROATOM_EL)) {
heteroCount+=multiplierValue;
multiplierValue =1;
} else if (possibleHeteroatomOrMultiplier.getName().equals(MULTIPLIER_EL)){
multiplierValue = Integer.parseInt(possibleHeteroatomOrMultiplier.getAttributeValue(VALUE_ATR));
}
else{
break;
}
possibleHeteroatomOrMultiplier = OpsinTools.getNextSibling(possibleHeteroatomOrMultiplier);
}
boolean assignLambdasToHeteroAtoms =false;
if (lambdaValues.length==heteroCount){//heteroatom and number of locants +lambdas must match
if (fusedRingPresent && possibleHeteroatomOrMultiplier!=null && possibleHeteroatomOrMultiplier.getName().equals(GROUP_EL) && possibleHeteroatomOrMultiplier.getAttributeValue(SUBTYPE_ATR).equals(HANTZSCHWIDMAN_SUBTYPE_VAL)){
//You must not set the locants of a HW system which forms a component of a fused ring system. The locant specified corresponds to the complete fused ring system.
}
else{
assignLambdasToHeteroAtoms =true;
}
}
else if (possibleHeteroatomOrMultiplier!=null && ((heteroCount==0 && OpsinTools.getNextSibling(lambdaConventionEl).equals(possibleHeteroatomOrMultiplier) &&
fusedRingPresent && possibleHeteroatomOrMultiplier.getName().equals(GROUP_EL) &&
(possibleHeteroatomOrMultiplier.getValue().equals("benzo") || possibleHeteroatomOrMultiplier.getValue().equals("benz"))
&& !OpsinTools.getNextSibling(possibleHeteroatomOrMultiplier).getName().equals(FUSION_EL)
&& !OpsinTools.getNextSibling(possibleHeteroatomOrMultiplier).getName().equals(LOCANT_EL))
|| (possibleHeteroatomOrMultiplier.getName().equals(POLYCYCLICSPIRO_EL) &&
(possibleHeteroatomOrMultiplier.getAttributeValue(VALUE_ATR).equals("spirobi")|| possibleHeteroatomOrMultiplier.getAttributeValue(VALUE_ATR).equals("spiroter"))))){
frontLocantsExpected = true;//a benzo fused ring e.g. 1lambda4,3-benzothiazole or a symmetrical poly cyclic spiro system
}
List<Element> heteroAtoms = new ArrayList<Element>();//contains the heteroatoms to apply the lambda values too. Can be empty if the values are applied to a group directly rather than to a heteroatom
if (assignLambdasToHeteroAtoms){//populate heteroAtoms, multiplied heteroatoms are multiplied out
Element multiplier = null;
Element heteroatomOrMultiplier = OpsinTools.getNextSibling(lambdaConventionEl);
while(heteroatomOrMultiplier != null){
if(heteroatomOrMultiplier.getName().equals(HETEROATOM_EL)) {
heteroAtoms.add(heteroatomOrMultiplier);
if (multiplier!=null){
for (int i = 1; i < Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); i++) {
Element newHeteroAtom = heteroatomOrMultiplier.copy();
OpsinTools.insertBefore(heteroatomOrMultiplier, newHeteroAtom);
heteroAtoms.add(newHeteroAtom);
}
multiplier.detach();
multiplier=null;
}
} else if (heteroatomOrMultiplier.getName().equals(MULTIPLIER_EL)){
if (multiplier !=null){
break;
}
else{
multiplier = heteroatomOrMultiplier;
}
}
else{
break;
}
heteroatomOrMultiplier = OpsinTools.getNextSibling(heteroatomOrMultiplier);
}
}
for (int i = 0; i < lambdaValues.length; i++) {//assign all the lambdas to heteroatoms or to newly created lambdaConvention elements
Matcher m = matchLambdaConvention.matcher(lambdaValues[i]);
if (m.matches()){//a lambda
Attribute valencyChange = new Attribute(LAMBDA_ATR, m.group(2));
String locant = m.group(1) != null ? fixLocantCapitalisation(m.group(1)) : null;
if (frontLocantsExpected){
if (locant == null) {
throw new ComponentGenerationException("Locant not found for lambda convention before a benzo fused ring system");
}
lambdaValues[i] = locant;
}
if (assignLambdasToHeteroAtoms){
Element heteroAtom = heteroAtoms.get(i);
heteroAtom.addAttribute(valencyChange);
if (locant != null) {
heteroAtom.addAttribute(LOCANT_ATR, locant);
}
}
else{
Element newLambda = new TokenEl(LAMBDACONVENTION_EL);
newLambda.addAttribute(valencyChange);
if (locant != null) {
newLambda.addAttribute(LOCANT_ATR, locant);
}
OpsinTools.insertBefore(lambdaConventionEl, newLambda);
}
}
else{//just a locant e.g 1,3lambda5
String locant = fixLocantCapitalisation(lambdaValues[i]);
lambdaValues[i] = locant;
if (!assignLambdasToHeteroAtoms){
if (!frontLocantsExpected){
throw new ComponentGenerationException("Lambda convention not specified for locant: " + locant);
}
}
else{
Element heteroAtom = heteroAtoms.get(i);
heteroAtom.addAttribute(new Attribute(LOCANT_ATR, locant));
}
}
}
if (!frontLocantsExpected){
lambdaConventionEl.detach();
}
else{
lambdaConventionEl.setName(LOCANT_EL);
lambdaConventionEl.setValue(StringTools.arrayToString(lambdaValues, ","));
}
}
}
/**Finds matching open and close brackets, and places the
* elements contained within in a big <bracket> element.
* @param brackets
*
* @param substituentsAndRoot: The substituent/root elements at the current level of the tree
* @throws ComponentGenerationException
*/
private void findAndStructureBrackets(List<Element> substituentsAndRoot, List<Element> brackets) throws ComponentGenerationException {
int blevel = 0;
Element openBracket = null;
boolean nestedBrackets = false;
for (Element sub : substituentsAndRoot) {
List<Element> children = sub.getChildElements();
for (Element child : children) {
String name = child.getName();
if(name.equals(OPENBRACKET_EL)) {
blevel++;
if(openBracket == null) {
openBracket = child;
}
else {
nestedBrackets = true;
}
} else if (name.equals(CLOSEBRACKET_EL)) {
blevel--;
if(blevel == 0) {
Element bracket = structureBrackets(openBracket, child);
brackets.add(bracket);
if (nestedBrackets) {
findAndStructureBrackets(OpsinTools.getDescendantElementsWithTagNames(bracket, new String[]{SUBSTITUENT_EL, ROOT_EL}), brackets);
}
openBracket = null;
nestedBrackets = false;
}
}
}
}
if (blevel != 0){
throw new ComponentGenerationException("Brackets do not match!");
}
}
/**Places the elements in substituents containing/between an open and close bracket
* in a <bracket> tag.
*
* @param openBracket The open bracket element
* @param closeBracket The close bracket element
* @return The bracket element thus created.
* @throws ComponentGenerationException
*/
private Element structureBrackets(Element openBracket, Element closeBracket) throws ComponentGenerationException {
Element bracket = new GroupingEl(BRACKET_EL);
Element currentEl = openBracket.getParent();
OpsinTools.insertBefore(currentEl, bracket);
/* Pick up everything in the substituent before the bracket*/
Element firstChild = currentEl.getChild(0);
while(!firstChild.equals(openBracket)) {
firstChild.detach();
bracket.addChild(firstChild);
firstChild = currentEl.getChild(0);
}
/* Pick up all elements from the one with the open bracket,
* to the one with the close bracket, inclusive.
*/
while(!currentEl.equals(closeBracket.getParent())) {
Element nextEl = OpsinTools.getNextSibling(currentEl);
currentEl.detach();
bracket.addChild(currentEl);
currentEl = nextEl;
if (currentEl == null) {
throw new ComponentGenerationException("Brackets within a word do not match!");
}
}
currentEl.detach();
bracket.addChild(currentEl);
/* Pick up elements after the close bracket */
currentEl = OpsinTools.getNextSibling(closeBracket);
while(currentEl != null) {
Element nextEl = OpsinTools.getNextSibling(currentEl);
currentEl.detach();
bracket.addChild(currentEl);
currentEl = nextEl;
}
openBracket.detach();
closeBracket.detach();
return bracket;
}
/**Looks for annulen/polyacene/polyaphene/polyalene/polyphenylene/polynaphthylene/polyhelicene tags and replaces them with a group with appropriate SMILES.
* @param subOrRoot The subOrRoot to look for tags in
* @throws ComponentGenerationException
*/
private void processHydroCarbonRings(Element subOrRoot) throws ComponentGenerationException {
List<Element> annulens = subOrRoot.getChildElements(ANNULEN_EL);
for (Element annulen : annulens) {
String annulenValue =annulen.getValue();
Matcher match = matchAnnulene.matcher(annulenValue);
match.matches();
if (match.groupCount() !=1){
throw new ComponentGenerationException("Invalid annulen tag");
}
int annulenSize=Integer.valueOf(match.group(1));
if (annulenSize <3){
throw new ComponentGenerationException("Invalid annulen tag");
}
//build [annulenSize]annulene ring as SMILES
String SMILES = "c1" +StringTools.multiplyString("c", annulenSize -1);
SMILES += "1";
Element group =new TokenEl(GROUP_EL, annulenValue);
group.addAttribute(new Attribute(VALUE_ATR, SMILES));
group.addAttribute(new Attribute(LABELS_ATR, NUMERIC_LABELS_VAL));
group.addAttribute(new Attribute(TYPE_ATR, RING_TYPE_VAL));
group.addAttribute(new Attribute(SUBTYPE_ATR, RING_SUBTYPE_VAL));
annulen.getParent().replaceChild(annulen, group);
}
List<Element> hydrocarbonFRSystems = subOrRoot.getChildElements(HYDROCARBONFUSEDRINGSYSTEM_EL);
for (Element hydrocarbonFRSystem : hydrocarbonFRSystems) {
Element multiplier = OpsinTools.getPreviousSibling(hydrocarbonFRSystem);
if(multiplier != null && multiplier.getName().equals(MULTIPLIER_EL)) {
int multiplierValue =Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR));
String classOfHydrocarbonFRSystem =hydrocarbonFRSystem.getAttributeValue(VALUE_ATR);
StringBuilder smilesSB= new StringBuilder();
if (classOfHydrocarbonFRSystem.equals("polyacene")){
if (multiplierValue <=3){
throw new ComponentGenerationException("Invalid polyacene");
}
smilesSB.append("c1ccc");
for (int j = 2; j <= multiplierValue; j++) {
smilesSB.append("c");
smilesSB.append(ringClosure(j));
smilesSB.append("c");
}
smilesSB.append("ccc");
for (int j = multiplierValue; j >2; j--) {
smilesSB.append("c");
smilesSB.append(ringClosure(j));
smilesSB.append("c");
}
smilesSB.append("c12");
}else if (classOfHydrocarbonFRSystem.equals("polyaphene")){
if (multiplierValue <=3){
throw new ComponentGenerationException("Invalid polyaphene");
}
smilesSB.append("c1ccc");
int ringsAbovePlane;
int ringsOnPlane;
int ringOpeningCounter=2;
if (multiplierValue %2==0){
ringsAbovePlane =(multiplierValue-2)/2;
ringsOnPlane =ringsAbovePlane +1;
}
else{
ringsAbovePlane =(multiplierValue-1)/2;
ringsOnPlane =ringsAbovePlane;
}
for (int j = 1; j <= ringsAbovePlane; j++) {
smilesSB.append("c");
smilesSB.append(ringClosure(ringOpeningCounter++));
smilesSB.append("c");
}
for (int j = 1; j <= ringsOnPlane; j++) {
smilesSB.append("cc");
smilesSB.append(ringClosure(ringOpeningCounter++));
}
smilesSB.append("ccc");
ringOpeningCounter--;
for (int j = 1; j <= ringsOnPlane; j++) {
smilesSB.append("cc");
smilesSB.append(ringClosure(ringOpeningCounter--));
}
for (int j = 1; j < ringsAbovePlane; j++) {
smilesSB.append("c");
smilesSB.append(ringClosure(ringOpeningCounter--));
smilesSB.append("c");
}
smilesSB.append("c12");
} else if (classOfHydrocarbonFRSystem.equals("polyalene")){
if (multiplierValue <5){
throw new ComponentGenerationException("Invalid polyalene");
}
smilesSB.append("c1");
for (int j = 3; j < multiplierValue; j++) {
smilesSB.append("c");
}
smilesSB.append("c2");
for (int j = 3; j <= multiplierValue; j++) {
smilesSB.append("c");
}
smilesSB.append("c12");
} else if (classOfHydrocarbonFRSystem.equals("polyphenylene")){
if (multiplierValue <2){
throw new ComponentGenerationException("Invalid polyphenylene");
}
smilesSB.append("c1cccc2");
for (int j = 1; j < multiplierValue; j++) {
smilesSB.append("c3ccccc3");
}
smilesSB.append("c12");
} else if (classOfHydrocarbonFRSystem.equals("polynaphthylene")){
if (multiplierValue <3){
throw new ComponentGenerationException("Invalid polynaphthylene");
}
smilesSB.append("c1cccc2cc3");
for (int j = 1; j < multiplierValue; j++) {
smilesSB.append("c4cc5ccccc5cc4");
}
smilesSB.append("c3cc12");
} else if (classOfHydrocarbonFRSystem.equals("polyhelicene")){
if (multiplierValue <4){
throw new ComponentGenerationException("Invalid polyhelicene");
}
smilesSB.append("c1c");
int ringOpeningCounter=2;
for (int j = 1; j < multiplierValue; j++) {
smilesSB.append("ccc");
smilesSB.append(ringClosure(ringOpeningCounter++));
}
smilesSB.append("cccc");
ringOpeningCounter--;
for (int j = 2; j < multiplierValue; j++) {
smilesSB.append("c");
smilesSB.append(ringClosure(ringOpeningCounter--));
}
smilesSB.append("c12");
}
else{
throw new ComponentGenerationException("Unknown semi-trivially named hydrocarbon fused ring system");
}
Element newGroup =new TokenEl(GROUP_EL, multiplier.getValue() + hydrocarbonFRSystem.getValue());
newGroup.addAttribute(new Attribute(VALUE_ATR, smilesSB.toString()));
newGroup.addAttribute(new Attribute(LABELS_ATR, FUSEDRING_LABELS_VAL));
newGroup.addAttribute(new Attribute(TYPE_ATR, RING_TYPE_VAL));
newGroup.addAttribute(new Attribute(SUBTYPE_ATR, HYDROCARBONFUSEDRINGSYSTEM_EL));
hydrocarbonFRSystem.getParent().replaceChild(hydrocarbonFRSystem, newGroup);
multiplier.detach();
}
else{
throw new ComponentGenerationException("Invalid semi-trivially named hydrocarbon fused ring system");
}
}
}
/**
* Handles irregular suffixes. e.g. Quinone and ylene
* @param subOrRoot
* @throws ComponentGenerationException
*/
private void handleSuffixIrregularities(Element subOrRoot) throws ComponentGenerationException {
List<Element> suffixes = subOrRoot.getChildElements(SUFFIX_EL);
for (Element suffix : suffixes) {
String suffixValue = suffix.getValue();
if (suffixValue.equals("ic") || suffixValue.equals("ous")){
if (!n2sConfig.allowInterpretationOfAcidsWithoutTheWordAcid()) {
Element next = OpsinTools.getNext(suffix);
if (next == null){
throw new ComponentGenerationException("\"acid\" not found after " +suffixValue);
}
}
}
// convert quinone to dione
else if (suffixValue.equals("quinone") || suffixValue.equals("quinon")){
suffix.removeAttribute(suffix.getAttribute(ADDITIONALVALUE_ATR));
suffix.setValue("one");
Element multiplier = OpsinTools.getPreviousSibling(suffix);
if (multiplier.getName().equals(MULTIPLIER_EL)){
Attribute multVal = multiplier.getAttribute(VALUE_ATR);
int newMultiplier = Integer.parseInt(multVal.getValue()) * 2;
multVal.setValue(String.valueOf(newMultiplier));
}
else{
multiplier = new TokenEl(MULTIPLIER_EL, "di");
multiplier.addAttribute(new Attribute(VALUE_ATR, "2"));
OpsinTools.insertBefore(suffix, multiplier);
}
}
else if (suffixValue.equals("ylene") || suffixValue.equals("ylen")){
suffix.removeAttribute(suffix.getAttribute(ADDITIONALVALUE_ATR));
suffix.setValue("yl");
Element alk = OpsinTools.getPreviousSibling(suffix, GROUP_EL);
if (alk.getAttribute(USABLEASJOINER_ATR)!=null){
alk.removeAttribute(alk.getAttribute(USABLEASJOINER_ATR));
}
Element multiplier = new TokenEl(MULTIPLIER_EL, "di");
multiplier.addAttribute(new Attribute(VALUE_ATR, "2"));
OpsinTools.insertBefore(suffix, multiplier);
}
else if (suffixValue.equals("ylium") &&//disambiguate between ylium the charge modifying suffix and ylium the acylium suffix
"acylium".equals(suffix.getAttributeValue(VALUE_ATR)) &&
suffix.getAttribute(SUFFIXPREFIX_ATR)==null &&
suffix.getAttribute(INFIX_ATR)==null){
Element group = OpsinTools.getPreviousSibling(suffix, GROUP_EL);
if (group==null || (!ACIDSTEM_TYPE_VAL.equals(group.getAttributeValue(TYPE_ATR)) &&
!CHALCOGENACIDSTEM_TYPE_VAL.equals(group.getAttributeValue(TYPE_ATR)) &&
!NONCARBOXYLICACID_TYPE_VAL.equals(group.getAttributeValue(TYPE_ATR)))){
Element beforeSuffix = OpsinTools.getPreviousSibling(suffix);
String o = beforeSuffix.getAttributeValue(SUBSEQUENTUNSEMANTICTOKEN_ATR);
if (o ==null || !StringTools.endsWithCaseInsensitive(o, "o")){
if (group!=null && ARYLSUBSTITUENT_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){
//contracted form for removal of hydride e.g. 9-Anthrylium
suffix.getAttribute(VALUE_ATR).setValue("ylium");
suffix.getAttribute(TYPE_ATR).setValue(CHARGE_TYPE_VAL);
suffix.removeAttribute(suffix.getAttribute(SUBTYPE_ATR));
}
else{
throw new ComponentGenerationException("ylium is intended to be the removal of H- in this context not the formation of an acylium ion");
}
}
}
}
else if (suffixValue.equals("nitrolic acid") || suffixValue.equals("nitrolicacid")) {
Element precedingGroup = OpsinTools.getPreviousSibling(suffix, GROUP_EL);
if (precedingGroup == null){
if (subOrRoot.getChildCount() != 1) {
throw new RuntimeException("OPSIN Bug: nitrolic acid not expected to have sibilings");
}
Element precedingSubstituent = OpsinTools.getPreviousSibling(subOrRoot);
if(precedingSubstituent == null || !precedingSubstituent.getName().equals(SUBSTITUENT_EL)){
throw new ComponentGenerationException("Expected substituent before nitrolic acid");
}
List<Element> existingSuffixes = precedingSubstituent.getChildElements(SUFFIX_EL);
if (existingSuffixes.size() == 1) {
if (!existingSuffixes.get(0).getValue().equals("yl")){
throw new ComponentGenerationException("Unexpected suffix found before nitrolic acid");
}
existingSuffixes.get(0).detach();
for (Element child : precedingSubstituent.getChildElements()) {
child.detach();
OpsinTools.insertBefore(suffix, child);
}
precedingSubstituent.detach();
}
else{
throw new ComponentGenerationException("Only the nitrolic acid case where it is preceded by an yl suffix is supported");
}
}
}
}
}
/**
* Looks for alkaneStems followed by a bridge forming 'o' and makes them fused ring bridge elements
* @param group
*/
private void detectAlkaneFusedRingBridges(Element group) {
if (ALKANESTEM_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){
Element unsaturator = OpsinTools.getNextSibling(group);
if (unsaturator != null && unsaturator.getName().equals(UNSATURATOR_EL)) {
Element possibleBridgeFormer = OpsinTools.getNextSiblingIgnoringCertainElements(group, new String[]{UNSATURATOR_EL});
if(possibleBridgeFormer != null && possibleBridgeFormer.getName().equals(BRIDGEFORMINGO_EL)){
group.setName(FUSEDRINGBRIDGE_EL);
Attribute smilesValAtr = group.getAttribute(VALUE_ATR);
smilesValAtr.setValue("-" + smilesValAtr.getValue() + "-");
possibleBridgeFormer.detach();
unsaturator.detach();
}
}
}
}
/**Looks (multiplier)cyclo/spiro/cyclo tags before chain
* and replaces them with a group with appropriate SMILES
* Note that only simple spiro tags are handled at this stage i.e. not dispiro
* @param group A group which is potentially a chain
* @throws ComponentGenerationException
*/
private void processRings(Element group) throws ComponentGenerationException {
Element previous = OpsinTools.getPreviousSiblingIgnoringCertainElements(group, new String[]{LOCANT_EL});
if(previous != null) {
String previousElType = previous.getName();
if(previousElType.equals(SPIRO_EL)){
processSpiroSystem(group, previous);
} else if(previousElType.equals(VONBAEYER_EL)) {
processVonBaeyerSystem(group, previous);
}
else if(previousElType.equals(CYCLO_EL)) {
processCyclisedChain(group, previous);
}
}
}
/**
* Processes a spiro descriptor element.
* This modifies the provided chainGroup into the spiro system by replacing the value of the chain group with appropriate SMILES
* @param chainGroup
* @param spiroEl
* @throws ComponentGenerationException
* @throws NumberFormatException
*/
private void processSpiroSystem(Element chainGroup, Element spiroEl) throws NumberFormatException, ComponentGenerationException {
int[][] spiroDescriptors = getSpiroDescriptors(StringTools.removeDashIfPresent(spiroEl.getValue()));
Element multiplier = OpsinTools.getPreviousSibling(spiroEl);
int numberOfSpiros = 1;
if (multiplier != null && multiplier.getName().equals(MULTIPLIER_EL) && BASIC_TYPE_VAL.equals(multiplier.getAttributeValue(TYPE_ATR))) {
numberOfSpiros = Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR));
multiplier.detach();
}
int numberOfCarbonInDescriptors =0;
for (int[] spiroDescriptor : spiroDescriptors) {
numberOfCarbonInDescriptors += spiroDescriptor[0];
}
numberOfCarbonInDescriptors += numberOfSpiros;
if (numberOfCarbonInDescriptors != chainGroup.getAttributeValue(VALUE_ATR).length()){
throw new ComponentGenerationException("Disagreement between number of atoms in spiro descriptor: " + numberOfCarbonInDescriptors +" and number of atoms in chain: " + chainGroup.getAttributeValue(VALUE_ATR).length());
}
int numOfOpenedBrackets = 1;
int curIndex = 2;
String smiles = "C0" + StringTools.multiplyString("C", spiroDescriptors[0][0]) + "10(";
// for those molecules where no superstrings compare prefix number with curIndex.
for (int i=1; i< spiroDescriptors.length; i++) {
if (spiroDescriptors[i][1] >= 0) {
int ringOpeningPos = findIndexOfRingOpenings( smiles, spiroDescriptors[i][1] );
String ringOpeningLabel = String.valueOf(smiles.charAt(ringOpeningPos));
ringOpeningPos++;
if (ringOpeningLabel.equals("%")){
while (smiles.charAt(ringOpeningPos)>='0' && smiles.charAt(ringOpeningPos)<='9' && ringOpeningPos < smiles.length()) {
ringOpeningLabel += smiles.charAt(ringOpeningPos);
ringOpeningPos++;
}
}
if (smiles.indexOf("C" + ringOpeningLabel, ringOpeningPos)>=0) {
// this ring opening has already been closed
// i.e. this atom connects more than one ring in a spiro fusion
// insert extra ring opening
smiles = smiles.substring(0, ringOpeningPos) + ringClosure(curIndex) + smiles.substring(ringOpeningPos);
// add ring in new brackets
smiles += "(" + StringTools.multiplyString("C", spiroDescriptors[i][0]) + ringClosure(curIndex) + ")";
curIndex++;
}
else {
smiles += StringTools.multiplyString("C", spiroDescriptors[i][0]) + ringOpeningLabel + ")";
}
}
else if (numOfOpenedBrackets >= numberOfSpiros) {
smiles += StringTools.multiplyString("C", spiroDescriptors[i][0]);
// take the number before bracket as index for smiles
// we can open more brackets, this considered in prev if
curIndex--;
smiles += ringClosure(curIndex) + ")";
// from here start to decrease index for the following
}
else {
smiles += StringTools.multiplyString("C", spiroDescriptors[i][0]);
smiles += "C" + ringClosure(curIndex++) + "(";
numOfOpenedBrackets++;
}
}
chainGroup.getAttribute(VALUE_ATR).setValue(smiles);
chainGroup.getAttribute(TYPE_ATR).setValue(RING_TYPE_VAL);
if (chainGroup.getAttribute(USABLEASJOINER_ATR) !=null){
chainGroup.removeAttribute(chainGroup.getAttribute(USABLEASJOINER_ATR));
}
spiroEl.detach();
}
/**
* If the integer given is > 9 return %ringClosure else just returns ringClosure
* @param ringClosure
* @return
*/
private String ringClosure(int ringClosure) {
if (ringClosure >9){
return "%" +Integer.toString(ringClosure);
}
else{
return Integer.toString(ringClosure);
}
}
/**
* Prepares spiro string for processing
* @param text - string with spiro e.g. spiro[2.2]
* @return array with number of carbons in each group and associated index of spiro atom
*/
private int[][] getSpiroDescriptors(String text) {
if (text.indexOf("-")==5){
text= text.substring(7, text.length()-1);//cut off spiro-[ and terminal ]
}
else{
text= text.substring(6, text.length()-1);//cut off spiro[ and terminal ]
}
String[] spiroDescriptorStrings = matchCommaOrDot.split(text);
int[][] spiroDescriptors = new int[spiroDescriptorStrings.length][2]; // array of descriptors where number of elements and super string present
for (int i=0; i < spiroDescriptorStrings.length; i++) {
String[] elements = matchNonDigit.split(spiroDescriptorStrings[i]);
if (elements.length >1) {//a "superscripted" number is present
spiroDescriptors[i][0] = Integer.parseInt(elements[0]);
StringBuilder superScriptedNumber = new StringBuilder();
for (int j = 1; j < elements.length; j++){//may be more than one non digit as there are many ways of indicating superscripts
superScriptedNumber.append(elements[j]);
}
spiroDescriptors[i][1] = Integer.parseInt(superScriptedNumber.toString());
}
else {
spiroDescriptors[i][0] = Integer.parseInt(spiroDescriptorStrings[i]);
spiroDescriptors[i][1] = -1;
}
}
return spiroDescriptors;
}
/**
* Finds the the carbon atom with the given locant in the provided SMILES
* Returns the next index which is expected to correspond to the atom's ring opening/s
* @param smiles string to search in
* @param locant locant of the atom in given structure
* @return index of ring openings
* @throws ComponentGenerationException
*/
private Integer findIndexOfRingOpenings(String smiles, int locant) throws ComponentGenerationException{
int count = 0;
int pos = -1;
for (int i=0; i<smiles.length(); i++){
if (smiles.charAt(i) == 'C') {
count++;
}
if (count==locant) {
pos=i;
break;
}
}
if (pos == -1){
throw new ComponentGenerationException("Unable to find atom corresponding to number indicated by superscript in spiro descriptor");
}
pos++;
return pos;
}
/**
* Given an element corresponding to an alkane or other systematic chain and the preceding vonBaeyerBracket element:
* Generates the SMILES of the von baeyer system and assigns this to the chain Element
* Checks are done on the von baeyer multiplier and chain length
* The multiplier and vonBaeyerBracket are detached
* @param chainEl
* @param vonBaeyerBracketEl
* @throws ComponentGenerationException
*/
private void processVonBaeyerSystem(Element chainEl, Element vonBaeyerBracketEl) throws ComponentGenerationException {
String vonBaeyerBracket = StringTools.removeDashIfPresent(vonBaeyerBracketEl.getValue());
Element multiplier = OpsinTools.getPreviousSibling(vonBaeyerBracketEl);
int numberOfRings=Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR));
multiplier.detach();
int alkylChainLength;
Deque<String> elementSymbolArray = new ArrayDeque<String>();
String smiles =chainEl.getAttributeValue(VALUE_ATR);
char[] smilesArray =smiles.toCharArray();
for (int i = 0; i < smilesArray.length; i++) {//only able to interpret the SMILES that should be in an unmodified unbranched chain
char currentChar =smilesArray[i];
if (currentChar == '['){
if ( smilesArray[i +2]==']'){
elementSymbolArray.add("[" +String.valueOf(smilesArray[i+1]) +"]");
i=i+2;
}
else{
elementSymbolArray.add("[" + String.valueOf(smilesArray[i+1]) +String.valueOf(smilesArray[i+2]) +"]");
i=i+3;
}
}
else{
elementSymbolArray.add(String.valueOf(currentChar));
}
}
alkylChainLength=elementSymbolArray.size();
int totalLengthOfBridges=0;
int bridgeLabelsUsed=3;//start labelling from 3 upwards
//3 and 4 will be the atoms on each end of one secondary bridge, 5 and 6 for the next etc.
List<HashMap<String, Integer>> bridges = new ArrayList<HashMap<String, Integer>>();
Map<Integer, ArrayList<Integer>> bridgeLocations = new HashMap<Integer, ArrayList<Integer>>(alkylChainLength);
if (vonBaeyerBracket.indexOf("-")==5){
vonBaeyerBracket = vonBaeyerBracket.substring(7, vonBaeyerBracket.length()-1);//cut off cyclo-[ and terminal ]
}
else{
vonBaeyerBracket = vonBaeyerBracket.substring(6, vonBaeyerBracket.length()-1);//cut off cyclo[ and terminal ]
}
String[] bridgeDescriptors = matchCommaOrDot.split(vonBaeyerBracket);//the bridgelengths and positions for secondary bridges
//all bridges from past the first 3 are secondary bridges and require specification of bridge position which will be partially in the subsequent position in the array
for (int i = 0; i < bridgeDescriptors.length; i++) {
String bridgeDescriptor = bridgeDescriptors[i];
HashMap<String, Integer> bridge = new HashMap<String, Integer>();
int bridgeLength =0;
if (i > 2){//this is a secondary bridge (chain start/end locations should have been specified)
i++;
String coordinatesStr1;
String coordinatesStr2 = matchNonDigit.matcher(bridgeDescriptors[i]).replaceAll("");
String[] tempArray = matchNonDigit.split(bridgeDescriptor);
if (tempArray.length ==1){
//there is some ambiguity as it has not been made obvious which number/s are supposed to be the superscripted locant
//so we assume that it is more likely that it will be referring to an atom of label >10
//rather than a secondary bridge of length > 10
char[] tempCharArray = bridgeDescriptor.toCharArray();
if (tempCharArray.length ==2){
bridgeLength= Character.getNumericValue(tempCharArray[0]);
coordinatesStr1= Character.toString(tempCharArray[1]);
}
else if (tempCharArray.length ==3){
bridgeLength= Character.getNumericValue(tempCharArray[0]);
coordinatesStr1=Character.toString(tempCharArray[1]) +Character.toString(tempCharArray[2]);
}
else if (tempCharArray.length ==4){
bridgeLength = Integer.parseInt(Character.toString(tempCharArray[0]) +Character.toString(tempCharArray[1]));
coordinatesStr1 = Character.toString(tempCharArray[2]) +Character.toString(tempCharArray[3]);
}
else{
throw new ComponentGenerationException("Unsupported Von Baeyer locant description: " + bridgeDescriptor );
}
}
else{//bracket or other delimiter detected, no ambiguity!
bridgeLength= Integer.parseInt(tempArray[0]);
coordinatesStr1= tempArray[1];
}
bridge.put("Bridge Length", bridgeLength );
int coordinates1=Integer.parseInt(coordinatesStr1);
int coordinates2=Integer.parseInt(coordinatesStr2);
if (coordinates1 > alkylChainLength || coordinates2 > alkylChainLength){
throw new ComponentGenerationException("Indicated bridge position is not on chain: " +coordinates1 +"," +coordinates2);
}
if (coordinates2>coordinates1){//makes sure that bridges are built from highest coord to lowest
int swap =coordinates1;
coordinates1=coordinates2;
coordinates2=swap;
}
if (bridgeLocations.get(coordinates1)==null){
bridgeLocations.put(coordinates1, new ArrayList<Integer>());
}
if (bridgeLocations.get(coordinates2)==null){
bridgeLocations.put(coordinates2, new ArrayList<Integer>());
}
bridgeLocations.get(coordinates1).add(bridgeLabelsUsed);
bridge.put("AtomId_Larger_Label", bridgeLabelsUsed);
bridgeLabelsUsed++;
if (bridgeLength==0){//0 length bridge, hence want atoms with the same labels so they can join together without a bridge
bridgeLocations.get(coordinates2).add(bridgeLabelsUsed -1);
bridge.put("AtomId_Smaller_Label", bridgeLabelsUsed -1);
}
else{
bridgeLocations.get(coordinates2).add(bridgeLabelsUsed);
bridge.put("AtomId_Smaller_Label", bridgeLabelsUsed);
}
bridgeLabelsUsed++;
bridge.put("AtomId_Larger", coordinates1);
bridge.put("AtomId_Smaller", coordinates2);
}
else{
bridgeLength= Integer.parseInt(bridgeDescriptor);
bridge.put("Bridge Length", bridgeLength);
}
totalLengthOfBridges += bridgeLength;
bridges.add(bridge);
}
if (totalLengthOfBridges + 2 !=alkylChainLength ){
throw new ComponentGenerationException("Disagreement between lengths of bridges and alkyl chain length");
}
if (numberOfRings +1 != bridges.size()){
throw new ComponentGenerationException("Disagreement between number of rings and number of bridges");
}
StringBuilder smilesSB = new StringBuilder();
int atomCounter=1;
int bridgeCounter=1;
//add standard bridges
for (HashMap<String, Integer> bridge : bridges) {
if (bridgeCounter==1){
smilesSB.append(elementSymbolArray.removeFirst());
smilesSB.append("1");
if (bridgeLocations.get(atomCounter)!=null){
for (Integer bridgeAtomLabel : bridgeLocations.get(atomCounter)) {
smilesSB.append(ringClosure(bridgeAtomLabel));
}
}
smilesSB.append("(");
}
int bridgeLength =bridge.get("Bridge Length");
for (int i = 0; i < bridgeLength; i++) {
atomCounter++;
smilesSB.append(elementSymbolArray.removeFirst());
if (bridgeLocations.get(atomCounter)!=null){
for (Integer bridgeAtomLabel : bridgeLocations.get(atomCounter)) {
smilesSB.append(ringClosure(bridgeAtomLabel));
}
}
}
if (bridgeCounter==1){
atomCounter++;
smilesSB.append(elementSymbolArray.removeFirst());
smilesSB.append("2");
if (bridgeLocations.get(atomCounter)!=null){
for (Integer bridgeAtomLabel : bridgeLocations.get(atomCounter)) {
smilesSB.append(ringClosure(bridgeAtomLabel));
}
}
}
if (bridgeCounter==2){
smilesSB.append("1)");
}
if (bridgeCounter==3){
smilesSB.append("2");
}
bridgeCounter++;
if (bridgeCounter >3){break;}
}
//create list of secondary bridges that need to be added
//0 length bridges and the 3 main bridges are dropped
List<HashMap<String, Integer>> secondaryBridges = new ArrayList<HashMap<String, Integer>>();
for (HashMap<String, Integer> bridge : bridges) {
if(bridge.get("AtomId_Larger")!=null && bridge.get("Bridge Length")!=0){
secondaryBridges.add(bridge);
}
}
Comparator<HashMap<String, Integer>> sortBridges= new VonBaeyerSecondaryBridgeSort();
Collections.sort(secondaryBridges, sortBridges);
List<HashMap<String, Integer>> dependantSecondaryBridges;
//add secondary bridges, recursively add dependent secondary bridges
do{
dependantSecondaryBridges = new ArrayList<HashMap<String, Integer>>();
for (HashMap<String, Integer> bridge : secondaryBridges) {
int bridgeLength =bridge.get("Bridge Length");
if (bridge.get("AtomId_Larger") > atomCounter){
dependantSecondaryBridges.add(bridge);
continue;
}
smilesSB.append(".");
for (int i = 0; i < bridgeLength; i++) {
atomCounter++;
smilesSB.append(elementSymbolArray.removeFirst());
if (i==0){
smilesSB.append(ringClosure(bridge.get("AtomId_Larger_Label")));
}
if (bridgeLocations.get(atomCounter)!=null){
for (Integer bridgeAtomLabel : bridgeLocations.get(atomCounter)) {
smilesSB.append(ringClosure(bridgeAtomLabel));
}
}
}
smilesSB.append(ringClosure(bridge.get("AtomId_Smaller_Label")));
}
if (dependantSecondaryBridges.size() >0 && dependantSecondaryBridges.size()==secondaryBridges.size()){
throw new ComponentGenerationException("Unable to resolve all dependant bridges!!!");
}
secondaryBridges=dependantSecondaryBridges;
}
while(dependantSecondaryBridges.size() > 0);
chainEl.getAttribute(VALUE_ATR).setValue(smilesSB.toString());
chainEl.getAttribute(TYPE_ATR).setValue(RING_TYPE_VAL);
if (chainEl.getAttribute(USABLEASJOINER_ATR) !=null){
chainEl.removeAttribute(chainEl.getAttribute(USABLEASJOINER_ATR));
}
vonBaeyerBracketEl.detach();
}
/**
* Converts a chain group into a ring.
* The chain group can either be an alkane or heteroatom chain
* @param chainGroup
* @param cycloEl
* @throws ComponentGenerationException
*/
private void processCyclisedChain(Element chainGroup, Element cycloEl) throws ComponentGenerationException {
String smiles=chainGroup.getAttributeValue(VALUE_ATR);
int chainlen =0;
for (int i = smiles.length() -1 ; i >=0; i--) {
if (Character.isUpperCase(smiles.charAt(i)) && smiles.charAt(i) !='H'){
chainlen++;
}
}
if (chainlen < 3){
throw new ComponentGenerationException("Heteroatom chain too small to create a ring: " + chainlen);
}
smiles+="1";
if (smiles.charAt(0)=='['){
int closeBracketIndex = smiles.indexOf(']');
smiles= smiles.substring(0, closeBracketIndex +1) +"1" + smiles.substring(closeBracketIndex +1);
}
else{
if (Character.getType(smiles.charAt(1)) == Character.LOWERCASE_LETTER){//element is 2 letters long
smiles= smiles.substring(0,2) +"1" + smiles.substring(2);
}
else{
smiles= smiles.substring(0,1) +"1" + smiles.substring(1);
}
}
chainGroup.getAttribute(VALUE_ATR).setValue(smiles);
if (chainlen==6){//6 membered rings have ortho/meta/para positions
if (chainGroup.getAttribute(LABELS_ATR)!=null){
chainGroup.getAttribute(LABELS_ATR).setValue("1/2,ortho/3,meta/4,para/5/6");
}
else{
chainGroup.addAttribute(new Attribute(LABELS_ATR, "1/2,ortho/3,meta/4,para/5/6"));
}
}
chainGroup.getAttribute(TYPE_ATR).setValue(RING_TYPE_VAL);
if (chainGroup.getAttribute(USABLEASJOINER_ATR) !=null){
chainGroup.removeAttribute(chainGroup.getAttribute(USABLEASJOINER_ATR));
}
cycloEl.detach();
}
/**Handles special cases in IUPAC nomenclature.
* Benzyl etc.
* @param group The group to look for irregularities in.
* @throws ComponentGenerationException
*/
private void handleGroupIrregularities(Element group) throws ComponentGenerationException {
String groupValue =group.getValue();
if (!n2sConfig.allowInterpretationOfAcidsWithoutTheWordAcid()) {
if (group.getAttribute(FUNCTIONALIDS_ATR) !=null && (groupValue.endsWith("ic") || groupValue.endsWith("ous"))){
Element next = OpsinTools.getNext(group);
if (next == null){
throw new ComponentGenerationException("\"acid\" not found after " +groupValue);
}
}
}
String groupType = group.getAttributeValue(TYPE_ATR);
String groupSubType = group.getAttributeValue(SUBTYPE_ATR);
if (OUSICATOM_SUBTYPE_VAL.equals(groupSubType)) {
Element next = OpsinTools.getNext(group, false);
if (next == null){
throw new ComponentGenerationException("counter anion not found after " +groupValue);
}
}
if(groupValue.equals("thiophen") || groupValue.equals("selenophen") || groupValue.equals("tellurophen")) {//thiophenol is generally phenol with an O replaced with S not thiophene with a hydroxy
Element possibleSuffix = OpsinTools.getNextSibling(group);
if (!"e".equals(group.getAttributeValue(SUBSEQUENTUNSEMANTICTOKEN_ATR)) && possibleSuffix !=null && possibleSuffix.getName().equals(SUFFIX_EL)) {
if (possibleSuffix.getValue().startsWith("ol")){
Element isThisALocant = OpsinTools.getPreviousSibling(group);
if (isThisALocant == null || !isThisALocant.getName().equals(LOCANT_EL) || isThisALocant.getValue().split(",").length != 1){
throw new ComponentGenerationException(groupValue + "ol has been incorrectly interpreted as "+ groupValue+", ol instead of phenol with the oxgen replaced");
}
}
}
}
else if(groupValue.equals("chromen")) {//chromene in IUPAC nomenclature is fully unsaturated, but sometimes is instead considered to be chromane with a front locanted double bond
Element possibleLocant = OpsinTools.getPreviousSibling(group);
if (possibleLocant != null && possibleLocant.getName().equals(LOCANT_EL) &&
(possibleLocant.getValue().equals("2") || possibleLocant.getValue().equals("3"))) {
Element possibleSuffix = OpsinTools.getNextSibling(group);
if (possibleSuffix == null || possibleSuffix.getName().equals(LOCANT_EL)){//if there is a suffix assume the locant refers to that rather than the double bond
group.getAttribute(VALUE_ATR).setValue("O1CCCc2ccccc12");
group.addAttribute(ADDBOND_ATR, "2 locant required");
group.addAttribute(FRONTLOCANTSEXPECTED_ATR, "2,3");
}
}
}
else if (groupValue.equals("methylene") || groupValue.equals("methylen")) {//e.g. 3,4-methylenedioxyphenyl
Element nextSub = OpsinTools.getNextSibling(group.getParent());
if (nextSub !=null && nextSub.getName().equals(SUBSTITUENT_EL) && OpsinTools.getNextSibling(group)==null
&& (OpsinTools.getPreviousSibling(group)==null || !OpsinTools.getPreviousSibling(group).getName().equals(MULTIPLIER_EL))){//not trimethylenedioxy
List<Element> children = nextSub.getChildElements();
if (children.size() >=2 && children.get(0).getValue().equals("di")&& children.get(1).getValue().equals("oxy")){
group.setValue(groupValue + "dioxy");
group.getAttribute(VALUE_ATR).setValue("C(O)O");
group.getAttribute(OUTIDS_ATR).setValue("2,3");
group.getAttribute(SUBTYPE_ATR).setValue(EPOXYLIKE_SUBTYPE_VAL);
if (group.getAttribute(LABELS_ATR)!=null){
group.getAttribute(LABELS_ATR).setValue(NONE_LABELS_VAL);
}
else{
group.addAttribute(new Attribute(LABELS_ATR, NONE_SUBTYPE_VAL));
}
nextSub.detach();
for (int i = children.size() -1 ; i >=2; i--) {
children.get(i).detach();
OpsinTools.insertAfter(group, children.get(i));
}
}
}
}
else if (groupValue.equals("ethylene") || groupValue.equals("ethylen")) {
Element previous = OpsinTools.getPreviousSibling(group);
if (previous != null && previous.getName().equals(MULTIPLIER_EL)){
int multiplierValue = Integer.parseInt(previous.getAttributeValue(VALUE_ATR));
Element possibleRoot = OpsinTools.getNextSibling(group.getParent());
if (possibleRoot==null && OpsinTools.getParentWordRule(group).getAttributeValue(WORDRULE_ATR).equals(WordRule.glycol.toString())){//e.g. dodecaethylene glycol
StringBuilder smiles = new StringBuilder("CC");
for (int i = 1; i < multiplierValue; i++) {
smiles.append("OCC");
}
group.getAttribute(OUTIDS_ATR).setValue("1," +Integer.toString(3*(multiplierValue-1) +2));
group.getAttribute(VALUE_ATR).setValue(smiles.toString());
previous.detach();
if (group.getAttribute(LABELS_ATR)!=null){//use numeric numbering
group.getAttribute(LABELS_ATR).setValue(NUMERIC_LABELS_VAL);
}
else{
group.addAttribute(new Attribute(LABELS_ATR, NUMERIC_LABELS_VAL));
}
}
else if (possibleRoot!=null && possibleRoot.getName().equals(ROOT_EL)){
List<Element> children = possibleRoot.getChildElements();
if (children.size()==2){
Element amineMultiplier =children.get(0);
Element amine =children.get(1);
if (amineMultiplier.getName().equals(MULTIPLIER_EL) && (amine.getValue().equals("amine") || amine.getValue().equals("amin"))){//e.g. Triethylenetetramine
if (Integer.parseInt(amineMultiplier.getAttributeValue(VALUE_ATR))!=multiplierValue +1){
throw new ComponentGenerationException("Invalid polyethylene amine!");
}
StringBuilder smiles = new StringBuilder();
for (int i = 0; i < multiplierValue; i++) {
smiles.append("NCC");
}
smiles.append("N");
group.removeAttribute(group.getAttribute(OUTIDS_ATR));
group.getAttribute(VALUE_ATR).setValue(smiles.toString());
previous.detach();
possibleRoot.detach();
group.getParent().setName(ROOT_EL);
if (group.getAttribute(LABELS_ATR)!=null){//use numeric numbering
group.getAttribute(LABELS_ATR).setValue(NUMERIC_LABELS_VAL);
}
else{
group.addAttribute(new Attribute(LABELS_ATR, NUMERIC_LABELS_VAL));
}
}
}
}
}
else{
Element nextSub = OpsinTools.getNextSibling(group.getParent());
if (nextSub !=null && nextSub.getName().equals(SUBSTITUENT_EL) && OpsinTools.getNextSibling(group)==null){
List<Element> children = nextSub.getChildElements();
if (children.size() >=2 && children.get(0).getValue().equals("di")&& children.get(1).getValue().equals("oxy")){
group.setValue(groupValue + "dioxy");
group.getAttribute(VALUE_ATR).setValue("C(O)CO");
group.getAttribute(OUTIDS_ATR).setValue("2,4");
group.getAttribute(SUBTYPE_ATR).setValue(EPOXYLIKE_SUBTYPE_VAL);
if (group.getAttribute(LABELS_ATR)!=null){
group.getAttribute(LABELS_ATR).setValue(NONE_LABELS_VAL);
}
else{
group.addAttribute(new Attribute(LABELS_ATR, NONE_SUBTYPE_VAL));
}
nextSub.detach();
for (int i = children.size() -1 ; i >=2; i--) {
children.get(i).detach();
OpsinTools.insertAfter(group, children.get(i));
}
}
}
}
}
else if (groupValue.equals("propylene") || groupValue.equals("propylen")) {
Element previous = OpsinTools.getPreviousSibling(group);
if (previous!=null && previous.getName().equals(MULTIPLIER_EL)){
int multiplierValue = Integer.parseInt(previous.getAttributeValue(VALUE_ATR));
Element possibleRoot = OpsinTools.getNextSibling(group.getParent());
if (possibleRoot==null && OpsinTools.getParentWordRule(group).getAttributeValue(WORDRULE_ATR).equals(WordRule.glycol.toString())){//e.g. dodecaethylene glycol
StringBuilder smiles =new StringBuilder("CCC");
for (int i = 1; i < multiplierValue; i++) {
smiles.append("OC(C)C");
}
group.getAttribute(OUTIDS_ATR).setValue("2," +Integer.toString(4*(multiplierValue-1) +3));
group.getAttribute(VALUE_ATR).setValue(smiles.toString());
if (group.getAttribute(LABELS_ATR)!=null){
group.getAttribute(LABELS_ATR).setValue(NONE_LABELS_VAL);
}
else{
group.addAttribute(new Attribute(LABELS_ATR, NONE_LABELS_VAL));
}
previous.detach();
}
}
}
//acridone (not codified), anthrone, phenanthrone and xanthone have the one at position 9 by default
else if (groupValue.equals("anthr")|| groupValue.equals("anthran") || groupValue.equals("phenanthr") || groupValue.equals("acrid") ||
groupValue.equals("xanth") || groupValue.equals("thioxanth") || groupValue.equals("selenoxanth")|| groupValue.equals("telluroxanth")|| groupValue.equals("xanthen")) {
Element possibleLocant = OpsinTools.getPreviousSibling(group);
if (possibleLocant==null || !possibleLocant.getName().equals(LOCANT_EL)){//only need to give one a locant of 9 if no locant currently present
Element possibleSuffix = OpsinTools.getNextSibling(group);
if (possibleSuffix!=null && "one".equals(possibleSuffix.getAttributeValue(VALUE_ATR))){
//Rule C-315.2
Element newLocant =new TokenEl(LOCANT_EL, "9");
OpsinTools.insertBefore(possibleSuffix, newLocant);
Element newAddedHydrogen = new TokenEl(ADDEDHYDROGEN_EL);
newAddedHydrogen.addAttribute(new Attribute(LOCANT_ATR, "10"));
OpsinTools.insertBefore(newLocant, newAddedHydrogen);
}
else if (possibleSuffix!=null && possibleSuffix.getName().equals(SUFFIX_EL) &&
groupValue.equals("xanth") || groupValue.equals("thioxanth") || groupValue.equals("selenoxanth")|| groupValue.equals("telluroxanth")){
//diasambiguate between xanthate/xanthic acid and xanthene
String suffixVal = possibleSuffix.getAttributeValue(VALUE_ATR);
if (suffixVal.equals("ic") || suffixVal.equals("ate")){
throw new ComponentGenerationException(groupValue + possibleSuffix.getValue() +" is not a derivative of xanthene");
}
}
}
}
else if (groupValue.equals("phospho")){//is this the organic meaning (P(=O)=O) or biochemical meaning (P(=O)(O)O)
Element wordRule = OpsinTools.getParentWordRule(group);
for (Element otherGroup : OpsinTools.getDescendantElementsWithTagName(wordRule, GROUP_EL)) {
String type = otherGroup.getAttributeValue(TYPE_ATR);
String subType = otherGroup.getAttributeValue(SUBTYPE_ATR);
if (OpsinTools.isBiochemical(type, subType) ||
(YLFORACYL_SUBTYPE_VAL.equals(subType) &&
("glycol".equals(otherGroup.getValue()) || "diglycol".equals(otherGroup.getValue()))
)
) {
group.getAttribute(VALUE_ATR).setValue("-P(=O)(O)O");
group.addAttribute(new Attribute(USABLEASJOINER_ATR, "yes"));
break;
}
}
}
else if (groupValue.equals("hydrogen")){
Element hydrogenParentEl = group.getParent();
Element nextSubOrRoot = OpsinTools.getNextSibling(hydrogenParentEl);
if (nextSubOrRoot!=null){
Element possibleSuitableAteGroup = nextSubOrRoot.getChild(0);
if (!possibleSuitableAteGroup.getName().equals(GROUP_EL) || !NONCARBOXYLICACID_TYPE_VAL.equals(possibleSuitableAteGroup.getAttributeValue(TYPE_ATR))){
throw new ComponentGenerationException("Hydrogen is not meant as a substituent in this context!");
}
Element possibleMultiplier = OpsinTools.getPreviousSibling(group);
String multiplier = "1";
if (possibleMultiplier!=null && possibleMultiplier.getName().equals(MULTIPLIER_EL)){
multiplier = possibleMultiplier.getAttributeValue(VALUE_ATR);
possibleMultiplier.detach();
}
possibleSuitableAteGroup.addAttribute(new Attribute(NUMBEROFFUNCTIONALATOMSTOREMOVE_ATR, multiplier));
group.detach();
List<Element> childrenToMove = hydrogenParentEl.getChildElements();
for (int i = childrenToMove.size() -1 ; i >=0; i--) {
childrenToMove.get(i).detach();
nextSubOrRoot.insertChild(childrenToMove.get(i), 0);
}
hydrogenParentEl.detach();
}
}
else if (groupValue.equals("acryl")){
if (SIMPLESUBSTITUENT_SUBTYPE_VAL.equals(groupSubType)){
Element nextEl = OpsinTools.getNext(group);
if (nextEl!=null && nextEl.getValue().equals("amid")){
throw new ComponentGenerationException("amide in acrylamide is not [NH2-]");
}
}
}
else if (groupValue.equals("azo") || groupValue.equals("azoxy") || groupValue.equals("nno-azoxy") || groupValue.equals("non-azoxy") || groupValue.equals("onn-azoxy") || groupValue.equals("diazoamino") || groupValue.equals("hydrazo") ){
Element enclosingSub = group.getParent();
Element next = OpsinTools.getNextSiblingIgnoringCertainElements(enclosingSub, new String[]{HYPHEN_EL});
if (next==null && OpsinTools.getPreviousSibling(enclosingSub) == null){//e.g. [(E)-NNO-azoxy]benzene
next = OpsinTools.getNextSiblingIgnoringCertainElements(enclosingSub.getParent(), new String[]{HYPHEN_EL});
}
if (next!=null && next.getName().equals(ROOT_EL)){
if (!(next.getChild(0).getName().equals(MULTIPLIER_EL))){
List<Element> suffixes = next.getChildElements(SUFFIX_EL);
if (suffixes.size()==0){//only case without locants is handled so far. suffixes only apply to one of the fragments rather than both!!!
Element newMultiplier = new TokenEl(MULTIPLIER_EL);
newMultiplier.addAttribute(new Attribute(VALUE_ATR, "2"));
next.insertChild(newMultiplier, 0);
Element interSubstituentHyphen = OpsinTools.getPrevious(group);
if (interSubstituentHyphen!=null && !interSubstituentHyphen.getName().equals(HYPHEN_EL)){//prevent implicit bracketting
OpsinTools.insertAfter(interSubstituentHyphen, new TokenEl(HYPHEN_EL));
}
}
}
}
}
else if (groupValue.equals("coenzyme a") || groupValue.equals("coa")){
Element enclosingSubOrRoot = group.getParent();
Element previous = OpsinTools.getPreviousSibling(enclosingSubOrRoot);
if (previous != null){
List<Element> groups = OpsinTools.getDescendantElementsWithTagName(previous, GROUP_EL);
if (groups.size() > 0){
Element possibleAcid = groups.get(groups.size() - 1);
if (ACIDSTEM_TYPE_VAL.equals(possibleAcid.getAttributeValue(TYPE_ATR))){
if (possibleAcid.getAttribute(SUFFIXAPPLIESTO_ATR) != null && possibleAcid.getAttributeValue(SUFFIXAPPLIESTO_ATR).split(",").length > 1){//multi acid. yl should be one oyl and the rest carboxylic acids
Element suffix = OpsinTools.getNextSibling(possibleAcid, SUFFIX_EL);
if (suffix.getAttribute(ADDITIONALVALUE_ATR) == null){
suffix.addAttribute(new Attribute(ADDITIONALVALUE_ATR, "ic"));
}
}
String subType = possibleAcid.getAttributeValue(SUBTYPE_ATR);
if (subType.equals(YLFORYL_SUBTYPE_VAL) || subType.equals(YLFORNOTHING_SUBTYPE_VAL)){
possibleAcid.getAttribute(SUBTYPE_ATR).setValue(YLFORACYL_SUBTYPE_VAL);//yl always means an acyl when next to coenzyme A
}
}
}
}
//locanted substitution onto Coenzyme A is rarely intended, so put prior content into a bracket to disfavour it
Element enclosingBracketOrWord = enclosingSubOrRoot.getParent();
int indexOfCoa = enclosingBracketOrWord.indexOf(enclosingSubOrRoot);
if (indexOfCoa > 0) {
Element newBracket = new GroupingEl(BRACKET_EL);
List<Element> precedingElements = enclosingBracketOrWord.getChildElements();
for (int i = 0; i < indexOfCoa; i++) {
Element precedingElement = precedingElements.get(i);
precedingElement.detach();
newBracket.addChild(precedingElement);
}
OpsinTools.insertBefore(enclosingSubOrRoot, newBracket);
}
}
else if (groupValue.equals("sphinganine") || groupValue.equals("icosasphinganine") || groupValue.equals("eicosasphinganine") || groupValue.equals("phytosphingosine") || groupValue.equals("sphingosine")
|| groupValue.equals("sphinganin") || groupValue.equals("icosasphinganin") || groupValue.equals("eicosasphinganin") || groupValue.equals("phytosphingosin") || groupValue.equals("sphingosin")){
Element enclosingSubOrRoot = group.getParent();
Element previous = OpsinTools.getPreviousSibling(enclosingSubOrRoot);
if (previous!=null){
List<Element> groups = OpsinTools.getDescendantElementsWithTagName(previous, GROUP_EL);
if (groups.size()>0){
Element possibleAcid = groups.get(groups.size()-1);
if (ALKANESTEM_SUBTYPE_VAL.equals(possibleAcid.getAttributeValue(SUBTYPE_ATR))){
List<Element> inlineSuffixes = OpsinTools.getChildElementsWithTagNameAndAttribute(possibleAcid.getParent(), SUFFIX_EL, TYPE_ATR, INLINE_TYPE_VAL);
if (inlineSuffixes.size()==1 && inlineSuffixes.get(0).getAttributeValue(VALUE_ATR).equals("yl")){
inlineSuffixes.get(0).getAttribute(VALUE_ATR).setValue("oyl");//yl on a systematic acid next to a fatty acid means acyl
//c.f. Nomenclature of Lipids 1976, Appendix A, note a
}
}
}
}
}
else if (groupValue.equals("sel")){
//check that it is not "selenium"
if (HETEROSTEM_SUBTYPE_VAL.equals(groupSubType) && group.getAttribute(SUBSEQUENTUNSEMANTICTOKEN_ATR) ==null){
Element unsaturator = OpsinTools.getNextSibling(group);
if (unsaturator !=null && unsaturator.getName().equals(UNSATURATOR_EL) && unsaturator.getValue().equals("en") && group.getAttribute(SUBSEQUENTUNSEMANTICTOKEN_ATR) ==null){
Element ium = OpsinTools.getNextSibling(unsaturator);
if (ium !=null && ium.getName().equals(SUFFIX_EL) && ium.getValue().equals("ium")){
throw new ComponentGenerationException("<multiplier>selenium does not indicate a chain of selenium atoms with a double bond and a positive charge");
}
}
}
}
else if ((groupValue.equals("keto") || groupValue.equals("aldehydo")) && SIMPLESUBSTITUENT_SUBTYPE_VAL.equals(groupSubType)){
//check for case where this is specifying the open chain form of a ketose/aldose
Element previousEl = OpsinTools.getPreviousSibling(group);
if (previousEl ==null || !previousEl.getName().equals(LOCANT_EL) || groupValue.equals("aldehydo")){
Element parentSubstituent = group.getParent();
Element nextSubOrRoot = OpsinTools.getNextSibling(parentSubstituent);
Element parentOfCarbohydate = nextSubOrRoot;
Element carbohydrate = null;
while (parentOfCarbohydate != null){
Element possibleCarbohydrate = parentOfCarbohydate.getFirstChildElement(GROUP_EL);
if (possibleCarbohydrate !=null && possibleCarbohydrate.getAttributeValue(TYPE_ATR).equals(CARBOHYDRATE_TYPE_VAL)){
carbohydrate = possibleCarbohydrate;
break;
}
parentOfCarbohydate = OpsinTools.getNextSibling(parentOfCarbohydate);
}
if (carbohydrate != null) {
if (parentOfCarbohydate.getChildElements(CARBOHYDRATERINGSIZE_EL).size() > 0){
throw new ComponentGenerationException("Carbohydrate has a specified ring size but " + groupValue + " indicates the open chain form!");
}
for (Element suffix : parentOfCarbohydate.getChildElements(SUFFIX_EL)) {
if ("yl".equals(suffix.getAttributeValue(VALUE_ATR))) {
throw new ComponentGenerationException("Carbohydrate appears to be a glycosyl, but " + groupValue + " indicates the open chain form!");
}
}
Element alphaOrBetaLocantEl = OpsinTools.getPreviousSiblingIgnoringCertainElements(carbohydrate, new String[]{STEREOCHEMISTRY_EL});
if (alphaOrBetaLocantEl != null && alphaOrBetaLocantEl.getName().equals(LOCANT_EL) ){
String value = alphaOrBetaLocantEl.getValue();
if (value.equals("alpha") || value.equals("beta") || value.equals("alpha,beta") || value.equals("beta,alpha")){
throw new ComponentGenerationException("Carbohydrate has alpha/beta anomeric form but " + groupValue + " indicates the open chain form!");
}
}
group.detach();
List<Element> childrenToMove = parentSubstituent.getChildElements();
for (int i = childrenToMove.size() -1 ; i >=0; i--) {
Element el = childrenToMove.get(i);
if (!el.getName().equals(HYPHEN_EL)){
el.detach();
nextSubOrRoot.insertChild(el, 0);
}
}
parentSubstituent.detach();
if (RING_SUBTYPE_VAL.equals(carbohydrate.getAttributeValue(SUBTYPE_ATR))) {
String carbohydrateAdditionValue = carbohydrate.getAttributeValue(ADDITIONALVALUE_ATR);
//OPSIN assumes a few trivial names are more likely to describe the cyclic form. additionalValue contains the SMILES for the acyclic form
if (carbohydrateAdditionValue == null){
throw new ComponentGenerationException(carbohydrate.getValue() + " can only describe the cyclic form but " + groupValue + " indicates the open chain form!");
}
carbohydrate.getAttribute(VALUE_ATR).setValue(carbohydrateAdditionValue);
}
}
else if (groupValue.equals("aldehydo")){
throw new ComponentGenerationException("aldehydo is only a valid prefix when it precedes a carbohydrate!");
}
}
}
else if (groupValue.equals("bor") || groupValue.equals("antimon")
|| groupValue.equals("arsen") || groupValue.equals("phosphor") || groupValue.equals("phosphate") || groupValue.equals("phosphat")
|| groupValue.equals("silicicacid") || groupValue.equals("silicic acid")
|| groupValue.equals("silicate") || groupValue.equals("silicat")){//fluoroboric acid/fluoroborate are trivial rather than systematic; tetra(fooyl)borate is inorganic
Element suffix = null;
Boolean isAcid = null;
if (groupValue.endsWith("acid")){
if (OpsinTools.getNext(group) == null){
isAcid = true;
}
}
else if (groupValue.endsWith("ate") || groupValue.endsWith("at")){
if (OpsinTools.getNext(group) == null){
isAcid = false;
}
}
else{
suffix = OpsinTools.getNextSibling(group);
if (suffix != null && suffix.getName().equals(SUFFIX_EL) &&
suffix.getAttribute(INFIX_ATR) == null && OpsinTools.getNext(suffix) == null){
String suffixValue = suffix.getAttributeValue(VALUE_ATR);
if (suffixValue.equals("ic")){
isAcid = true;
}
else if (suffixValue.equals("ate")){
isAcid = false;
}
}
}
if (isAcid != null){//check for inorganic interpretation
Element substituent = OpsinTools.getPreviousSibling(group.getParent());
if (substituent !=null && (substituent.getName().equals(SUBSTITUENT_EL) || substituent.getName().equals(BRACKET_EL))){
List<Element> children = substituent.getChildElements();
Element firstChild = children.get(0);
boolean matched = false;
if (children.size() ==1 && firstChild.getName().equals(GROUP_EL) && (firstChild.getValue().equals("fluoro") || firstChild.getValue().equals("fluor"))){
if (groupValue.equals("bor")) {
group.getAttribute(VALUE_ATR).setValue(isAcid ? "F[B-](F)(F)F.[H+]" : "F[B-](F)(F)F");
matched = true;
}
else if (groupValue.equals("antimon")) {
group.getAttribute(VALUE_ATR).setValue(isAcid ? "F[Sb-](F)(F)(F)(F)F.[H+]" : "F[Sb-](F)(F)(F)(F)F");
matched = true;
}
else if (groupValue.startsWith("silicic") || groupValue.startsWith("silicat")) {
group.getAttribute(VALUE_ATR).setValue(isAcid ? "F[Si|6-2](F)(F)(F)(F)F.[H+].[H+]" : "F[Si|6-2](F)(F)(F)(F)F");
matched = true;
}
if (matched) {
substituent.detach();
}
}
else if (firstChild.getName().equals(MULTIPLIER_EL)) {
String multiplierVal = firstChild.getAttributeValue(VALUE_ATR);
if (groupValue.equals("bor")){
if (multiplierVal.equals("4") || (multiplierVal.equals("3") && OpsinTools.getPreviousSibling(substituent) != null)) {
//tri case allows organotrifluoroborates
group.getAttribute(VALUE_ATR).setValue(isAcid ? "[B-].[H+]" :"[B-]");
matched = true;
}
}
else if (groupValue.equals("antimon") && multiplierVal.equals("6")) {
group.getAttribute(VALUE_ATR).setValue(isAcid ? "[Sb-].[H+]" :"[Sb-]");
matched = true;
}
else if (groupValue.equals("arsen") && multiplierVal.equals("6")) {
group.getAttribute(VALUE_ATR).setValue(isAcid ? "[As-].[H+]" :"[As-]");
matched = true;
}
else if (groupValue.startsWith("phosph") && multiplierVal.equals("6")) {
group.getAttribute(VALUE_ATR).setValue(isAcid ? "[P-].[H+]" :"[P-]");
matched = true;
}
else if (groupValue.startsWith("silic") && multiplierVal.equals("6")) {
group.getAttribute(VALUE_ATR).setValue(isAcid ? "[Si|6-2].[H+].[H+]" :"[Si|6-2]");
matched = true;
}
}
if (matched) {
group.getAttribute(TYPE_ATR).setValue(SIMPLEGROUP_TYPE_VAL);
group.getAttribute(SUBTYPE_ATR).setValue(SIMPLEGROUP_SUBTYPE_VAL);
Attribute usableAsJoiner = group.getAttribute(USABLEASJOINER_ATR);
if (usableAsJoiner != null){
group.removeAttribute(usableAsJoiner);
}
Attribute acceptsAdditiveBonds = group.getAttribute(ACCEPTSADDITIVEBONDS_ATR);
if (acceptsAdditiveBonds != null){
group.removeAttribute(acceptsAdditiveBonds);
}
Attribute functionalIds = group.getAttribute(FUNCTIONALIDS_ATR);
if (functionalIds != null){
group.removeAttribute(functionalIds);
}
if (suffix != null){
suffix.detach();
}
}
}
}
}
else if (ENDINIC_SUBTYPE_VAL.equals(groupSubType) && AMINOACID_TYPE_VAL.equals(groupType)) {
//aspartyl and glutamyl typically mean alpha-aspartyl/alpha-glutamyl
String[] suffixAppliesTo = group.getAttributeValue(SUFFIXAPPLIESTO_ATR).split(",");
if (suffixAppliesTo.length == 2) {
Element yl = OpsinTools.getNextSibling(group);
if (yl.getAttributeValue(VALUE_ATR).equals("yl")) {
if (yl.getAttribute(ADDITIONALVALUE_ATR) == null){
yl.addAttribute(new Attribute(ADDITIONALVALUE_ATR, "ic"));
}
}
}
} else if (SALTCOMPONENT_SUBTYPE_VAL.equals(groupSubType)) {
Element parse = null;
Element tempParent = group.getParent();
while (tempParent != null) {
parse = tempParent;
tempParent = tempParent.getParent();
}
if (parse.getChildCount() <= 1) {
throw new ComponentGenerationException("Group expected to be part of a salt but only one component found. Could be a class of compound: " + groupValue);
}
if (groupValue.length() > 0) {
//e.g. 2HCl
char firstChar = groupValue.charAt(0);
if (firstChar >= '1' && firstChar <= '9') {
Element shouldntBeAmultiplier= OpsinTools.getPreviousSibling(group);
if (shouldntBeAmultiplier != null && shouldntBeAmultiplier.getName().equals(MULTIPLIER_EL)) {
throw new ComponentGenerationException("Unepxected multiplier found before: " + groupValue);
}
Element multiplier = new TokenEl(MULTIPLIER_EL, String.valueOf(firstChar));
multiplier.addAttribute(TYPE_ATR, BASIC_TYPE_VAL);
multiplier.addAttribute(VALUE_ATR, String.valueOf(firstChar));
OpsinTools.insertBefore(group, multiplier);
group.setValue(groupValue.substring(1));
}
}
} else if (ELEMENTARYATOM_TYPE_VAL.equals(groupType)) {
//simple inorganic molecular diatomics should be implicitly bonded e.g. dioxygen
Element multiplier = OpsinTools.getPreviousSibling(group);
if (multiplier != null && "2".equals(multiplier.getAttributeValue(VALUE_ATR))) {
//check that the name is just formed of two tokens e.g. dinitrogen
Element temp = group.getParent();
Element parent = temp;
while (temp != null) {
parent = temp;
temp = parent.getParent();
}
if (OpsinTools.countNumberOfElementsAndNumberOfChildLessElements(parent)[1] == 2) {
String newVal;
switch (group.getAttributeValue(VALUE_ATR)) {
case "[H]":
newVal = "[H][H]";
break;
case "[N]":
newVal = "N#N";
break;
case "[O]":
newVal = "O=O";
break;
case "[F]":
newVal = "FF";
break;
case "[Cl]":
newVal = "ClCl";
break;
case "[Br]":
newVal = "BrBr";
break;
case "[I]":
newVal = "II";
break;
default:
newVal = null;
break;
}
if (newVal != null) {
Element newGroup = new TokenEl(GROUP_EL, groupValue);
newGroup.addAttribute(TYPE_ATR, SIMPLEGROUP_TYPE_VAL);
newGroup.addAttribute(SUBTYPE_ATR, SIMPLEGROUP_SUBTYPE_VAL);
newGroup.addAttribute(VALUE_ATR, newVal);
OpsinTools.insertAfter(group, newGroup);
group.detach();
multiplier.detach();
}
}
}
}
if (AMINOACID_TYPE_VAL.equals(groupType)) {
Element previous = OpsinTools.getPreviousSibling(group.getParent());
if (previous != null) {
List<Element> groups = OpsinTools.getDescendantElementsWithTagName(previous, GROUP_EL);
if (groups.size() > 0) {
Element possibleAcid = groups.get(groups.size() - 1);
if (ACIDSTEM_TYPE_VAL.equals(possibleAcid.getAttributeValue(TYPE_ATR))) {
if (possibleAcid.getAttribute(SUFFIXAPPLIESTO_ATR) != null && possibleAcid.getAttributeValue(SUFFIXAPPLIESTO_ATR).split(",").length > 1) {//multi acid. yl should be one oyl and the rest carboxylic acids
Element suffix = OpsinTools.getNextSibling(possibleAcid, SUFFIX_EL);
if (suffix.getAttribute(ADDITIONALVALUE_ATR) == null) {
suffix.addAttribute(new Attribute(ADDITIONALVALUE_ATR, "ic"));
}
}
}
}
}
}
}
private void moveDetachableHetAtomRepl(Element bracket) throws ComponentGenerationException {
int indexOfLastHeteroatom = -1;
for (int i = bracket.getChildCount() - 1; i >= 0; i--) {
Element child = bracket.getChild(i);
if (child.getName().equals(HETEROATOM_EL)) {
indexOfLastHeteroatom = i;
break;
}
}
if (indexOfLastHeteroatom >=0) {
Element rightMostGroup = null;
Element nextSubOrRootOrBracket = OpsinTools.getNextSibling(bracket);
while (nextSubOrRootOrBracket != null) {
Element groupToConsider = nextSubOrRootOrBracket.getFirstChildElement(GROUP_EL);
if (groupToConsider != null) {
rightMostGroup = groupToConsider;
}
nextSubOrRootOrBracket = OpsinTools.getNextSibling(nextSubOrRootOrBracket);
}
if (rightMostGroup == null) {
throw new ComponentGenerationException("Unable to find group for: " + bracket.getChild(0).getValue() +" to apply to!");
}
Element rightMostGroupParent = rightMostGroup.getParent();
for (int i = indexOfLastHeteroatom; i >= 0; i--) {
Element locantededHeteroAtomRepl = bracket.getChild(i);
locantededHeteroAtomRepl.detach();
rightMostGroupParent.insertChild(locantededHeteroAtomRepl, 0);
}
}
}
}
|
<gh_stars>1-10
package com.sunj.gankio.widget.search;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.sunj.gankio.R;
/**
* @Description:
* @Author: sunjing
* @Time: 2018/10/28 10:02 PM
*/
public class SearchText extends AppCompatEditText {
private Drawable mRightDrawable = ContextCompat.getDrawable(getContext(), R.drawable.ic_delete);
private float top, bottom, left, right, movex, movey;
public SearchText(Context context) {
super(context);
}
public SearchText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SearchText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void showDeleteIcon(boolean isShow) {
if (isShow) {
setCompoundDrawablesWithIntrinsicBounds(null, null, mRightDrawable, null);
} else {
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
setPadding(getHeight()/2, 0, getHeight()/2-mRightDrawable.getBounds().width()/2, 0);
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
showDeleteIcon(text.length() != 0 && hasFocus());
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
showDeleteIcon(length() != 0 && focused);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
movex = event.getX();
movey = event.getY();
bottom = getHeight();
left = getWidth() - getPaddingRight() - mRightDrawable.getBounds().width();
right = getWidth();
if (length() != 0 && movex > left && movex < right && movey > top && movey < bottom) {
setText("");
}
break;
}
return super.onTouchEvent(event);
}
}
|
History and management of congenital aortic stenosis and coarctation of the aorta in a 38-year-old patient We present the case of a 38-year-old woman with congenital aortic stenosis as well as coarctation of the aorta that was unrecognised in her childhood. The patient was treated by balloon valvuloplasty. Ten years after the procedure, clinical deterioration was observed with subsequent progression of valvular gradient, aortic regurgitation, and diagnosis of coarctation. At the age of 38 years, a routine echocardiographic test showed massive calcifications of aortic leaflets with a transvalvular gradient 77/41 mm Hg, and third-degree insufficiency with widening of the ascending aorta (42 mm) and normal left ventricle systolic function. Additionally, for the first time the test showed coarctation of the aorta narrowing in the isthmus below the arch down to 15 mm, with a maximum flow gradient ca. 60 mm Hg. The management of the complex heart defects is currently being considered.
|
def remove_node_dependency(self, node):
assert node in self.vertices
others = [v for v in self.vertices if (node, v) in self.edges]
for other in others:
self.remove_edge_dependency((node, other))
|
Improved DNA probe detection of Listeria monocytogenes in enrichment culture after physical-chemical fractionation. Bacterial detection in foods by nucleic acid probes is limited by microflora competition during selective enrichment. Probe target concentration by extraction and fractionation of enrichments may diminish this limitation. The 1-h AccuProbe chemiluminescent culture identification test for Listeria monocytogenes was used as a model. Its high detection threshold provides a stringent challenge for evaluating enrichment work-up protocols. Detection of L. monocytogenes, at 1-4 colony-forming units/g food, was not consistently possible in 48 h enrichment cultures using AccuProbe. Concentration by cell sedimentation was occasionally helpful but the volume of co-sedimented food limited concentration to about 10-fold. To improve concentration, enrichment sediments were sonicated or enzymatically lysed to release the probe's target, r-RNA. The RNA was separated from non-RNA material by extraction with phenol and precipitation with ethanol. Enrichments (250 mL) were concentrated 2500-fold, and the limitation was food RNA volume. A strongly competitive Enterococcus faecium food isolate was used to demonstrate the effect of artificial competition on the kit's ability to detect L. monocytogenes in enrichments. High competitor concentrations repressed the level of the target below the detection threshold, but concentration of r-RNA enabled detection of L. monocytogenes. The effectiveness of this enrichment sample work-up was demonstrated with naturally contaminated hummus.
|
Evaluation of tolerance to Phytophthora capsici-the causal agent of foot rot disease in black pepper Vietnam is the leading black pepper export country in the world. However, the production of pepper may be affected by natural disasters, pests such as Phytophthora capsici. The Phytophthora capsica disease has caused a significant decline in pepper yields. The disease is characterized with a high mortality rate (up to 100%) and rapid outbreak and thus is very challenging to control. In the present study, eight strains of P. capsici were isolated from 100 samples of leaf, stem, root and soil that were collected from pepper-growing areas of Dong Nai, Binh Duong and Ba Ria - Vung Tau provinces. These isolates' straits had capacity to cause foot rot on pepper leaf after two days of inoculation. Among them, the isolates with the highest pathogenicity are BR-L1, DN-D1 and DN-D2. In order to determine the resistance level to P. capsici of commonly grown pepper varieties (Vinh Linh, Se, Xanh, Trau and Kuching), the pepper leaves were in vitro infected with P. capsici BR-L1 spores in laboratory and greenhouse conditions. Trau variety showed the highest resistance level to P. capsici with the as indicated by (P < 0.01) disease ratio (74.1%) and disease index (73.7%) after 6 days in laboratory condition and the corresponding numbers of 17.3% and 15.8% after 12 days in greenhouse condition.
|
INDUSTRIAL SETTING OF SOCIO-ECONOMIC ACHIEVEMENT AND CLASS MOBILITY Employment in different industries and sectors of the economy influences the socio-economic status, occupational prestige, income and social mobility of individuals irrespective of characteristics such as class, education, gender, social background etc. In order to prove this claim, the paper places social mobility, class structure transformations and socio-economic achievement in their economic context characterised by the industrial and sectoral composition. The consequences of an individual's location in a so defined economic setting constitute the main topic of the analysis. The addition of a structural economic dimension increases our ability to explain these processes. Thus, the economic structure, defined in terms of industries and sectors, has to be interpreted as an additional dimension of social structure.
|
def _sequence(self):
return self._complement.sequence.complement
|
On May 1st, protest marches were held in major cities all across America. In many instances, union workers marched arm in arm with radical communists. You see, the truth is that “May Day” is very important to communists, and they were out in full force to support their cause. But instead of shunning the communists, liberal activists greeted “their brothers and sisters” with open arms. The photos posted below are from a “May Day” march in California that were recently emailed to me by a friend. They are incredibly disturbing. They show workers from various unions such as the SEIU marching arm in arm with members of the communist party. Remember, the SEIU contributed nearly $28 million to Obama’s campaign in 2008. That made the SEIU “the organization that spent the most to help Barack Obama get elected president.” So the SEIU is very close to Obama. And to see Obama supporters marching in “solidarity” with their communist comrades in California is very disturbing.
The following are the photos that were emailed to me. Try not to get too sick as you look at them.
This young lady is encouraging American workers to “fight for communism”….
This man believes that the time has come to “smash capitalism”. Also notice the SEIU banner in the background….
In this photo, we see the banner of the communist party USA prominently displayed….
During the march, SEIU banners were displayed proudly right along with the red flags of communism….
Pro-illegal immigration protesters were also welcomed by the SEIU marchers….
One communist even openly displayed a sign bearing the likeness of Lenin….
Of course hatred for the Tea Party was a huge theme….
Apparently they were not fond of Sheriff Joe Arpaio either….
Do you ever think you would have seen something like this back in the 1950s or 1960s in America?….
We need to let America know the truth about these Obama supporters. They plan to “mobilize the masses for communism” and turn America into a very different place….
Unfortunately, large numbers of Americans are getting swept up in movement such as “Occupy Wall Street” without understanding what is really going on.
The communist movement in America is gaining numbers and influence. As the economy falls apart, even more Americans will rally to their cause.
Eventually, these radicals will not be content with just marching in the streets. At some point many of them will decide to take more direct action.
Please share this with as many people as you can. We need to wake people up to what is happening.
|
pub mod page;
pub use page::Page;
|
Postscript on the Realism-Instrumentalism Debate The body of the monograph has throughout skirted around the philosophic literature comprising the realist-instrumentalist debate. This Postscript does not take sides in this debate, but offers suggestions intended to make the debate more tractable. One suggestion concerns two largely ignored distinctions: the first between theoretical claims that enter into the design of an experiment constitutively versus only heuristically; the second between intermediate standings a hypothesis can have between its being a mere conjecture and its becoming deeply entrenched through the success of research predicated on it. The second half of the Postscript explains why, of all elements of science, the equations in theory-mediated measurement that authorize values for target quantities to be obtained from values of more accessible quantities and the values so obtained can, under identifiable conditions, have the strongest claim to permanence in the face of both new data and theory change.
|
/**
* Announce this connection to the backend with the intention of
* transferring a file (read or write). This should be the first command
* sent to the backend after {@link #mythProtoVersion()}.<br>
* <br>
* If a file transfer is not needed, use
* {@link #ann(ConnectionType, String, EventLevel)} instead.
*
* @param host
* the name of the host that is being announced (the client)
* @param type
* how the transfer connection will be used (read/write)
* @param readAhead
* if <code>true</code>, the backend will spawn a read ahead
* thread
* @param timeout
* milliseconds to timeout the transfer
* @param uri
* the URI of the file to transfer, relative to the storage group
* @param storageGroup
* the storage group that contains (will contain) the file to be
* transferred (optional, can be <code>null</code>, in which case
* any and all storage groups are used)
* @param commandProtocol
* the protocol that will be used to send file transfer commands
* @return a sub-protocol API that can be used to manipulate the data stream
* @throws IOException
* if there is a communication or protocol error
*/
public QueryFileTransfer annFileTransfer(String host,
FileTransferType type,
boolean readAhead,
long timeout,
URI uri,
String storageGroup,
Protocol commandProtocol) throws IOException;
|
Towards a typology of social news apps from a Crowd Computing perspective The Web is now both an information repository and a cyberspace supported by a participatory culture. In the domain of news and journalism, the Social Web has witnessed the emergence of Social News Websites (SNW), where users contribute for various reasons. Sites like Digg, Reddit and Storify, just to name a few, allow their users to discuss, comment, share, recirculate, tag and rate news from various sources. However, the social computing literature has described these sites so far through narrow definitions, e.g., as a synonym for social news aggregators, as specializations of social media or even as specialized forms of online social networks. In this research, we identify a broader landscape of social applications exploring citizen participation in the news value chain, and propose a broader definition and a typology for social news applications from the perspective of Crowd Computing.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.