content
stringlengths 10
4.9M
|
---|
/**
* Base class for all API, communication, or serialization related
* exceptions. The idea is to provide an consistent interface
* and shield dependent projects from having to have explicit source code
* dependencies on Jersey and Jackson.
*
*/
public class ApiException extends RuntimeException {
public ApiException() {
super();
}
public ApiException(final Exception exception) {
super(exception);
}
} |
Inverse spin Hall effect in a closed loop circuit
We present measurements of inverse spin Hall effects (ISHEs) in which the conversion of a spin current into a charge current via the ISHE is detected not as a voltage in a standard open circuit but directly as the charge current generated in a closed loop. The method is applied to the ISHEs of Bi-doped Cu and Pt. The derived expression of ISHE for the loop structure can relate the charge current flowing into the loop to the spin Hall angle of the SHE material and the resistance of the loop.
We present measurements of inverse spin Hall effects (ISHEs) in which the conversion of a spin current into a charge current via the ISHE is detected not as a voltage in a standard open circuit but directly as the charge current generated in a closed loop. The method is applied to the ISHEs of Bi-doped Cu and Pt. The derived expression of ISHE for the loop structure can relate the charge current flowing into the loop to the spin Hall angle of the SHE material and the resistance of the loop. Spintronic devices rely on the generation, manipulation, and detection of spin currents, flows of spin angular momentum . The spin Hall effect (SHE), originally predicted by Dyakonov and Perel in 1971 and revived by Hirsch about thirty years later, is one of the ways to convert an electric charge current into a spin current. Since the spin current does not accompany the flow of charge causing energy dissipation, effective ways to produce the spin current have been intensively studied in the field of spintronics . However, the spin current is not a conservative quantity but a diffusive flow. Thus, it cannot be directly observed but is measured via spin accumulation, and the spatial variation of spin accumulation is the spin current.
Using the inverse process of SHE, i.e., inverse SHE (ISHE), a spin current can be converted into a charge current. In a standard open circuit measurement, the charge current induced by the ISHE gives rise to charge accumulation generating an electric voltage . Here we present experiments showing clearly that the ISHE can also be detected by the current in a closed loop. The current in the loop can be measured as the voltage between two voltage probes in the loop. Such a voltage drop in the nanoscale device is a clear evidence of the conversion of spin current into charge current, which has not directly been observed in previous experiments . From the detailed analyses, it turns out that the amount of the charge current is determined by the spin Hall (SH) angle of SHE material and the resistance of the loop.
Samples have been fabricated on a thermally oxidized silicon subtrate using electron beam lithography on polymethyl-methacrylate resist and subsequent liftoff process. We first patterned a 100 nm wide wire and deposited permalloy (Py; Ni 81 Fe 19 ) by 30 nm. We also patterned a closed loop or an open end shape next to the Py wire and deposited two different SHE materials, i.e., Cu 99.5 Bi 0.5 and Pt, by 20 nm. The length of the loop L M is 6, 11, and 19 µm, and the distance (d) between the Py TABLE I: Dimensions (width w and thickness t) of Py, Cu, Cu99.5Bi0.5 and Pt wires constituting the SHE devices. We also show the resistivity ρ, the spin diffusion length λ and the SH angle αH measured at T = 10 K. The suffix X represents each material (N, F or M). The index (1D or 3D) indicates that the paramter is obtained with the one-dimensional (1D) or three-dimensional (3D) model. The values of λ 1D/3D X are taken from our previous papers . wire and the SHE wire is 500 nm. The Py and SHE wires were bridged by a 100 nm wide and 100 nm thick Cu wire transferring the spin current. We also deposited six Cu electrodes (i-vi in Fig. 1) to measure the voltage (V ISHE ) induced by the ISHE. Before the deposition of the Cu bridge and electrodes, a careful Ar ion etching was carried out for 30 seconds to obtain transparent interfaces between the SHE material and Cu as well as between Py and Cu. The detailed sample dimensions and other characteristics are listed in Table I. In Fig. 1(a), we show the principle of ISHE in an SHE ring using the spin absorption method . When the electric current I flows from the Py wire to the left side of the Cu wire, the resulting spin accumulation induces a pure spin current (I S ) on the right side of the Cu wire. The pure spin current is preferentially absorbed into the Cu 99.5 Bi 0.5 or Pt ring. The opposite spin-up and spin-down electrons composing the absorbed pure spin current are deflected to the same direction by the ISHE. As we will detail later on, this conversion occurs only below the Cu bridge.
In the present work, we prepared two types of samples, is the saturation field of magnetization of the Py wire, as already shown in our previous reports .
What is interesting to note is the amplitude of R ISHE , i.e., ∆R ISHE . In the closed loop structure, ∆R ISHE depends on the distance L between two voltage positions as shown in Fig. 1 To see clearly the relation between ∆R ISHE and L, we plot ∆R ISHE of the Cu 99.5 Bi 0.5 and Pt rings as a function of L in Fig. 2(a). Both of them show a linear dependence on L, but ∆R ISHE of Cu 99.5 Bi 0.5 has a negative slope while that of Pt has a positive one. This is consistent with our previous works; the SH angle α H of Cu 99.5 Bi 0.5 is negative while that of Pt is positive . From the linear dependence of ∆R ISHE on L, we can conclude that an electric current (I loop ) flows in the SHE ring and the direction of the current relies on the SH angle of the SHE material. From the slope of ∆R ISHE vs L curve, we can estimate I loop in the ring; I loop = −0.18 nA for Cu 99.5 Bi 0.5 and I loop = 0.04 nA for Pt when I = 0.58 mA is applied. However, the obtained I loop is too small when we simply consider the conversion of spin current into charge current via the ISHE.
We now formulate I loop within the standard onedimensional (1D) spin diffusion model . As shown in Figs. 1(d) and 1(e), the generated I S is absorbed into the SHE ring because of its strong spin-orbit interaction. In this device structure, the absorbed pure spin current can be expressed as follows: where I S is defined as an average of pure spin current flowing vertically into the Cu 99.5 Bi 0.5 or Pt ring. R N , R F and R M are respectively the spin resistances of Cu, Py and Cu 99.5 Bi 0.5 or Pt, and Q F = R F /R N and where ρ X , λ X , p X and A X are respectively the electrical resistivity, the spin diffusion length, the spin polarization, the effective cross sectional area involved in the equations of the 1D spin diffusion model and the suffix X represents each material (N, F or M). These values obtained at T = 10 K are shown in Table I. Here I 1 , I 2 and I loop are currents flowing in the SHE material only below the Cu bridge, in the Cu bridge, and in the SHE material outside the Cu bridge, respectively. As can be seen in Fig. 1(g), ∆R ISHE has no voltage position dependence. Thus, the induced ISHE voltage ∆V ISHE can be written as follows: where r is the resistance of the SHE material below the Cu bridge , ρ M is the longitudinal resistivity of the SHE material, and x ≃ 0.36 is the shunting factor, originally introduced in Ref. . This expression is indeed the same as Eq. (2) in Ref. .
In the loop structure, I loop is not zero anymore as shown in Fig. 1(d) and can be expressed as: To obtain Eq. (3), we assume L M ≫ w N . From this equation, we can explain that I loop depends not only on α 1D H but also on L M . In addition, ∆V ISHE at the endpoint of the loop (L = L M ) becomes Eq. (2) since it is a product of I loop and the resistance of the loop. As I loop is already obtained from Fig. 2, we can estimate α 1D H with Eq. (3). We note that unlike the case of the lateral spin valve device , λ 1D M , which is needed to obtain I S , cannot be directly determined on the same device. Therefore, as shown in Table I, we have referred to λ 1D M reported in our previous works to obtain α 1D H ; α 1D H = −0.11 for Cu 99.5 Bi 0.5 and α 1D H = 0.014 for Pt. These results are consistent with our previous works . as can be seen in Fig. 2(b). This result also supports the above consideration.
To confirm our 1D analysis, we have also performed three-dimensional (3D) analyses for V ISHE and I loop using SpinFlow 3D based on the Valet-Fert formalism . In the case of the open circuit device, the distribution of V ISHE is homogeneous both for the left and right sides, and the difference between the two sides corresponds to ∆V ISHE , as shown in Fig. 3(a). This result also indicates that I loop = 0. When the SHE material has a closed loop structure, on the other hand, V ISHE gradually changes from the positive value (on the left side) to the negative one (on the right side), but ∆V ISHE obtained at the two edges next to the Cu bridge is the same as that for the open end circuit . This is consistent with the experimental result shown in Fig. 2(b). To prove that the charge current flows in the ring, we show the charge current density distribution calculated with SpinFlow 3D in Figs. 3(c)-3(f). As in the case of the 1D model, j C is compensated by j below the Cu bridge, but since the SHE material has a ring shape, the small leakage current flows in the ring. From the leakage current, we can also estimate α 3D H by using λ 3D M shown in Table I; α 3D H = −0.22 for Cu 99.5 Bi 0.5 and α 1D H = 0.021 for Pt. These are again consistent with our previous works .
In Fig. 3, we selected Pt as an SHE material to show the current distribution in the ring. We obtain the similar current distribution for CuBi but with the opposite direction compared to Pt. However, the current distribution below the Cu bridge is much more complicated to see than that for Pt. This originates from the spreading of the spin accumulation at the side edges of the CuBi ring since λ CuBi is larger than t CuBi .
Finally, we discuss how I 1 , I 2 and I loop are generated in the closed loop circuit and how I loop can be utilized. As shown in Fig. 1(d), the induced I S is injected into the SHE material from the Cu bridge. We note here that the conversion of I S into I C occurs only at the Cu/SHEmaterial junction. Thus, electrons converted from I S lose the driving force once they go out from the junction, and are accumulated to one side. This induces the electric field in the SHE wire. For the open end circuit, the accumulated electrons are balanced with the electric field, as in the case of the normal Hall effect. As a result, I C is cancelled out by I 1 and I 2 , and the electric voltage ∆V ISHE can be measured. When the circuit is closed, the electric field also induces I loop in the loop. This I loop is essentially different from a current due to electromotive force induced by an alternating magnetic field through a ring. Although we have used the ac lock-in technique to obtain I loop , it is in principle a dc current. The present result clearly shows that by flowing I from Py to Cu non-locally, another steady current can be induced in a mesoscopic ring with a large α H via the ISHE.
As discussed above, since I loop is proportional to t M /L M , it is of the order of 1 nA at the moment. By op-timizing the device structure, the value can be enhanced by a factor of ten. Furthermore, by replacing a part of SHE ring with a superconductor, we could obtain a smaller resistance of the loop compared to the resistance of the shunt (Cu bridge). In such a case, I loop should be enhanced closer to I C . It is known that when there is a magnetic flux φ threading such a mesoscopic ring, a small persistent current (of the order of 1 nA) is induced in the ring and shows an oscillation with a period of φ 0 = h/e where h is the Plank constant . In the same way as a dc-SQUID magnetometer, by arranging the SHE ring on top of a sample and measuring a current in the ring precisely, one could observe a modulation of I loop and thus extract the magnetization of the sample.
In summary, we have measured the ISHEs of CuBi and Pt by means of the spin absorption technique in both open end and closed loop circuits, and found that the electric current can be obtained only in the closed loop. The detected current depends on the spin Hall angle of the SHE material and also on the resistance of the loop. It is commonly considered that the ISHE converts a spin current into a charge current, but this is the first observation of the converted charge current via the ISHE of CuBi or Pt. The amount of the charge current can be quantitatively explained by our spin transport models.
We acknowledge helpful discussions with T. Kato. We would also like to thank Y. Iye and S. Katsumoto for the use of the lithography facilities. This work was supported by KAKENHI (Grant No. 24740217 and 23244071) and by Foundation of Advanced Technology Institute. |
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PBAP_PSE_SERVICE_H
#define PBAP_PSE_SERVICE_H
#include <cstring>
#include <list>
#include <map>
#include <vector>
#include "../obex/obex_headers.h"
#include "../obex/obex_session.h"
#include "../obex/obex_transport.h"
#include "base_def.h"
#include "context.h"
#include "interface_profile_pbap_pse.h"
#include "message.h"
#include "pbap_pse_def.h"
#include "raw_address.h"
namespace bluetooth {
/**
* @brief phone book server service
* process connect event
*/
class PbapPseService : public IProfilePbapPse, public utility::Context {
public:
/**
* @brief register observer
* @details register observer for the service of phone book serve
* @param observer the pointer that point to a PbapPseObserver
* @return void
*/
void RegisterObserver(IPbapPseObserver &observer) override;
/**
* @brief deregister observer
* @details deregister observer for the service of phone book serve
* @param observer the pointer that point to a PbapPseObserver
* @return void
*/
void DeregisterObserver(IPbapPseObserver &observer) override;
/**
* @brief get the remote devices
* @details get the remote device with the specified states
* @param states states
* @return std::vector remote devices
*/
std::vector<RawAddress> GetDevicesByStates(const std::vector<int> &states) const override;
/**
* @brief get the state of device
* @details get the state with the specified remote device
* @param device remote device
* @return int @c not -1 state of the specified remote device
* @c -1 device is not exist
*/
int GetDeviceState(const RawAddress &device) const override;
/**
* @brief constructor
* @details constructor
*/
PbapPseService();
/**
* @brief deconstructor
* @details deconstructor
*/
virtual ~PbapPseService();
/**
* @brief get context
* @details get context
* @return Context*
*/
utility::Context *GetContext() override;
/**
* @brief start server
* @details start phone book server
*/
void Enable() override;
/**
* @brief shutdown server
* @details shutdown phone book server
*/
void Disable() override;
/**
* @brief not used
* @details not used
*/
int Connect(const RawAddress &device) override;
/**
* @brief disconnect device
* @details disconnect from remote device
* @return bool @c 0 success
* @c -1 failure
*/
int Disconnect(const RawAddress &device) override;
/**
* @brief not used
* @details not used
*/
std::list<RawAddress> GetConnectDevices() override;
/**
* @brief Get Connect State
* @details Get Connect State for base service
*/
int GetConnectState() override;
/**
* @brief Get Max Connect Num
* @details Get Max Connect Num for base service
*/
int GetMaxConnectNum() override;
/**
* @brief Set the connection policy of the specified device.
*
* @param device Reference to the remote bluetooth device.
* @param strategy Reference to the connection policy,
* @c UNKNOWN : the connection policy for unkown state.
* @c ALLOWED : the connection policy for allowed state.
* @c FORBIDDEN : the connection policy for forbidden state.
* @return Returns true if the operation is successful;returns false if the operation fails.
*/
int SetConnectionStrategy(const RawAddress &device, int strategy) override;
/**
* @brief Get the connection policy of the specified device.
*
* @param device Reference to the remote bluetooth device.
* @return Returns the connection police of the specified bluetooth address.
*/
int GetConnectionStrategy(const RawAddress &device) const override;
/**
* @brief Grant connect permission to device
*
* @param device device
* @param allow allow
* @param save save
*/
void GrantPermission(const RawAddress &device, bool allow, bool save = false) override;
/**
* @brief Set device's password
*
* @param device device
* @param password device's password
* @param userId device's userId
*/
int SetDevicePassword(const RawAddress &device, const std::string &password, std::string userId = "") override;
/**
* @brief post message
* @details post message to self thread
* @param msg message from other threads
* @return void
*/
void PostMessage(utility::Message msg);
/**
* @brief Process Obex Request
*
* @param what msgId
* @param device remote address
*/
void ProcessObexRequest(int what, const RawAddress &device) const;
/**
* @brief Process Obex Request
*
* @param what msgId
* @param device remote address
* @param incomingConnect incoming connect
*/
void ProcessObexRequest(int what, const RawAddress &device, ObexIncomingConnect &incomingConnect);
/**
* @brief Process Obex Request
*
* @param what msgId
* @param device remote address
* @param session obex session
* @param req obex request header
*/
void ProcessObexRequest(int what, const RawAddress &device, ObexServerSession &session, const ObexHeader &req);
/**
* @brief Process Obex Busy
*
* @param device remote address
* @param isBusy isBusy
*/
void ProcessObexBusy(const RawAddress &device, bool isBusy) const;
/**
* @brief Get the Next Connect Id object
*
* @return uint32_t
*/
uint32_t GetNextConnectId() const;
private:
/**
* @brief enable service
* @details enable service
* @return void
*/
void EnableService();
/**
* @brief disable service
* @details disable service
* @return void
*/
void DisableService();
/**
* @brief disconnect to server
* @details disconnect to phone book server
* @param device remote device
*/
void DisConnectInternal(RawAddress device);
/**
* @brief incoming process
* @details when incoming obex server, call it
* @param device remote address
* @param msg message from other threads
* @return void
*/
void ProcessConnectIncoming(const RawAddress &device, const utility::Message &msg);
/**
* @brief incoming grant permission process
* @details when decide accept/reject incoming
* @param device remote address
* @param allow accept:true reject:false
* @param save save
* @return void
*/
void ProcessGrantPermission(const RawAddress &device, bool allow, bool save) const;
/**
* @brief disconnect after connected
* @details disconnect after connected
* @param device remote address
* @return void
*/
void ProcessWaitToDisconnect(const RawAddress &device) const;
/**
* @brief set password process
* @details when password set by user
* @param device remote address
* @param password password
* @param userId userId
* @return void
*/
void ProcessSetDevicePassword(const RawAddress &device, std::string password, std::string userId) const;
/**
* @brief connected process
* @details when connected obex server, call it
* @param device remote address
* @param msg message from other threads
* @return void
*/
void ProcessObexConnect(const RawAddress &device, const utility::Message &msg) const;
/**
* @brief disconnected process
* @details when disconnected obex server, call it
* @param device remote address
* @param msg message from other threads
* @return void
*/
void ProcessDeviceDisconnected(const RawAddress &device, const utility::Message &msg) const;
/**
* @brief shutdown process
* @details when shutdown obex server, call it
* @param msg message from other threads
* @return void
*/
void ProcessShutDownComplete(const utility::Message &msg);
/**
* @brief Incoming connect Timeout process
* @details when incoming connect Timeout , call it
* @param device remote address
* @return void
*/
void IncomingTimeout(const RawAddress &device);
void ProcessIncomingTimeout(const RawAddress &device) const;
/**
* @brief save pbap connection policy
* @details save pbap connection policy
* @param addr remote address
* @param strategy strategy
* @return bool
*/
bool SaveConnectPolicy(const std::string &addr, int strategy) const;
/**
* @brief load pbap connection policy
* @details load pbap connection policy
* @param addr remote address
* @param strategy strategy
* @return bool
*/
bool LoadConnectPolicy(const std::string &addr, int &strategy) const;
/**
* @brief is all devices disconnected
* @details is all devices disconnected
* @return bool
*/
bool IsAllDisconnected() const;
/**
* @brief load adapter config
* @details load adapter config
*/
void LoadAdapterConfig() const;
DECLARE_IMPL();
DISALLOW_COPY_AND_ASSIGN(PbapPseService);
};
} // namespace bluetooth
#endif // PBAP_PSE_SERVICE_H
|
<reponame>ob-algdatii-20ss/leistungsnachweis-teammaze<gh_stars>0
package solver
import (
"github.com/ob-algdatii-20ss/leistungsnachweis-teammaze/common"
)
const (
Add = "ADD"
Remove = "REMOVE"
Visited = "VISITED"
)
type Function = func(common.Labyrinth, common.Location, common.Location, bool) ([]common.Location, []common.Pair)
func contains(l []common.Location, e common.Location) bool {
for _, s := range l {
if s.Compare(e) {
return true
}
}
return false
}
func removeFirstOccurrence(l []common.Location, e common.Location) []common.Location {
for i, s := range l {
if s.Compare(e) {
return append(l[:i], l[i+1:]...)
}
}
return l
}
|
#ifndef GLMMAT4SERIALIZE_H_
#define GLMMAT4SERIALIZE_H_
#include <boost/serialization/serialization.hpp>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
namespace boost
{
namespace serialization
{
template<class Archive> void serialize(Archive& ar, glm::mat4& m, unsigned int version)
{
for (glm::detail::uint32 i=0; i < 4u; i++)
for (glm::detail::uint32 j=0; j < 4u; j++)
ar & m[i][j];
}
}
}
#endif /* GLMMAT4SERIALIZE_H_ */
|
<gh_stars>100-1000
package com.nilhcem.fakesmtp.log;
import java.util.Observable;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
/**
* Logback appender class, which will redirect all logs to the {@code LogsPane} object.
*
* @author Nilhcem
* @since 1.0
* @param <E> a Logback logging event.
*/
public final class SMTPLogsAppender<E> extends AppenderBase<E> {
private SMTPLogsObservable observable = new SMTPLogsObservable();
/**
* Receives a log from Logback, and sends it to the {@code LogsPane} object.
*
* @param event a Logback {@code ILoggingEvent} event.
*/
@Override
protected void append(E event) {
if (event instanceof ILoggingEvent) {
ILoggingEvent loggingEvent = (ILoggingEvent) event;
observable.notifyObservers(loggingEvent.getFormattedMessage());
}
}
/**
* Returns the log observable object.
*
* @return the log observable object.
*/
public Observable getObservable() {
return observable;
}
}
|
#include "NetGameEventListMessage.hpp"
#include "BitIO/BitIOReader.hpp"
#include "BitIO/BitIOWriter.hpp"
#include "misc/Exceptions.hpp"
#include "net/data/SourceConstants.hpp"
#include "net/worldstate/WorldState.hpp"
void NetGameEventListMessage::ReadElementInternal(BitIOReader& reader)
{
const auto eventsCount = reader.ReadInline<uint_fast16_t>("eventsCount", MAX_EVENT_BITS);
reader.Read("m_BitCount", m_BitCount, BIT_COUNT_BITS);
for (uint_fast16_t i = 0; i < eventsCount; i++)
{
GameEventDeclaration& e = m_Events.emplace_back();
reader.Read("m_ID", e.m_ID, MAX_EVENT_BITS);
e.m_Name = reader.ReadString("m_Name");
GameEventDataType type;
while ((type = reader.ReadInline<GameEventDataType>("GameEventDataType", EVENT_DATA_TYPE_BITS)) != GameEventDataType::Local)
{
const auto name = reader.ReadString("name");
e.m_Values.push_back(std::make_pair(name, type));
}
}
}
void NetGameEventListMessage::WriteElementInternal(BitIOWriter& writer) const
{
writer.Write(m_Events.size(), MAX_EVENT_BITS);
writer.Write(m_BitCount, BIT_COUNT_BITS);
for (const auto& event : m_Events)
{
writer.Write(event.m_ID, MAX_EVENT_BITS);
writer.Write(event.m_Name);
for (const auto& dt : event.m_Values)
{
writer.Write(dt.second, EVENT_DATA_TYPE_BITS);
writer.Write(dt.first);
}
writer.Write(GameEventDataType::Local, EVENT_DATA_TYPE_BITS);
}
}
void NetGameEventListMessage::GetDescription(std::ostream& description) const
{
description << "svc_GameEventList: number " << m_Events.size() << ", bytes " << (m_BitCount + 7) / 8;
}
void NetGameEventListMessage::ApplyWorldState(WorldState& world) const
{
auto clone = m_Events;
world.m_Events.PreGameEventListLoad(clone);
world.m_GameEventDeclarations = std::move(clone);
world.m_Events.PostGameEventListLoad();
} |
Identification of the Marginal Treatment Effect with Multivalued Treatments
Heckman et al. (2008) examine the identification of the marginal treatment effect (MTE) with multivalued treatments by extending the local instrumental variable (LIV) approach of Heckman and Vytlacil (1999). Lee and Salani\'e (2018) study the identification of conditional expectations given unobserved heterogeneity; in Section 5.2 of their paper, they analyze the identification of MTE under the same selection mechanism as in Heckman et al. (2008). We note that the construction of their model in Section 5.2 in Lee and Salani\'e (2018) is incomplete, and we establish sufficient conditions for the identification of MTE with an improved model. While we reduce the unordered multiple-choice model to the binary treatment setting as in Heckman et al. (2008), we can identify the MTE defined as a natural extension of the MTE using the binary treatment defined in Heckman and Vytlacil (2005). Further, our results can help identify other parameters such as the marginal distribution of potential outcomes.
Introduction
Assessing heterogeneity in treatment effects is important for precise treatment evaluation. The marginal treatment effect (MTE) provides rich information on heterogeneity across economic agents in terms of their observed and unobserved characteristics. Further, once the MTE is estimated, researchers can obtain other treatment effects, such as the average treatment effect (ATE), average treatment effect on the treated, and local ATE (LATE).
For the binary treatment models, Heckman and Vytlacil (1999) establish the local instrumental variable (LIV) framework to identify MTE, while Imbens and Angrist (1994) demonstrate that monotonicity is a sufficient condition for identifying LATE. Vytlacil (2002) shows that the LIV and LATE approaches depend on the same monotonicity assumption, implying that these approaches require that a selection mechanism be characterized by an additively separable latent-variable threshold-crossing model.
In many applications, selection problems cannot be adequately described using single-crossing models. For example, vocational programs provide various types of training to participants, and college choice involves numerous dimensions to respond to varied incentives. The literature has developed treatment effects with multivalued treatments, such as Angrist and Imbens (1995), Heckman et al. (2006Heckman et al. ( , 2008, Heckman and Vytlacil (2007b), Heckman and Pinto (2018), Lee and Salanié (2018), and Fusejima (2022). Heckman and Pinto (2018) introduce an "unordered monotonicity" condition that is weaker than a monotonicity condition under models with multiple choices, and show the identification of several treatment effects. Heckman et al. (2006Heckman et al. ( , 2008 and Heckman and Vytlacil (2007b) examine the treatment effect based on the discrete choice model that is additively separable in instruments and errors.
This model is a generalization of the multiple logit model, and has been extensively studied in economics since the seminal work of McFadden (1974). In theoretical research, Matzkin (1993) establishes sufficient conditions for the nonparametric identification of the discrete choice model.
In applied research, Dahl (2002) employs this model to study the effects of self-selected migration on returns to college. Kline and Walters (2016) use the discrete multiple-choice model as a self-selection model to analyze the Head Start program's cost-effectiveness. Heckman and Vytlacil (2007b) and Heckman et al. (2008) expand the LIV approach to a model with multivalued treatments generated by a general unordered choice model. They identify various treatment effects related to MTE and LATE. The MTE of one specified choice versus another choice can be identified if we assume utilities of all the other options are quite small. For example, when the number of treatments is three, Heckman and Vytlacil (2007b) and Heckman et al. (2008) assume the utility of one option is sufficiently small, and reduce the model to the binary treatment model in effect. Thereafter, they identify the MTE using identification results in the binary model. Lee and Salanié (2018) investigate the identification of conditional expectations given unob-served variables based on multinomial choice models characterized by a combination of separable threshold-crossing rules. They assume the existence of continuous instruments and identify several causal effects with identified thresholds. In Section 4, they introduce several commonly used models that their framework covers and show the identification of MTE for each model with sufficient conditions for the identification of thresholds. In Section 5.2, Lee and Salanié (2018) analyze the identification of the MTE of one specified choice versus another specified choice studied by Heckman and Vytlacil (2007b) and Heckman et al. (2008). They argue that if we know the thresholds and apply the result of Lee and Salanié (2018), we can identify MTE without reducing the model to the binary treatment case.
We notice that the construction of threshold-crossing rules in Section 5.2 of Lee and Salanié (2018) is incomplete, and we establish sufficient conditions for identifying MTE under an improved model. Under the assumptions for the threshold variation, we reduce the unordered multiple-choice model to a binary treatment setting, as in Heckman and Vytlacil (2007b) and Heckman et al. (2008). A major distinction between Heckman et al. (2008) and our study is the object of the identification. By extending the LIV approach, Heckman and Vytlacil (2007b) and Heckman et al. (2008) identify MTE. We study the identification of conditional expectations on unobserved heterogeneity. While the MTE that Heckman and Vytlacil (2007b) and Heckman et al. (2008) identify depends on the cumulative function of unobserved error terms, we identify the MTE conditional on the unobserved variable normalized to have a uniform distribution on . In the binary treatment case, Heckman and Vytlacil (2005) identify the MTE conditional on unobserved heterogeneity that uniformly ranges from 0 to 1. Therefore, the MTE we identify is a natural extension of the MTE defined in Heckman and Vytlacil (2005) to the multiple-choice model. Moreover, our results help identify not only MTE but also other measurements, such as quantile treatment effect.
We further establish a sufficient condition for identifying the thresholds. Heckman et al. (2008) identify the MTE given known utility functions and refer to Heckman and Vytlacil (2007a) for the identification of utility functions. The identification results of Lee and Salanié (2018) are conditional on the identified thresholds. While they rely on Matzkin (1993) 2 Multiple Discrete Choice Model and Lee and Salanié (2018) 2
.1 Basic Setup
Let := denote "equals by definition," and let a.s. denote "almost surely." Let ½{·} denote the indicator function. For random variables X and Z, f X (·) denotes the probability density function of X. F X|Z (·) and Q X|Z (·) denotes the distribution and quantile functions of X given Z, respectively. Let · d denote the Euclidean norm in R d , and let N d (a, δ) be a δ-neighborhood of a in (0, 1) d , that is, For any set A and B,Ā denotes the closure of A, and A\B denotes the set difference, that is, the set of elements in A but not in B. Let |A| denote the cardinality of A.
As in Heckman et al. (2006Heckman et al. ( , 2008 and Heckman and Vytlacil (2007b), we consider the following discrete choice model. Let K be the set of treatments comprising K(= |K|) elements, and let Z be the vector of the observed random variables. For each k, we define R k (Z) as an unknown function that maps from R dim(Z) to R and define U k as an unobserved continuous random variable whose support is R. Let {Y k : k ∈ K} be a potential outcome. D k takes the value one if the agent chooses treatment k. By extending the definition of the treatment variable in the binary treatment model, we formulate the treatment decision as follows: where Pr((R k (Z) − U k ) = (R j (Z) − U j )) = 0 for j = k. The observed outcome and treatment are expressed as D = K−1 k=0 kD k and Y = K−1 k=0 D k Y k , respectively. The data contains covariates X and instruments Z. Throughout this article, we condition on the value of X and suppress it from the notation. Let the support of Y and Z be Y ⊂ R and Z ⊂ R dim(Z) , respectively.
Intuitively, by interpreting R k (Z) and U k as utility and cost from choice k, respectively, this discrete multiple-choice model states that an agent chooses a choice that gives the largest benefit.
From this intuition, we regard model (1) as a straightforward extension of the generalized Roy model.
Model
(1) has been studied extensively in economics since the seminal work of McFadden (1974). Matzkin (1993) establishes sufficient conditions for the nonparametric identification of the utility functions and the cumulative joint density of unobserved random terms. The multinomial choice model has also been used in applied research. Dahl (2002) uses this model to study the effects of self-selected migration on the return to college. Kline and Walters (2016) adopts the discrete multiple-choice model as a self-selection model and analyzes the Head Start program's cost-effectiveness in the presence of the substitute preschools. Kirkeboen et al. (2016) examine the effect of types of postsecondary education on the gains in earnings. They find that the estimated payoffs are consistent with agents choosing fields based on a discrete multiplechoice model.
2.2 Section 5.2 of Lee and Salanié (2018) Lee and Salanié (2018) employ the following model: where c k l is an integer. Let Q(Z) denote the vector of functions of the instruments Q i (Z), that is, Let V = (V 1 , · · · , V J ) be a vector of continuous random variables whose support is J . For each j ∈ {1, · · · , J}, define S j (V, Q(Z)) := ½(V j < Q j (Z)), which is an element of the selection mechanism (2). Let J be the set {1, · · · , J}, and let L be the set of all the subsets of J .
Model (2) can express any decision model that comprises sums, products, and differences of their indicator functions S j , that is, ½(V j ≥ Q j (Z)). When Z is given, Q j (Z) becomes constant and serves as a threshold for each S j .
Evidently, this corresponds to the decision rule based on model (1).
We first collect relevant assumptions and definitions in Lee and Salanié (2018).
Assumption 2.1 (Lee and Salanié, 2018) Any of the following three equivalent statements holds: (i) the treatment variable D is measurable with respect to the σ-field generated by the events Moreover, every treatment value k has positive probability.
Assumption 3.4 (Lee and Salanié, 2018) The point q ∈ (0, 1) 3 belongs to the interior of the range of variation of the thresholds Q.
q is the point where we can identify the MTE. Q is defined as follows: Definition 3.1 (Lee and Salanié, 2018) Let Z denote the support of Z, and let Q = Lee and Salanié (2018) Moreover, because they identify the MTE via multidimensional cross derivatives, they do not rely on the identification-at-infinity strategy.
The following proposition shows that if one assumes Assumption 3.2 of Lee and Salanié (2018), this model does not satisfy Assumption 3.4 of Lee and Salanié (2018). By construction, the value of (Q 0,1 (Z), Q 0,2 (Z), Q 1,2 (Z)) ′ is uniquely determined by only two arguments. This implies that Q becomes a surface in (0, 1) 3 . Because a surface does not contain any sphere, Assumption 3.4 of Lee and Salanié (2018) fails.
Consequently, we cannot apply Theorem A.1 of Lee and Salanié (2018) to their model in Section 5.2 and cannot achieve the identification of the MTE with multivalued treatments.
Model and Identification
This section reveals the identification of MTE in model (1) in Section 2.1. We construct a model of three alternatives for the identification of MTE, with a focus on Y 1 . Sections 3.1 and 3.2 provide sufficient conditions for identifying MTE between Y 2 and Y 1 , and between Y 0 and Y 1 , respectively. Section 5 provides a general model that identifies the MTE between Y j and Y k AssumeŨ 1,0 andŨ 1,2 are continuously distributed. Let Note that and a similar argument gives We show D 2 = (1 − S 2 )S 3 . By construction, we obtain For the MTE identification, we impose basic assumptions that are also required in Lee and Salanié (2018) and Heckman et al. (2008). Noteworthily, each element of V has U distribution from its definition. The main idea of our identification strategy is similar to that in Heckman and Vytlacil (2007b) and Heckman et al. (2008) 1 . They assume (U 0 , U 1 , U 2 ) are continuously distributed whose support is equal to R 3 ; that (Y 0 , Y 1 , Y 2 ) and V are jointly independent of Z; and that, To identify MTE of one specified choice versus another specified choice, they impose a large support assumption in Theorem 8 (Heckman and Vytlacil, 2007b) and Theorem 3 (Heckman et al., 2008). This large support assumption implies that one utility function, R k (Z), can take a sufficiently negative value, which effectively reduces the model with three alternatives to a binary case. In the following subsection, we impose assumptions that play the same role as the large support assumption.
In the binary treatment case, Heckman and Vytlacil (2005) define D * = 1 as the receipt of the treatment and characterize the decision rule as the generalized Roy model, that is, where µ D (Z) is an unknown function, which maps from R dim(Z) to R, and U D is an unobserved continuous random variable. As a normalization, they innocuously assume that Thereafter, Heckman and Vytlacil (2005) define MTE with binary treatment as where u D ∈ (0, 1) A major distinction between Heckman et al. (2008) and our study is the object of the identification. By extending the LIV approach, Heckman and Vytlacil (2007b) and Heckman et al. (2008) study the identification of MTE, that is, for any ℓ ∈ R and j, k ∈ K, such that j = k, We study the identification of the following conditional expectations 2 When we set G(Y ) = Y and take the difference between two conditional expectations, we identify the following MTE: We identify MTE (7) conditional on V . By the definition of V , V uniformly ranges from 0 to 1, and q * is the quantile of the distribution of U k −U j , which corresponds to the definition of MTE (5) with binary treatment in Heckman and Vytlacil (2005). However, Heckman et al. (2008) and Heckman and Vytlacil (2007b) identify MTE (6) conditional on U k −U j , which implies the shape of the cumulative function of U k − U j affects the interpretation of MTE. Therefore, the MTE (7) is a natural extension of MTE with binary treatment to the multivalued treatment case.
Identification of MTE between Y 1 and Y 2
As in Heckman and Vytlacil (2007b) and Heckman et al. (2008), we impose the large support assumption for the identification of MTE between Y 1 and Y 2 .
Definition 3.1. Let Z denote the support of Z and Q = Q(Z) denote the range of variation of Assumption 3.5. Let q * 2 be in (0, 1).
Assumption 3.5 ensures partial differentiability that is important for the MTE identification.
Assumption 3.5 (ii) ensures the existence of the case wherein the agents choose between options 1 and 2, which plays the same role as the large support assumption in Heckman and Vytlacil (2007b) and Heckman et al. (2008). Assumptions 3.1 to 3.5 impose no explicit restriction on Z, but Assumption 3.5 (ii) implicitly requires that at least two variables in Z must be continuous.
not in Q, the range of variation of Q(Z), these two conditional expectations are not defined at (q 1 , q 2 ) ′ = (1, q * 2 ) ′ . We identify MTE between Y 1 and Y 2 by first extending these two conditional expectations to N 2 ((1, q * 2 ) ′ , δ), such that they are defined at (1, q * 2 ) ′ and, thereafter, by partially differentiating the extended functions with respect to Q 2 (Z) at (1, q * 2 ) ′ . To this end, we first introduce the definition of Cauchy continuity.
Definition 3.2 (Cauchy continuity
Lemma 3.1 (Theorem 7, Snipes (1977)). Assume A is dense in X, where X ⊂ R d . If a function f : A → R is Cauchy continuous, a unique continuous functionf : X → R that extends f exists.
The following lemma extends
Conditional on the assumption that Q 1 (Z) and Q 2 (Z) are identified, we identify the con- In Section 4, we give a sufficient condition of the identification of thresholds Q(Z) that Heckman and Vytlacil (2007b) and Heckman et al.
Theorem 3.3. Assume Assumptions 3.1 to 3.5 hold. Then, the conditional expectations of G(Y 1 ), G(Y 2 ) are given by The identification result of the conditional expectations enables us to identify measures of treatment effects. For example, if we set G(Y ) = Y as we did previously, we obtain If we let G(Y ℓ ) = ½(Y ℓ ≤ y) for y ∈ R, we can identify If F Y 1 |V and F Y 2 |V are invertible, we identify the quantile treatment effect by taking the difference between the two, that is, where τ ∈ (0, 1).
Identification of MTE between Y 0 and Y 1
In this subsection, similar to Section 3.1, we state sufficient conditions for the identification of MTE between Y 0 and Y 1 . We impose assumptions similar to Assumptions 3.5 in Section 3.1.
respectively.
A similar argument to Theorem 3.3 provides the identification results for the conditional Theorem 3.5. Assume Assumptions 3.1 to 3.4 and 3.6 hold. Then, the conditional expectations of G(Y 0 ), G(Y 1 ) are given by .
Identification of thresholds Q(Z)
In this section, we provide a sufficient condition for the nonparametric identification of Q 1 (Z) and Q 2 (Z). Heckman et al. (2008) identify the MTE given known utility functions; they refer to Heckman and Vytlacil (2007a) for the identification of utility functions. Lee and Salanié (2018) establish the sufficient conditions for the identification of the MTE conditional on the assumption that Q(Z) is already identified. They rely on Matzkin (1993)'s result, which establishes sufficient conditions for the nonparametric identification of the utility functions and the cumulative joint density of unobserved random terms. However, because Matzkin (1993) does not intend to identify thresholds, her result is not sufficient for the nonparametric identification of thresholds.
We establish a sufficient condition for the identification of thresholds, thereby enabling the estimation of MTE with the results in Theorems 3.3 and 3.5.
A sufficient condition requires the existence of at least one instrument that significantly and negatively affects only one utility.
Generalization
This section generalizes the framework in Section 3 to identify the MTE for the discrete choice model with more than two treatments.
Model and Assumptions
In this subsection, we construct a model for the identification of MTE between Y j and Y k for any j = k, where j, k ∈ K and |K| ≥ 3.
Define, for each i = k in K, 4 Assumption 4.1 implies Assumption 3.5 (ii) and Assumption 3.6 (ii) because Q1(Z), Q2(Z) approach one as R0(Z), R2(Z) approach minus infinity, respectively. AssumeŨ k,i s are continuously distributed. Let By construction, Q i (Z), V i and S i are defined for each i in K except k. Note that Define, for each i = j, k in K, By construction, we obtain Hence, D j = i∈K\{k,j} S * i (1 − S j ) by definition. We use the same strategy to identify MTE between Y j and Y k as in Section 3. Assumptions 5.1 to 5.5 in the following correspond to Assumptions 3.1 to 3.5, respectively.
To reduce the model with multivalued treatments to a binary treatment model, we need to impose Assumption 5.5 which enables us to define two conditional expectations, , and E at q * j by extension, and to partially differentiate two extended conditional expectations with respect to Q j (Z) at q * j .
Lemma 5.1. Under Assumptions 5.1 to 5.5, there exist continuous functions respectively. This extension is unique.
Identification Result of MTE
from Lemma 5.1, we identify the MTE at V j = q * j in a similar way to Theorems 3.3 and 3.5.
Theorem 5.2. Let Assumptions 5.1 to 5.5 hold. Then, the conditional expectations of G(Y k ), G(Y j ) are given by
Conclusion
We study the identification of MTE with multivalued treatments. We note that the model in Section 5.2 of Lee and Salanié (2018) is incomplete for identifying MTE and propose an improved model. By reducing the multiple discrete choice model to the case with binary treatment, we achieve the identification of MTE that is a natural extension of MTE with binary treatment defined in Heckman and Vytlacil (2005). Further, we establish a sufficient condition for the identification of thresholds.
For any Z ∈ Z q , it follows from (A.1) that Hence, if q is included in Q, q 3 is uniquely determined by q 1 and q 2 as Becauseq := (q 1 , q 2 , q 3 + δ 2 ) with δ > 0 does not satisfy (A.2), q cannot be in the interior of Q. Therefore, Q does not contain q that satisfies the Assumption 3.4 of Lee and Salanié (2018). ✷
giving the stated result for Q 1 (Z). For Q 2 (Z), similar to the proof for Q 1 (Z), we have Hence, it follows from the DCT and Fubini's theorem that:
It follows from the DCT and Fubini's theorem that
Then, from an argument similar to that in (A.15), we obtain (A.16). |
package main
// program to create sqlite file used by the auth api
// if no file specified it will create a file with the
// default name of users.db
// args:
// 1) existing sqlite file name (optional)
import (
"fmt"
"github.com/satori/go.uuid"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/ssh/terminal"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"os"
"strings"
)
//types based on models.go
type UserCredentials struct {
Username string
Password string
}
type User struct {
Username string `gorm:"primaryKey"`
PassHash []byte
TokenSlug uuid.UUID
TokenID uuid.UUID `gorm:"index"`
}
//function defs
func register_server_user(userdb *gorm.DB, username string, passwd string) {
creds := &UserCredentials{Username: username, Password: <PASSWORD>}
if creds.Username == "" || creds.Password == "" {
return
}
//salt and hash the password using the bcrypt algorithm
//the second argument is the cost of hashing, which we arbitrarily set as 8 (this value can be more or less, depending on the computing power you wish to utilize)
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 8)
tokenslug := uuid.Must(uuid.NewV4(), err)
if err != nil {
fmt.Println(err)
return
}
tokenid := uuid.Must(uuid.NewV4(), err)
if err != nil {
fmt.Println(err)
return
}
var newuser = User{ //create new user
Username: creds.Username,
PassHash: <PASSWORD>,
TokenSlug: tokenslug,
TokenID: tokenid,
}
err = userdb.Table("users").Create(&newuser).Error //send new user to the database
if err != nil {
fmt.Println("Error creating user " + creds.Username)
fmt.Println(err)
return
}
}
func setup_file(filename string) (*gorm.DB, error) {
var db *gorm.DB
var err error
if filename != "" {
db, err = gorm.Open(sqlite.Open(filename), &gorm.Config{})
} else {
db, err = gorm.Open(sqlite.Open("users.db"), &gorm.Config{})
}
db.AutoMigrate(&User{})
return db, err
}
func enter_creds() (string, string, error) {
var username string
var password string
fmt.Println("Enter Username: ")
fmt.Scanln(&username)
fmt.Println("Enter Password: ")
bytePassword, err := terminal.ReadPassword(0)
password = string(<PASSWORD>)
return strings.TrimSpace(username), strings.TrimSpace(password), err
}
func printhelp() {
fmt.Println("Run command: go run users_db_helper.go <filename (opt)>")
fmt.Println("Args:")
fmt.Println("1) existing sqlite file name (optional)")
fmt.Println("")
fmt.Println("You will be prompted for your credentials after initiating the run command")
}
func main() {
var userdb *gorm.DB
argsWithoutProg := os.Args[1:]
if len(argsWithoutProg) == 1 && argsWithoutProg[0] == "-h" {
printhelp()
return
}
username, pass, err := enter_creds()
if err != nil || username == "" || pass == "" {
fmt.Println("Error recieving credentials")
return
}
if len(argsWithoutProg) > 1 {
fmt.Println("Invalid arguments, exiting")
return
} else if len(argsWithoutProg) == 1 {
userdb, err = setup_file(argsWithoutProg[0])
} else {
userdb, err = setup_file("")
}
if err != nil {
fmt.Println("Error, could not connect to users db")
return
}
register_server_user(userdb, username, pass)
}
|
/**
* Key iterator implementation.
*/
private final class KeyIterator extends HashIterator implements Iterator<K>, Enumeration<K> {
/**
* @param asc {@code True} for ascending iterator.
*/
private KeyIterator(boolean asc) {
super(asc);
}
/** {@inheritDoc} */
@Override public K next() {
return nextEntry().key;
}
/** {@inheritDoc} */
@Override public K nextElement() {
return nextEntry().key;
}
} |
def labels(self) -> List[Label]:
if any([lnu for lnu in self._labelNeedsUpdate.values()]):
self._updateLabels()
return sorted(self._labels, key=str) |
/**
* Represents a JavaScript expression for array literals.
*/
public final class JsArrayLiteral extends JsLiteral {
private final List<JsExpression> exprs = Lists.newArrayList();
private boolean internable = false;
public JsArrayLiteral(SourceInfo sourceInfo, Iterable<JsExpression> expressions) {
super(sourceInfo);
Iterables.addAll(this.exprs, expressions);
}
public JsArrayLiteral(SourceInfo sourceInfo, JsExpression... expressions) {
this(sourceInfo, Arrays.asList(expressions));
}
public List<JsExpression> getExpressions() {
return exprs;
}
@Override
public boolean equals(Object that) {
if (that == null || this.getClass() != that.getClass()) {
return false;
}
JsArrayLiteral thatLiteral = (JsArrayLiteral) that;
return internable == thatLiteral.internable && exprs.equals(thatLiteral.exprs);
}
@Override
public NodeKind getKind() {
return NodeKind.ARRAY;
}
@Override
public int hashCode() {
return exprs.hashCode() + 17 * (internable ? 0 : 1);
}
@Override
public boolean hasSideEffects() {
for (JsExpression expr : exprs) {
if (expr.hasSideEffects()) {
return true;
}
}
return false;
}
@Override
public boolean isBooleanFalse() {
return false;
}
@Override
public boolean isBooleanTrue() {
return true;
}
@Override
public boolean isDefinitelyNull() {
return false;
}
@Override
public void traverse(JsVisitor v, JsContext ctx) {
if (v.visit(this, ctx)) {
v.acceptWithInsertRemove(exprs);
}
v.endVisit(this, ctx);
}
/**
* Some array literals are not mutated and hence internable.
*/
@Override
public boolean isInternable() {
return internable;
}
public void setInternable() {
internable = true;
}
} |
Mike D’Antoni was officially named new coach of the Houston Rockets, and he has brought Jeff Bzdelik and Roy Rogers, two defensive-minded coaches, to help. Last season, Houston finished as the sixth-worst defense in the league by allowing 106.4 points per game and opponents shot 45.9 percent against them, slightly above the league average of 45.2 percent.
We chatted with Bzdelik on Wednesday about how he can improve the Rockets' defense.
What attracted you to this job?
Bzdelik: First of all, I’m going to echo everything Mike said and Mr. [Leslie] Alexander and Daryl [Morey]: Everybody is aligned as to how to play. I like playing that way. Mike is brilliant enough to say, "Houston has won and they got a great player [James Harden] and other really, really good players." Everybody is committed and that’s a great thing, so it’s just a great opportunity and Houston is a great city to live in. It really is all those things. When the opportunity was presented to me, it was a no-brainer for my wife and I.
How do you improve defensively in general?
Bzdelik: We have competitive guys who want to win. If you look at the last 10 NBA championship teams, nine of them have finished both in the top 10 in offense and defense. So they know unless they’re really not walking the talk, you've got to be committed on both ends. When players are really comfortable offensively and feel really good, that feeds into their defensive energy in a positive way. When they’re sideways offensively they can be sideways defensively, very easily. Unfortunately it shouldn’t be that way, but it is that way.
What’s your main philosophy on defense?
Bzdelik: All five guys have to be committed. It takes all five guys to get a stop. The goal is to have teams take tough, contested [2-pointers] outside the paint and inside the arc. In order to do that, you have to have great defensive transition because we can’t be one-way runners. Take away easy baskets so they can’t get a coast-to-coast layup, they can’t get a layup off one pass or two passes. They got to have more than two passes and get that ball swung from one side to the other side, and players clearly have to know the scheme and be held accountable, as we are held accountable by all of you.
James Harden took a lot of heat from the media for his defensive play. Is he a better defender than what we think?
Bzdelik: He can defend, as all of them can when they want to, and that goes back to everybody needs to be committed and there needs to be a trust. You can be selfish on defense like you can be selfish on offense by not being where you’re supposed to be to help your teammate or communicate.
Can Clint Capela be the anchor on defense?
Bzdelik: He’s got a chance to be really special because he plays with great energy. He’s light on his feet, he seems intelligent and he can guard multiple positions. |
/*
create rand unsign 64 bit by single number
*/
func RandByUInt64(n int64) (result int64) {
s := rand.NewSource(n)
result = rand.New(s).Int63()
return
} |
package coinbase
import (
"encoding/json"
"io/ioutil"
)
type Time struct {
ISO string `json:"iso"`
Epoch float64 `json:"epoch"`
}
// https://developers.coinbase.com/api/v2#time
type timeService struct {
client *CoinbaseClient
}
// https://docs.pro.coinbase.com/#time
type timeProService struct {
client *CoinbaseProClient
}
// https://developers.coinbase.com/api/v2#get-current-time
func (time *timeService) GetCurrentTime() Time {
endpoint := time.client.baseURL + "/time"
res, _ := time.client.client.Get(endpoint)
data, _ := ioutil.ReadAll(res.Body)
payload := struct {
Data Time `json:"data"`
}{}
_ = json.Unmarshal(data, &payload)
return payload.Data
}
// https://docs.pro.coinbase.com/#time
func (time *timeProService) GetCurrentTime() Time {
endpoint := time.client.baseURL + "/time"
res, _ := time.client.client.Get(endpoint)
data, _ := ioutil.ReadAll(res.Body)
var payload Time
_ = json.Unmarshal(data, &payload)
return payload
}
|
/**
* This class defines a MinHeap implementation using an ArrayList (based on Heap class in Y Daniel Liang's Introduction
* To Java Programming 10th Edition Chapter 23)
*
* @author Drew Hans
* @param <E>
*/
public class MinHeap<E extends Comparable> {
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
/**
* Create an empty MinHeap
*/
public MinHeap() {
}//end MinHeap constructor
/**
* Create a MinHeap from an array of objects
*
* @param objects
*/
public MinHeap(E[] objects) {
for (int i = 0; i < objects.length; i++) {
add(objects[i]);
}
}//end MinHeap constructor
/**
* Add a new object into the heap
*
* @param newObject
*/
public final void add(E newObject) {
list.add(newObject); // Append to the heap
int currentIndex = list.size() - 1; // The index of the last node
while (currentIndex > 0) {
int parentIndex = (currentIndex - 1) / 2;
// Swap if the current object is greater than its parent
if (list.get(currentIndex).compareTo(list.get(parentIndex)) > 0) {
E temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
} else {
break; // the heap has been balanced
}
currentIndex = parentIndex;
}
}//end add method
/**
* Remove the root from the heap
*
* @return the removedObject
*/
public final E remove() {
if (list.isEmpty()) {
return null;
}
E removedObject = list.get(0); // get the object at top of MinHeap
list.set(0, list.get(list.size() - 1)); // change list size
list.remove(list.size() - 1); // remove the object from the list
// balance the heap
int currentIndex = 0;
while (currentIndex < list.size()) {
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
// Find the maximum between two children
if (leftChildIndex >= list.size()) {
break; // the heap has been balanced
}
int maxIndex = leftChildIndex;
if (rightChildIndex < list.size()) {
if (list.get(maxIndex).compareTo(
list.get(rightChildIndex)) < 0) {
maxIndex = rightChildIndex;
}
}
// Swap if the current node is less than the maximum
if (list.get(currentIndex).compareTo(
list.get(maxIndex)) < 0) {
E temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
} else {
break; // the heap has been balanced
}
}
return removedObject;
}//end remove method
/**
* Get the number of nodes in the tree
*
* @return
*/
public int getSize() {
return list.size();
}//end getSize method
} |
E-cadherin maintains the undifferentiated state of mouse spermatogonial progenitor cells via β-catenin
Background Cadherins play a pivotal role in facilitating intercellular interactions between spermatogonial progenitor cells (SPCs) and their surrounding microenvironment. Specifically, E-cadherin serves as a cellular marker of SPCs in many species. Depletion of E-cadherin in mouse SPCs showed no obvious effect on SPCs homing and spermatogenesis. Results Here, we investigated the regulatory role of E-cadherin in regulating SPCs fate. Specific deletion of E-cadherin in germ cells was shown to promote SPCs differentiation, evidencing by reduced PLZF+ population and increased c-Kit+ population in mouse testes. E-cadherin loss down-regulated the expression level of β-catenin, leading to the reduced β-catenin in nuclear localization for transcriptional activity. Remarkably, increasing expression level of Cadherin-22 (CDH22) appeared specifically after E-cadherin deletion, indicating CDH22 played a synergistic effect with E-cadherin in SPCs. By searching for the binding partners of β-catenin, Lymphoid enhancer-binding factor 1 (LEF1), T-cell factor (TCF3), histone deacetylase 4 (HDAC4) and signal transducer and activator 3 (STAT3) were identified as suppressors of SPCs differentiation by regulating acetylation of differentiation genes with PLZF. Conclusions Two surface markers of SPCs, E-cadherin and Cadherin-22, synergically maintain the undifferentiation of SPCs via the pivotal intermediate molecule β-catenin. LEF1, TCF3, STAT3 and HDAC4 were identified as co-regulatory factors of β-catenin in regulation of SPC fate. These observations revealed a novel regulatory pattern of cadherins on SPCs fate. Supplementary Information The online version contains supplementary material available at 10.1186/s13578-022-00880-w.
Introduction
Spermatogonial stem cells (SSCs) are the foundation of spermatogenesis, which are able to differentiate into functional sperms via multiple steps in testis. In their differentiation hierarchies, A s , A pr and A al spermatogonia are referred to as the undifferentiated populations, and are nominated as spermatogonial progenitor cells (SPCs) . A transcription suppressor promyelocytic leukemia zinc finger (PLZF) is identified as a specific SPC marker , and further confirmed to be an essential factor for SPCs maintenance , through binding to and inhibiting many differentiation associated genes such as c-Kit , Sall4 and Redd1 . Based on these findings, our recent study successfully identified additional target genes of PLZF that are associated with SPC differentiation, including Stra8, Sohlh2 and Dmrt1 . SPCs fate is regulated by their microenvironment through interacting with neighboring cells. And many membrane or transmembrane proteins, such as cadherins, integrins, claudins, are intimately associated with intra-and intercellular functions such as adhesion, binding, recognition and signal transduction . Among them, E-cadherin acts as an important molecule involved in structural and signaling-related functions in epithelial cells, SSCs included , and has been characterized as a SPC marker . As a transmembrane molecule, E-cadherin is involved in binding of SPCs to the niche and regulating SPC's fate . Our recent study revealed that E-cadherin on SPCs could interact with ITGB1 on Sertoli cells . However, evidence from conditional knockout of E-cadherin in SSCs showing no impact on SSCs homing after transplantation cannot lead to the conclusion that E-cadherin is ineffective for SPCs, due to the fact that SPCs are enriched with other cadherins which could compensate for E-cadherin loss . Nevertheless, germline specific deletion of E-cadherin at embryonic stage leads to germ cell loss caused by apoptosis, indicating that a pivotal role of E-cadherin in gonad development . Here, we were wondering if E-cadherin contributed to the regulation of SPC's fate, especially as a binding partner of β-catenin, another pivotal player in the proliferation of SPCs . Interestingly, evidence from another group suggested that β-catenin was more likely to promote differentiation of SPCs by using a β-catenin overexpression model. In their case, the role of ß-catenin was explored in a more Wnt signaling regulatory-related way. More observations showed that hyperactivation of Wnt/β-catenin signaling in gonocyte , spermatogonial cell line or in vivo resulted in reduced cell proliferation and viability, indicating an enhanced exhaustion of SSCs pool. As a multiple-role molecule, β-catenin was proven to possess structural and signalingassociated functions, via interacting with many signaling pathways (Wnt, JAK-STAT, etc.) and transcriptional factors (TCF family, HDAC family, etc.). These complicated interactions shadow our understanding of the molecular mechanism of β-catenin, especially in the regulation of stem cell fate . Thus, further study is required to unveil the comprehensive mechanism of β-catenin in SPCs.
β-catenin functions as a pivotal intermediate molecule in Wnt signaling pathway . However, its binding to cadherins as a structural component can also play a role as co-transcription factor in a dynamic pattern . Notably, β-catenin relies on a mediator to convey its regulatory effect on the expression of target genes due to a lack of DNA binding domain . In addition to the well-known TCF family, β-catenin could cooperate with HDAC family members as well. Some HDACs are found to be involved in functions of germline, for instance the expression levels of Hdac2, Hdac6, and Sirt1 increased, while Hdac8, Hdac9 and Sirt4 decreased, during SSCs differentiation or aging . Moreover, a study reported that HDAC4 bound to PLZF to enhance the repression of differentiation . Thus, it might be interesting to look into the interplay between β-catenin and HDAC in SPCs.
Here, the role of E-cadherin in SPCs was studied using conditional knockout mice and in vitro cell culture models. The dynamic role of β-catenin in regulating SPCs fate was identified, and the interaction regarding downstream genes or cooperators was further analyzed. Briefly, E-cadherin was identified as an essential transmembrane molecule to maintain undifferentiated state of SPCs, and CDH22 played a similar role as E-cadherin and might compensate for E-cadherin loss. Deletion of E-cadherin disturbed the dynamic balance of β-catenin in structural maintenance, protein degradation and nuclear localization, leading to a reduced β-catenin expression and promoted SPCs differentiation. Moreover, the interaction among β-catenin, PLZF and HDAC4 was discussed in SPCs. These observations indicated a new regulatory pattern of SPCs differentiation.
E-cadherin and β-catenin were co-expressed in undifferentiated spermatogonia
A subpopulation of undifferentiated spermatogonia, SPCs, was identified as PLZF + cells residing in the first layer in seminiferous tubules and found to regulate SPCs fate (Fig. 1A). Since the expression of E-cadherin and β-catenin could be detected in the same population ( Fig. 1B and C), we postulated that both molecules might be involved in modulating SPCs fate. To study the role of E-cadherin, SPCs were purified using THY1.2 + MACS from neonatal mouse testis, and grape-like clones were observed after 2 passages on MEF feeder layers (Fig. 1D), which were able to be stably maintained in vitro for more than 30 passages . The expression of SPC markers, including Plzf, Cdh1, Gfra1 and Id4, was examined to characterize their identities using RT-PCR (Fig. 1D). Moreover, IF staining against PLZF, E-cadherin, β-catenin, Axin2 and ZO-2 further confirmed that SPCs were notably enriched (Additional file 1: Fig.S1 A-E). Subsequently, co-IF staining demonstrated an overlap of E-cadherin + and PLZF + /β-catenin + populations ( Fig. 1E and F). In all, these observations confirmed a co-expression pattern of E-cadherin and β-catenin both in vivo and in vitro, demonstrating that E-cadherin in combination Fig. 1 Expression of E-cadherin and SPC markers in mouse testis and isolated SPCs. The expression of PLZF (A), E-cadherin (B) and β-catenin (C) was detected in the testis of 42-day old mouse using IHC. The morphology of purified SPCs on MEF feeder layer was exhibited, and expression of SPCs markers was determined using RT-PCR (1.testis, 2.SPCs, 3.H 2 O) (D). Co-IF staining was employed to detect the expression of PLZF and E-cadherin (E green: PLZF, red: E-cadherin, blue: DAPI), or β-catenin and E-cadherin (F red β-catenin, green E-cadherin, blue DAPI) in purified SPCs. Expression of E-cadherin was detected in SPCs transfected with scrambled (G E-cadherin, H. DAPI, I. Merge) or E-cadherin siRNA (J E-cadherin, K DAPI, L Merge) was exhibited 72 h post transfection using IF staining. The number of SPCs was statistically calculated (M) (10 views of ×200 were randomly selected). The expression of E-cadherin, PLZF, GFRA1, c-Kit and β-tubulin was determined in scrambled or E-cadherin siRNA transfected SPCs using Western blot, n=3 (N), and was statistically calculated (O). The interaction of E-cadherin and β-catenin in SPCs was detected using co-IP (P). Scale bar = 20 μm, data represents mean ± standard deviation (SD), *p<0.05, **p<0.01 of canonical Wnt signaling pathway might play a role in SPCs.
Differentiation markers up-regulated after disturbing E-cadherin expression in SPCs
To better understand the role of E-cadherin, RNAi was employed to disturb the expression of E-cadherin in SPCs. IF staining revealed the efficient decrease of E-cadherin expression in primary SPCs (Fig. 1J-L), compared to scramble siRNA group (Fig. 1G-I). Although neither obvious morphological change (data not shown) nor difference in the number of SPCs was observed 72 h posttransfection (Fig. 1M), the expression of SPC markers was altered (Fig. 1N, O). Reduced PLZF and GFRA1 along with the increased differentiation marker c-Kit suggested that the disturbance of E-cadherin might jeopardize the undifferentiated state of SPCs under in vitro culture. The binding of E-cadherin to β-catenin was further confirmed in SPCs by co-IP (Fig. 1P). Though E-cadherin knockout maintained the capacities of SPC homing and spermatogenesis , our observations revealed a possible influence of E-cadherin on SPCs fate. Therefore, a better understanding of the regulatory mechanism of E-cadherin in SPCs could be greatly valued, especially its interaction with β-catenin.
Conditional knockout of E-cadherin in germline promoted differentiation at protein levels
To further characterize the effect of E-cadherin deficiency on SPCs fate, LoxP-Cre system was employed to conditionally knockout E-cadherin in mouse SPCs ( Fig. 2A). Germline-specific E-cadherin knockout mice (E-cadherin L/L ;Ddx4-Cre + ) were generated by mating E-cadherin floxed females with E-cadherin L/+ ;Ddx4-Cre + males (Fig. 2B). Testes from 3-month E-cadherin L/ L ;Ddx4-Cre + males were harvested for histological analysis, and germ cells at different differentiation stages could be easily distinguished ( Fig. 2C-F), indicating that E-cadherin deficiency neither affected seminiferous tubule structure nor disturbed spermatogenesis. However, when evaluating the expression of undifferentiated spermatogonia marker PLZF using IHC, we noticed that the number of PLZF + cells in E-cadherin L/L ;Ddx4-Cre + testis remarkably decreased compared to control group ( Fig. 2G-I), and the number of differentiating population represented by c-Kit staining intensively increased in E-cadherin deficient tubules ( Fig. 2J-L). These observations demonstrated that E-cadherin might inhibit SPCs differentiation. To obtain a better understanding, testes from E-cadherin L/L and E-cadherin L/L ;Ddx4-Cre + littermates were collected for evaluating the expression of self-renewal and differentiation markers using Western blot. Consistently, E-cadherin deficient testes expressed decreasing level of SPC markers such as GFRA1, PLZF and ITGA6, and increasing expression level of differentiation marker c-Kit compared to control group, respectively ( Fig. 2M and N). Noteworthy, expression of AXIN2 and GSK3-β was up-regulated ( Fig. 2M and N), suggesting that E-cadherin deficiency possibly enhanced the activation of β-catenin degradation complex. Meanwhile, the expression of PCNA, BAX and BCL-2 was not affected in E-cadherin deficient group ( Fig. 2M and N), implying that E-cadherin loss promoted differentiation, but not proliferation or apoptosis, in testis.
Subsequently, we explored the impact of E-cadherin deficiency on β-catenin's translocation into nucleus. IF staining of β-catenin in E-cadherin L/L and E-cadherin L/ L ;Ddx4-Cre + testes revealed limited nuclear distribution of β-catenin, while no remarkable difference observed between wild type and E-cadherin deficient SPCs ( Fig. 2O and P). Likewise, strong β-catenin signal was restricted to cytoplasm of purified SPCs (Fig. 2Q), we postulated that β-catenin was mainly distributed in cytoplasm in both genotypes. Collectively, E-cadherin could play an important role in SPCs differentiation by modulating both differentiation and SPC marker expression.
The impact of E-cadherin deficiency on the fates of β-catenin in SPCs
A decreased β-catenin expression in E-cadherin knockout SPCs compared with WT controls might be detected because of two possibilities: 1. E-cadherin knockout led to reduced expression of β-catenin; 2. E-cadherin knockout enhanced the degradation of β-catenin. To test these hypotheses, we first compared the expression of β-catenin at mRNA level in SPCs from both genotypes, and noticed an attenuated β-catenin expression in E-cadherin knockout SPCs (Fig. 3A). Subsequently, different phosphorylated forms of β-catenin were determined. A β-catenin antibody targeting phosphorylation at Ser33/Ser37/Tyr41 was used to examine the degradation of β-catenin, and the declined phosphorylation implied that E-cadherin knockout reduced the degradation of β-catenin in SPCs ( Fig. 3B and C). Interestingly, phosphorylation at Ser675 representing a transcriptional active form of β-catenin, was declined in E-cadherin knockout SPCs as well ( Fig. 3B and C), indicating that E-cadherin deficiency down-regulated the transcriptional activity of β-catenin. Furthermore, a sustained effect on β-catenin expression and phosphorylation was observed when E-cadherin got deleted in cultured SPCs with CRISPR/Cas9 (Fig. 3D, E). The expression of PCNA and BAX was not changed, while expression of anti-apoptosis protein BCL-2 was downregulated. Thus, we proposed that E-cadherin might play a role in anti-apoptosis, since the ratio of BCL-2/ Fig. 2 Expression of E-cadherin and SPC markers in germline-specific E-cadherin knockout mice. A schematic illustration of conditional knockout of E-cadherin driven by Ddx4-Cre in germ cells (A). The goal mice with E-cadherin germline specific knockout were generated by mating E-cadherin floxed and Ddx4-Cre mice (B). The histology of testes from 90-day old E-cadherin L/L (C) and E-cadherin L/L ;Ddx4-Cre + mice (D) was exhibited. The expression of E-cadherin, PLZF and c-Kit in testes from 90-day old E-cadherin L/L (E E-cadherin, G PLZF, J c-Kit) and E-cadherin L/L ;Ddx4-Cre + (F E-cadherin, H. PLZF, K c-Kit) were determined using IHC. The relative ratio of PLZF + (I) and c-Kit + (L) cells per seminiferous tubule in testes from both genotypes was statistically analyzed (for each genotype, 15 tubules from 3 testes were counted). The expression levels of E-cadherin, β-catenin, GSK3-β, AXIN2, PLZF, GFRA1, ITGA6, HDAC4, c-Kit, SOHLH2, CDH22, PCNA, BAX, BCL-2 and β-tubulin were determined in testes from both genotypes at 90-day using Western blot, n = 3 (M), and was statistically analyzed (N). Expression of β-catenin in testes from 90-day old E-cadherin L/L (O) and E-cadherin L/L ;Ddx4-Cre + mice (P) and newly isolated SPCs (Q) was determined using IF. Scale bar = 20 μm, data represent as mean ± SD *p < 0.05; **p < 0.01 BAX reduced after E-cadherin loss. Considering that E-cadherin deletion increased Axin2 and GSK-3β expression in testes (Fig. 2M, N), we concluded that E-cadherin knockout down-regulated β-catenin expression, resulting in a reduced transcriptional activity of β-catenin.
CDH22 co-regulates β-catenin with E-cadherin in SPCs
In addition to E-cadherin, we were also interested in other types of cadherins expressed in SPCs, particularly CDH22, a key signal molecule regarding SPCs fate . In rats, Cdh22 encodes two splicing proteins. The shorter one lacking catenin binding domain is associated with SSCs self-renewal through interacting with JAK-STAT and PI3K-AKT signaling pathways, while the longer one contains catenin binding domain . Notably, Cdh22 in mouse ovary only encodes the latter one, which interacts with β-catenin to regulate female germline stem cells (FGSCs) self-renewal . Here, we wondered whether CDH22 could compensate for E-cadherin loss in SPCs. As shown in Fig. 3F, CDH22 was detected in SPCs residing in basal membrane and freshly isolated SPCs. Western blot results revealed that only one band was detected in mouse SPCs (Fig. 3G), which was consistent with that of mouse FGSCs. Subsequently, we disturbed Cdh22 expression in SPCs and confirmed the reduced phosphorylation levels of S33/S37/T41 and S675 of β-catenin (Fig. 3H, I), and decreased expression of anti-apoptotic protein BCL-2 ( Fig. 3H, I), indicating that CDH22 was positively correlated with transcription activity of β-catenin and anti-apoptosis capacity in SPCs, similar to E-cadherin. Also, simultaneous transfection of Cdh1 and Cdh22 siRNA into SPCs aggravated the decline of β-catenin expression ( Fig. 3J and K), suggesting that CDH22 might regulate β-catenin expression in SPCs along with E-cadherin in a synergistic manner. More importantly, the binding of CDH22 and β-catenin was confirmed using co-IP (Fig. 3L), indicating a direct interaction between CDH22 and β-catenin in SPCs. Based on these observations, we postulated that β-catenin could be a critical intermediate molecule interacting with CDH1 and CDH22 to regulate SPCs fate.
Identification of ß-catenin co-regulatory factors in SPCs
Due to lack of DNA binding domain, β-catenin needs to bind to TCF family including LEF1, TCF1, TCF3 and TCF4 in mouse and human to regulate target gene expression . Using RT-PCR, Lef1, Tcf3 and Tcf4 mRNA were detected in SPCs (Fig. 4A). Interestingly, LEF1 and TCF3 were restricted to SPCs residing in the basal membrane, while TCF4 was broadly distributed in undifferentiated spermatogonia, differentiating spermatogonia and mature spermatocytes (Fig. 4B). IF staining confirmed the expression of LEF1, TCF3 and TCF4 in purified SPCs (Fig. 4C-E), and co-IP assays demonstrated the binding of β-catenin to LEF1 and TCF3, but not TCF4 in SPCs (Fig. 4F). As shown in Fig. 4G, β-catenin knockdown in SPCs showed no impact on the expression of LEF1, TCF3 and TCF4. On the other hand, though decreased expression of LEF1 led to no significant change in β-catenin expression, a down-regulation of PLZF was observed (Fig. 4H). Considering β-catenin combined with LEF1 regulates Plzf expression in innate memory-like CD8 thymocytes , a similar regulatory pattern might exist in SPCs to maintain the undifferentiated state. Also, we hypothesized that β-catenin displaced the suppressor TCF3 from self-renewal associated genes (such as Plzf). Conversely, knockdown of Tcf3 caused up-regulation of PLZF (Fig. 4I), suggesting opposite roles of LEF1 and TCF3 in regulating SPCs fate by cooperating with β-catenin. Our current finding raises up a question that whether β-catenin displaces its suppressor TCF3 from binding to self-renewal associated genes (such as Plzf) to maintain SPCs undifferentiated state, which requires further investigation.
Validation of co-regulatory role of HDAC4 with PLZF in SPCs
In addition to TCF family, β-catenin is able to cooperate with other co-factors as well, such as SOX1, SOX2 and KLF4 . Among them, we were specifically interested in HDAC family, known as pivotal partners in regulating gene expression , especially in (See figure on next page.) Fig. 3 The expression of β-catenin was regulated by E-cadherin knockout in SPCs. Expression levels of E-cadherin, β-catenin, Axin2, Plzf and c-Kit mRNA were detected in SPCs from E-cadherin L/L and E-cadherin L/L ;Ddx4-Cre + mice using real time-qPCR (A). The expression levels of E-cadherin, β-catenin, and β-catenin phosphates (S33/S37/T41 and S675) were detected in SPCs from both genotypes (B) using Western blot, and were statistically analyzed (C). The expression levels of E-cadherin, β-catenin, and β-catenin phosphates (S33/S37/T41 and S675), PCNA, BAX, BCLL-2 and β-tubulin in E-cadherin deleted SPCs mediated CRISPR/Cas9 were detected using Western blot, n=3 (D), and were statistically analyzed (E). CDH22 was detected in 20-day mouse testes (left) and freshly isolated SPCs from 5-day mice (right, top: CDH22, down: DAPI) (F). A single band of CDH22 was detected in mouse testis and SPCs (G). Phosphorylation at S33/S37/T41 and S675 of β-catenin, and expression levels of CDH22, β-catenin, PCNA, BAX, BCL-2 and β-tubulin were detected in SPCs transfected with scramble or E-cadherin siRNA (H), and were statistically analyzed (I). Expression of E-cadherin, CDH22 and β-catenin in SPCs transfected with scramble, E-cadherin siRNA, or E-cadherin siRNA plus Cdh22 siRNA was evaluated with Western blot, n=3 (J), and were further statistically analyzed (K). The binding of CDH22 and β-catenin was verified with co-IP (L). Scale bar = 20 μm, data represent as mean ± SD, *p<0.05, **p<0. germline . Consequently, we wondered if HDAC was able to directly bind to β-catenin as a cooperator. Indeed, purified SPCs expressed Hdac1-9 mRNA (Fig. 5A), and HDAC4 was predominately expressed in SPCs residing in the basal membrane of seminiferous tubules (Fig. 5B). In purified SPCs, HDAC4 signal was highly overlapped with PLZF in the nucleus (Fig. 5C-G) demonstrating the co-localization of HDAC4 and PLZF. Subsequently, co-IP assay revealed the binding of β-catenin and HDAC4 in SPCs, as well as STAT3 (Fig. 5H), another key transcription factor for SSCs self-renewal and differentiation via cooperation with the β-catenin/TCF4 complex . To understand the interaction between β-catenin and HDAC4, β-catenin knockdown was performed in SPCs, resulting in a slightly increased expression of c-Kit and BCL-2, as well as decreased GFRA1, PLZF, Cyclin D1, HDAC4 and BAX (Fig. 5I and J), implying differentiation was enhanced, but proliferation and apoptosis were declined in SPCs. This observation is consistent with a previous study showing that hyper-proliferation is accompanied with enhanced apoptosis in Wnt hyperactive gonocytes . Meanwhile, RNAi assay was employed to reveal the role of HDAC4 in SPCs, and the results showed that the growth condition of SPCs transfected with Hdac4 siRNA was not remarkably altered during 48 h post transfection compared with control (data not shown), but the expression of PLZF was suppressed, and the expression of differentiation markers including c-Kit, STRA8 and SOHLH2, were up-regulated ( Fig. 5K and L). Notably, Hdac4 loss led to down-regulation of PCNA and AXIN2, without affecting apoptosis (Fig. 5K and L), suggesting that HDAC4 is more likely a regulator to maintain SPCs self-renewal, and is probably associated with canonical Wnt signal pathway. Collectively, these observations indicated a positive correlation between HDAC4 and β-catenin expression in SPCs, which might synergistically regulate SPCs differentiation, proliferation or apoptosis. Thus, we proposed that β-catenin combined with HDAC4 in SPCs to maintain the undifferentiation state and proliferation capacity. Similarly, STAT3 might be involved in the regulation of differentiation and proliferation in SPCs, since disturbance of Stat3 also led to decreasing PLZF and PCNA, and increasing STRA8 ( Fig. 5M and N). Moreover, STAT3 in SPCs seems to maintain β-catenin activity, since Stat3 loss caused decreased AXIN2 (Fig. 5M and N). The increased value of BCL-2/BAX implied that Stat3 loss strengthened the anti-apoptosis capacity in SPCs, further confirming that the positive correlation of proliferation and apoptosis in SPCs. Overall, these observations suggested that HDAC4 and STAT3 could be potential collaborators of β-catenin that synergically regulated SPCs fate.
HDAC4 directly repressed c-Kit expression through deacetylation in SPCs
Since HDAC family members could cooperate with transcription factors , we investigated whether HDAC4 bound to differentiation suppressor PLZF in SPCs. Co-IP assay confirmed the binding of HDAC4 to PLZF in SPCs (Fig. 6A), suggesting HDAC4 might be a co-suppressor of PLZF in the inhibition of SPCs differentiation. Considering that HDAC4 also bound to β-catenin (Fig. 5H), we checked whether HDAC4 could form a complex with β-catenin and PLZF in SPCs. Co-IP showed no direct binding between β-catenin and PLZF (Fig. 6B), suggesting that HDAC4 might bind to β-catenin and PLZF separately. Although knockdown of β-catenin or Hdac4 led to SPCs differentiation ( Fig. 5I-L), it was not clear how the β-catenin-HDAC4 complex involved in this biological process, nor the role of HDAC4-PLZF complex. As a type of ubiquitous deacetylase, HDAC family members generally bind to target gene to repress gene expression through modulating its acetylation level , and our previous work revealed that PLZF could repress SPCs differentiation via direct binding to the promoter regions of c-Kit and Stra8 . Thus, dual luciferase report assay was performed to test whether HDAC4 could regulate c-Kit or Stra8 expression through directly binding to their promoter regions. The c-Kit promoter region from − 1846 bp to − 6 bp was subcloned into pGL3 basic plasmid, and then transfected into HEK 293T cells with the recombinant HDAC4 and/or PLZF overexpression plasmids. As shown in Fig. 6C, the relative luciferase activity was remarkably declined in pGL3-c-Kit when co-transfected with Plzf, and further decreased in Hdac4 co-transfected group. Surprisingly, simultaneous co-transfection of Plzf and Hdac4 overexpression plasmids showed no further suppression of c-Kit activity compared to Hdac4 transfected group, which may probably due to a more significant inhibitory effect of HDAC4 on c-Kit than PLZF. Similarly, the inhibition effect was also observed on Stra8 (Fig. 6D), further confirmed the co-regulatory mechanism of HDAC4 on SPCs differentiation. Considering that HDAC4 overexpression demonstrated more efficient Hdac4), n=3. Acetylation lysine IP coupled with Western blot was used to detect the impact of HDAC4 on c-Kit acetylation (E). A schematic illustration described the regulatory mechanism that HDAC4 could directly bind to c-Kit to suppress its expression via deacetylation (F). The regulatory pattern of cadherins on SPCs fate was schematically summarized (G). Data represent as mean ± SD *p < 0.05; **p < 0.01 suppression of c-Kit and Stra8 than PLZF, we hypothesized that the deacetylation level might be dependent on the gene transcription activity. Therefore, we measured acetylation levels of c-Kit and STRA8 using acetylation lysine immunoprecipitation coupled with Western blot analysis against c-Kit or STRA8. The acetylation levels of c-Kit and STRA8 in Hdac4 knockdown group remarkably increased compared to that of control group (Fig. 6E). Thus, we postulated that HDAC4 synergically suppressed SPCs differentiation with PLZF through direct binding to differentiation associated genes (such as c-Kit and Stra8) and regulating acetylation (Fig. 6F).
Collectively, a putative regulatory pattern of E-cadherin on SPCs fate through β-catenin and HDAC4 is summarized (Fig. 6G). E-cadherin plays structural and signaling roles in SPCs. Proliferation, differentiation and apoptosis are inhibited since SPCs are attached in the niche by E-cadherin. Under the physiological condition, β-catenin is dynamically balanced among three statuses: binding to cadherins anchored at cell membrane, residing in cytoplasm and ultimately going into degradation by APC, or translocation into nucleus for transcriptional activity. In the nucleus of SPCs, β-catenin interacts with TCF/LEF, HDAC4 or STAT3 to inhibit differentiation and regulate proliferation. Based on our observations, deficiency of E-cadherin reduces cellular contents of β-catenin and its phosphorylation level, resulting in less β-catenin for degradation and nuclear localization. Consequently, the downstream targets associated with undifferentiation state of SPCs are disturbed. Meanwhile, the synergetic effect on inhibition of differentiation genes with HDAC4 or STAT3 is attenuated, to further promote SPCs turning to differentiation state.
Discussion
So far, knockout assay serves as the gold standard in understanding the role of a specific gene. Unfortunately, it may not be sufficient to unmask the regulatory mechanism of E-cadherin and β-catenin in regulating SPCs fate due to their complex interactions. There have been some controversial observations reported , and the inconsistent results regarding the role of E-cadherin in SPCs maintenance might be due to the artifacts from different knockout models, or the time duration of E-cadherin deficiency lasted in SPCs.
The complicated interaction pattern between E-cadherin and Wnt signaling pathway shadows our understanding in regulation of SPCs fate. E-cadherin is negatively regulated by Wnt signaling , while Wnt ligands compete with E-cadherin in binding to β-catenin. Some of Wnt's downstream target genes negatively regulate cadherin genes , or further encode enzymes to destabilize membrane anchored β-catenin . Cleavage of E-cadherin by proteases led to release of β-catenin from cell membrane and enhanced its transcriptional activity . In reproductive organs specifically, a study showed no significant effect of E-cadherin knockout on SPCs homing and colonization . Using an adenovirus mediated gene delivery system E-cadherin knockout was triggered by virus injection, following by transient transplantation of harvested SPCs. Due to the relative low efficiency (41-75%) in gene deletion, the un-infected SPCs populations seemed to be able to reconstitute germ cell pool afterwards. In our study, LoxP-Cre system was employed to enable a conditional knockout, in which the germline specific deletion of E-cadherin started at embryonic stage driven by Ddx4-Cre. Compared to the in vitro deletion system mediated by adenovirus, Ddx4-Cre exerts deletion as early as embryonic day 15 with a more than 95% efficacy . Notably, although these mice were fertile, their fertility was slightly hampered by about 20%, and the number of PLZF + population was reduced in E-cadherin deletion group. Overall, these observations implied that E-cadherin might affect SPCs maintenance under physiological conditions. Also, the compensation effect of CDH22-β-catenin complex on SPC development predicted by Shinohara was verified in our study, indicating a delicate interaction between cadherins and Wnt signaling pathway.
To understand the biological role of E-cadherin in regulating SPCs fate, it's essential to focus on the two major functions of E-cadherin, the structural role and signaling role. In this study, we demonstrated that conditional disfunction of E-cadherin in germ cells promoted differentiation, but deletion of E-cadherin in SPCs through CRISPR/Cas9 not only gave rise to differentiation, but also reduced anti-apoptosis capacity. We proposed that the testicular microenvironment protected SPCs from apoptosis after E-cadherin deletion, and SPCs in vitro lacking of the protective function of niche were susceptible to apoptosis. However, further experimental evidence is required to verify this hypothesis.
More importantly, we revealed that loss of E-cadherin led to a remarkable decrease of β-catenin expression and a consequent decline of translocation to nucleus for transcription. As the pivotal molecule of cadherins and Wnt signal pathways, β-catenin is involved in the regulation of SPCs fate through transcriptional activity. HDAC4 and STAT3 were identified as two novel partners of β-catenin in this study, but the role of Wnt secreted by the niche is not determined, yet. Evidence demonstrated that Wnt5a secreted by feeder cells supports SSC self-renewal through β-catenin-independent pathway , and Wnt3a selectively stimulates proliferation of spermatogonia progenitors, rather than SSCs population . Thus, it's interesting to figure out the connection of secreted Wnt molecules in the niche and E-cadherin/β-catenin signaling pathway in SPCs fate in future study.
Moreover, the connection of β-catenin and SSCs fate is not fully revealed. Studies from different groups reported controversial functions of β-catenin: to promote the proliferation of PLZF + undifferentiated spermatogonia , or to stimulate the GFRA1 + SPCs population to differentiate into NGN3 + population . However, these observations are likely to be coherent. Knockout of β-catenin caused reduced number of PLZF + and c-Kit + cells in seminiferous tubules without significant difference in the number of GFRA1 + cells , indicating β-catenin mainly influenced the A al and differentiating spermatogonia, due to the fact that GFRA1 + cells primarily distributes in A s and A pr . Therefore, we postulated that the regulatory effect of β-catenin was more restricted to the proliferation of A al and differentiating spermatogonia (c-Kit + ) populations, rather than inducing SSCs differentiation. Meanwhile the other group claimed that β-catenin promoted differentiation of SPCs instead of affecting self-renewal, supported by the observation that deletion of β-catenin did not change the number of GFRA1 + cells, but rather affected differentiation from GFRA1 + to NGN3 + population, and activation of β-catenin led to GFRA1 + cells loss . Collectively, these observations suggest that β-catenin only regulates the fate of A al and differentiating spermatogonia. However, the ID4 + cells, a real SSCs enriched population , were not analyzed in both studies, so that it may not be sufficient to draw a solid conclusion about the interplay between β-catenin and SSCs fate. In our study, deletion of E-cadherin down-regulated expression of PLZF and GFRA1 in SPCs, indicating that E-cadherin affected the fate of SPCs, including A s , A pr and A al spermatogonia. We noticed that the PLZF + population highly overlapped with β-catenin + cells, and disturbance of either PLZF or β-catenin led to up-regulation of differentiation markers represented by c-Kit. Although no direct binding was detected between PLZF and β-catenin, they were found to bind to HDAC4 separately. Molecular assays further demonstrated that HDAC4 combined with β-catenin to suppress differentiation and promote proliferation, and synergically cooperated with PLZF to regulate acetylation of c-kit and Stra8 genes in SPCs.
These observations further unveil the complicated regulation pattern of SPCs fate mediated by E-cadherin/β-catenin, but there are still many questions need to be addressed. For example, deletion of E-cadherin in germline through LoxP-Cre system caused the down-regulation of β-catenin and up-regulation of AXIN2 , while disturbance the expression of β-catenin, HDAC4 or STAT3 in cultured SPCs inhibited the expression of AXIN2 . As the direct target gene of β-catenin/TCF4 , expression of Axin2 should be positively correlated to transcriptional activity of β-catenin. However, it is worth noting that that E-cadherin could simultaneously activate multiple signaling pathways , which might have some unknown connection with Axin2. Moreover, although β-catenin is the intermediate molecule of Wnt and E-cadherin signaling pathways, the target genes activated by Wnt ligands or by E-cadherin loss might be different. Thus, the underlying mechanism is worthy to be explored in future study. Another question is that the connection of β-catenin and other members of cadherin family in germline is largely unknown, yet. Undifferentiated SPCs and round spermatids are likely to be distinct Wnt signaling responders , since E-cadherin is mainly localized in SPCs. Here we postulated that the homeostasis of β-catenin might be achieved by binding to CDH22, similar to that of E-cadherin. Loss of E-cadherin or CDH22 passively reduced the level of β-catenin, which subsequently affected its nuclear expression associated with transcriptional regulation or interaction with co-factors, leading to SPCs differentiation. These observations introduced a novel regulatory pattern of β-catenin in SPCs and may be worth looking into. Interestingly, we noticed that inhibition of E-cadherin led to up-regulated CDH22, while knockdown of Cdh22 caused a slightly increase in E-cadherin expression (Fig. 3J, K). A compensation was speculated due to the important role of cadherins in SPC development. Notably, the binding of CDH22 and β-catenin was detected in mouse SPCs, confirming CDH22 possessed catenin binding domain in mouse SPCs, which is consistent with previous studies showing CDH22 in mouse FGSCs contained a catenin binding domain , but different from that in rat SSCs . In mouse FGSCs, CDH22 interacts with β-catenin, JAK2 and PI3K , indicating that CDH22 regulates FGSCs fate via multiple signal pathways. Here, β-catenin and CDH22 are possible interactive partners as well, but the complicated network needs to be further studied.
Conclusions
Collectively, we focused on the regulatory mechanism of E-cadherin in SPCs, demonstrating a potential regulatory pattern of SPCs maintenance mediated by E-cadherin and CDH22 through the pivotal intermediate molecule β-catenin, and revealed HDAC4 and STAT3 as the co-regulatory factors of β-catenin. We hope this study could share some novel insights into the cadherin and β-catenin-mediated SPCs fate regulation, while further research emphasizing on more detailed mechanism is acquired to enable a comprehensive understanding.
Animals
The CD-1 mice for experiments were supplied by Comparative Medicine Centre of Yangzhou University. The E-cadherin floxed mice (Cdh1 L/L ) were purchased from Jackson Lab. The protocols for breeding, mating, and genotyping of E-cadherin floxed mice were identical to previous study . All the procedures for animal experiments were approved by the ethical committee at Nanjing Agricultural University.
Isolation and culture of mouse SPCs
Testicular cells were extracted from 5 days postpartum mice generally following previous protocol . Briefly, testes were cut into small particles and followed by collagenase IV and trypsin digestion and centrifugation, and cell pellet was resuspended and were filtered with 70-µm cell filter and subsequently sorted using mouse THY-1.2 antibody coated magnetic beads (BD, Cat.551518). Thy1.2 + fraction was collected and cultured on mitotically inactivated mouse embryonic fibroblast (MEF) feeder layer at 37 ℃ with 5% CO 2 . Preparation of culture medium for SPCs and making of MEF feeder cells also followed with previous protocols. SPCs could be stably maintained on MEF feeder layers for more than 30 passages.
RNA extraction, RT-PCR and real time quantitative PCR (RT-qPCR)
For RNA extraction, tissue or cell samples were treated with TRNZol (Tiangen, DP405), and cDNA was reversed-transcripted using GoScript ™ Reverse Transcription System (Promega, A5001). RT-qPCR was performed using TB Green premix Ex Taq II (Takara, RR820A) according to the instruction. Reactions were run in triplicate in three independent experiments. The results were analyzed using the 2 −△△CT method, and housekeeping gene Gapdh was used to control the variability in expression levels. The information of primers was listed in Additional file 2: Table S1.
Immunohistochemistry (IHC) and immunofluorescence (IF)
The protocol for IHC is identical to previous study . Briefly, mouse testes were harvested and fixed in 4% neutral paraformaldehyde overnight, and subsequently dehydrated and embedded in paraffin. Histological sections were dewaxed and rehydrated in ethanol series, followed by microwave antigen retrieval in 0.01 M citrate (pH = 6.0) and methanol/H 2 O 2 treatment. After blocking with 5% goat serum, the slides were incubated with diluted primary and biotin labeled secondary antibodies, respectively. Streptavidin-HRP (Jackson Lab, 1:500) and DAB kit (Vector, sk4100) were used for visualization.
For cell IF staining, primary SPCs (within 5 passages) were carried out as described . For membrane protein, 10% Neutral Formalin without Triton X-100 was used for cell fix, while for cytoplasm or nuclear protein, Carnoy's fixative was used. Mouse IgG and rabbit IgG were used as negative control (Bioss, bs-0295PC, bs-0296PC). See antibodies information in Additional file 3: Table S2.
Construct of recombinant plasmids and transfection
For HDAC4 and PLZF overexpression plasmid, the open reading frame (ORF) of Hdac4 or Plzf were amplified and cloned into the pcDNA 3.1(+) plasmid, named as pcDNA 3.1(+)/Hdac4 or pcDNA3.1(+)/Plzf. For luciferase plasmid, c-Kit or Stra8 promoter gene sequences were amplified from genomic DNA using PCR, and inserted into the pGL3 basic plasmid with T4 DNA ligase (Takara, 2011A). There plasmids were nominated as pGL3 basic/c-Kit or pGL3 basic/Sta8 promoter. Both of amplified sequences in the recombinant plasmids were confirmed by sequencing. Primer sequences were listed in Additional file 2: Table S1.
RNAi and CRISPR/Cas9-mediated gene editing
For transfection and CRISPR/Cas9 assays, SPCs of 10-15 passages were used. SPCs were transfected with siRNA or plasmids using lipofectamine 3000 (Life technologies, L3000015) according to the manufacturer's instructions. The sequences of siRNA used in this study were listed in Additional file 4: Table S3.
Western blot (WB) and Co-Immunoprecipitation (Co-IP)
The protocols for WB and Co-IP are identical to previous study , and details are summarized below: Protein samples separated by SDS-PAGE were electro-transferred to PVDF membrane, which were subsequently blocked in 5% skim milk at room temperature for 1 h and then incubated with primary antibodies overnight at 4 ℃. After that, the membranes were rinsed in TBST followed by incubated with goat anti-mouse IgG-HRP (Santa Cruz, sc-2005) or mouse anti-rabbit IgG-HRP (Santa Cruz, sc-2357). Finally, samples were visualized using enhanced chemiluminescence (Tanon, 180-501). The information of antibodies was listed in Additional file 3: Table S2.
All procedures were conducted at 4 °C to preserve the protein integrity. Cells were lysed in lysis buffer (Beyotime, P0013) with gentle rocking. After centrifugation, the supernatant was collected and transferred to new tubes. Thereafter, the supernatant was incubated with the diluted antibodies overnight with a gentle rotation. Protein A/G agarose beads (Santa Cruz, sc-2003) were added into the supernatant and incubated for 3 h. Afterwards, beads were precipitated by centrifugation and washed five times with the cold lysis buffer. Finally, the pellet was resuspended in 1 × SDS loading buffer followed by western blot analysis.
For analysis of samples from mouse testes, three 90-day E-cadherin L/L mice and three 90-day E-cadherin L/L ;Ddx4-Cre + mice were sacrificed to collect testes, and each testis was separately treated for Western blot analysis. For cell samples, SPCs of 3-5 wells in 24-well plates were harvested (around 10^6) for analysis, and all experiments repeated at least three times.
Dual luciferase reporter assay
The dual luciferase reporter assay was performed in triplicate based on a previous protocol . Briefly, 0.25 μg of pGL3 basic/Kit promoter, 0.25 μg of empty pcDNA 3.1(+), pcDNA 3.1(+)/Hdac4 or pcDNA 3.1(+)/Plzf and 3 ng of an internal control Renilla luciferase assay vector pRL-CMV were transfected into HEK 293T cells. Cells were pre-seeded in 24-well plates at a concentration of 4 × 10 4 per well. Twenty-four hours post-transfection, luciferase activity was measured with a dual luciferase kit (Promega, E1910) by the Glomax ® 20/20 luminometer (Promega, E5311). Three wells were prepared for each experiment, and the experiments were repeated for three times. The results were calculated by normalizing the luciferase fluorescence value to that of renilla fluorescence.
Statistical analysis
For cell counting, sections or immunofluorescent visual fields were selected randomly. All the spermatogonia in 200× magnification view of microscope were counted and statistically analyzed, and the ratio of SPCs number in knockdown group/control group was defined as relative SPCs number. For IHC, the positive cells in twelve seminiferous tubules of slides were counted under microscope. The seminiferous tubules were randomly selected in discontinuous slides from three mice. Values plotted were expressed as mean ± standard deviation (SD). Statistical analysis was performed using Graphpad prism7 and Student's t-test, *p < 0.05; **p < 0.01. |
By Dana Gabriel
BlacklistedNews.com
In a move that went largely unnoticed, the U.S. government unveiled a new counter-narcotics strategy for the northern border which will work towards closer cooperation with Canada in the war on drugs. This includes both countries strengthening integrated cross-border intelligence sharing and law enforcement operations. Canada has also released a comprehensive counter-terrorism plan aimed at combating the threats of domestic and international violent extremism. The separate U.S.-Canada undertakings are both tied to the Beyond the Border deal and efforts to establish a North American security perimeter.
In January, the Obama administration announced the National Northern Border Counternarcotics Strategy. A press release by the Office of National Drug Control Policy (ONDCP) described how the plan seeks, “to reduce the two-way flow of illicit drugs between the United States and Canada by increasing coordination among Federal, state, local, and tribal enforcement authorities, enhancing intelligence sharing between counterdrug agencies, and strengthening ongoing counterdrug partnerships and initiatives with the Government of Canada and the Royal Canadian Mounted Police (RCMP).” Senator Charles Schumer proclaimed, “I pushed so hard for this strategy to be finalized because we have to immediately stop the flow of drugs from Canada into New York, and it’s going to take an inter-agency and international effort.” He added, “I’m pleased that this agreement lays the groundwork for Canadian and American law enforcement to work hand-in-glove to fight the drug trade.” Schumer has also endorsed the new cross-border action plan. In addition, he is pushing to establish a Northern Border Intelligence Center in Franklin County, NY to better coordinate efforts to fight drug smuggling and other cross-border criminal activities.
While commenting on the new plan to disrupt the flow of drugs over the U.S.-Canada border, ONDCP Deputy Director of State, Local and Tribal Affairs, Ben Tucker explained that, “By strengthening integrated cross-border law enforcement between our two countries, the Strategy supports a key area of cooperation outlined by President Obama and Prime Minister Harper in the Beyond the Border declaration.” In December of last year, the leaders issued the follow up Perimeter Security and Economic Competitiveness Action Plan. The deal focuses on addressing security threats early, facilitating trade, economic growth and jobs, integrating cross-border law enforcement, as well as improving infrastructure and cyber-security. As part of the agreement, both countries will, “create integrated teams in areas such as intelligence and criminal investigations, and an intelligence-led uniformed presence between ports of entry.” The U.S. and Canada continue to expand the nature and scope of joint law enforcement operations, along with intelligence collection and sharing.
The new northern border drug strategy also called for increasing judicial cooperation, improving information-sharing and extradition arrangements, as well as better coordinating cross-border undercover operations and investigations with Canada. It recommended working towards, “operational fusion with Canadian partners in interoperable communications, technology, and activities. The ability to integrate Canadian and U.S. technology, including sensors, videos, radio communications, and radar feeds, will permit automated sharing of timely information.” The document also argued that, "It is imperative that Canada and the United States work together to expedite the sharing of information from electronic communication service providers; and share information necessary to lay the foundation for intercepting internet and voice communications.” While various new measures are being put in place to thwart illegal drug, terrorist and other criminal activity, they could easily be used to target anyone else the government deems a threat.
The use of technology is emphasized throughout the report, “Technical collection capabilities and programs along the Northern border, such as thermal camera systems, License Plate Readers (LPRs), Mobile Surveillance Systems, Unmanned Aircraft Systems (UAS), national distress and command and control networks, and Remote Video Surveillance Systems will be deployed and carefully coordinated among participating agencies.” The new strategy also recommended enhancing air and maritime domain awareness and response capabilities as another means of disrupting the flow of illegal drugs across the U.S.-Canada border. In February of 2009, U.S. Customs and Border Protection began using unmanned aerial vehicles on the northern border and expanded the program in January of last year. The UAV drones are being deployed in support of border security, counter-narcotics and counter-terrorism missions. Congress recently passed a bill that will make it easier for the government to use surveillance drones and it is projected that that there could be up to 30,000 in operation over U.S. skies by 2020.
On February 9, the Conservative government released the Building Resilience Against Terrorism: Canada’s Counter-terrorism Strategy. The new plan is aimed at countering domestic, as well as international terrorism and better protecting Canadian interests. It outlined counter-terrorism efforts under four pillars, “prevent individuals from engaging in terrorism; detect the activities of individuals who may pose a terrorist threat; deny terrorists the means and opportunity to carry out their activities; and respond proportionately, rapidly and in an organized manner to terrorist activities and mitigate their effects.” The report stressed partnership and cooperation as the key to achieving these goals which, “will require an integrated approach not only by the Government of Canada, but by all levels of government, law enforcement agencies, the private sector and citizens, in collaboration with international partners and key allies, such as the United States.” The strategy will, “serve to reinforce security initiatives between Canada and the U.S. and will complement the Canada-U.S. Beyond the Border: A Shared Vision for Perimeter Security and Competitiveness.”
The anti-terror policy identified Sunni Islamist extremism as Canada’s top security threat. It also warned of homegrown terrorists and lone wolf attackers, including issue-based domestic extremism which it stated, “tends to be based on grievances—real or perceived—revolving around the promotion of various causes such as animal rights, white supremacy, environmentalism and anti-capitalism.” CTV News reported that similar intelligence assessments can be found in documents regarding CSIS and RCMP surveillance between 2005-2010 which categorized, “some animal rights, environmental and aboriginal activists alongside terrorists that pose a threat to national security.” The documents were obtained through access to information requests. They became the basis of the research paper Making up Terror Identities where authors Jeffrey Monaghan and Kevin Walby voiced concerns on how, “intelligence agencies have blurred the categories of terrorism, extremism and activism into an aggregate threat matrix. This blurring of threat categories expands the purview of security intelligence agencies, leading to net-widening where a greater diversity of actions are governed through surveillance processes and criminal law.”
The never ending war on drugs and war on terrorism are being used to justify the huge police state security apparatus being assembled. This includes the militarization of the northern border and plans for a North American security perimeter. In the name of national security, there has been a steady erosion of civil liberties and privacy rights in both the U.S. and Canada. Our freedoms are under assault. The amount of information being collected and shared on all aspects of our daily lives has expanded and is being stored in massive databases. Sweeping new surveillance powers targeting terrorists and other criminals are being increasingly turned against those who are critical of government policy. There is a concerted effort to demonize political opponents, activists, protesters and other peaceful groups. We are witnessing the criminalization of dissent where those who oppose the government’s agenda are being labelled as terrorists and a threat to security.
Dana Gabriel is an activist and independent researcher. He writes about trade, globalization, sovereignty, security, as well as other issues. Contact: [email protected]. Visit his blog at beyourownleader.blogspot.com |
<gh_stars>0
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package leader
import (
"errors"
"sync"
"time"
"github.com/docker/leadership"
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/zookeeper"
log "github.com/sirupsen/logrus"
"github.com/uber-go/tally"
)
// Observer is an interface that describes something that can observe an election for a given role,
// and can Start() observing, query the CurrentLeader(), and Stop() observing.
// 观察者接口
type Observer interface {
// 获取当前领导者
CurrentLeader() (string, error)
// 启动
Start() error
// 停止
Stop()
}
type observer struct {
// 锁
sync.Mutex
metrics observerMetrics // 指标
follower *leadership.Follower // 跟随者
role string // 角色
callback func(string) error // 回调
leader string // 领导者
running bool // 是否运行
stopChan chan struct{} // 停止通道
}
// NewObserver creates a new Observer that will watch and react to new leadership events for leaders in
// a given `role`, and will call newLeaderCallback whenever leadership changes
func NewObserver(cfg ElectionConfig, scope tally.Scope, role string, newLeaderCallback func(string) error) (Observer, error) {
// 日志
log.WithFields(log.Fields{"role": role}).Debug("Creating new observer of election")
// 创建客户端
client, err := zookeeper.New(cfg.ZKServers, &store.Config{ConnectionTimeout: zkConnErrRetry})
if err != nil {
return nil, err
}
// 创建观察者
obs := observer{
role: role,
metrics: newObserverMetrics(scope, role),
callback: newLeaderCallback,
follower: leadership.NewFollower(client, leaderZkPath(cfg.Root, role)),
stopChan: make(chan struct{}),
}
return &obs, nil
}
// Start begins observing the election results. When new leaders are detected, the callback will be invoked.
// watching the election happens in a background goroutine.
func (o *observer) Start() error {
o.Lock()
defer o.Unlock()
// 校验是否已启动
if o.running {
return errors.New("Already observing election, cannot Start again")
}
o.running = true
o.metrics.Start.Inc(1)
o.metrics.Running.Update(1)
// 日志
log.WithFields(log.Fields{"role": o.role}).Info("Watching for leadership changes")
// 启动观察过程
go o.observe()
return nil
}
// Stop cancels the observation of an election. It will terminate the background goroutine that is observing.
func (o *observer) Stop() {
o.Lock()
defer o.Unlock()
if o.running {
// 设置结束标志
o.running = false
// 打开关闭通道
close(o.stopChan)
// 停止跟随者
o.follower.Stop()
// 更新指标
o.metrics.Stop.Inc(1)
o.metrics.Running.Update(0)
}
}
// CurrentLeader returns the currently observed leader, or an error if not running.
// NOTE: Calls to CurrentLeader() return an error if the Observer is not started
func (o *observer) CurrentLeader() (string, error) {
o.Lock()
defer o.Unlock()
// 返回领导者
if o.running {
return o.leader, nil
}
// 出错
return "", errors.New("observer is not running")
}
// waitForEvent handles events like a new leader being elected, or an error occurring (i.e. a connectivity error).
// this function blocks until an event is handled from either the error channel or the leader channel. It
// should be called by a wrapper function that handles retries
func (o *observer) waitForEvent() error {
// 获取领导者变更、错误通道
leaderCh, errCh := o.follower.FollowElection()
for {
select {
case leader, ok := <-leaderCh:
// 获取领导者
if !ok {
return nil
}
o.Lock() // make sure we lock around modifying the current leader, and invoking callback
// 日志
log.WithFields(log.Fields{"role": o.role, "leader": leader}).Info("New leader detected")
// 指标
o.metrics.LeaderChanged.Inc(1)
// 领导者变更
o.leader = leader
// 领导者变更回调
err := o.callback(leader)
o.Unlock()
// 出错日志
if err != nil {
log.WithFields(log.Fields{"role": o.role, "error": err}).Error("NewLeaderCallback failed")
}
case err := <-errCh:
// 跟随者错误
if err != nil {
log.WithFields(log.Fields{"role": o.role, "error": err}).Error("Error following election")
o.metrics.Error.Inc(1)
return err
}
// just a shutdown signal from the docker/leadership lib,
// we can propogate this and let the caller decide if we
// should continue to run, or terminate
return nil
}
}
}
// observe will repeatedly call waitForEvent(), and retry when errors are encountered
// 观察者进程
func (o *observer) observe() {
for {
select {
case <-o.stopChan:
// 结束进程
return
default:
// 等待结束
err := o.waitForEvent()
if err != nil {
// 错误日志
log.WithFields(log.Fields{
"role": o.role,
"error": err,
}).Errorf("Failure observing election; retrying")
// if we already stop the observer, return without sleep
select {
case <-o.stopChan:
// 退出
return
default:
// 休眠等待
time.Sleep(zkConnErrRetry)
}
}
}
}
}
|
Turkish President Tayyip Erdogan addresses his supporters during a rally for the upcoming referendum in the Black Sea city of Rize, Turkey, April 3, 2017. REUTERS/Umit Bektas
ANKARA (Reuters) - Turkish President Tayyip Erdogan on Tuesday called on Iraqi Kurds to lower the Kurdish flag in the northern Iraqi city of Kirkuk, warning that failure to do so would damage their relations with Turkey.
Kirkuk, one of Iraq’s disputed territories, has Kurdish, Arab, and Turkmen populations. Kurdish peshmerga forces took control of it in 2014 when Islamic State overran around a third of Iraq and the army’s northern divisions disintegrated.
“We don’t agree with the claim ‘Kirkuk is for the Kurds’ at all. Kirkuk is for the Turkmen, Arabs and Kurds, if they are there. Do not enter into a claim it’s yours or the price will be heavy. You will harm dialogue with Turkey,” Erdogan said.
“Bring that flag down immediately,” he said at a rally in the Black Sea province of Zonguldak, where he was campaigning ahead of an April 16 referendum on constitutional changes that would broaden his powers.
Kurds have long claimed Kirkuk and its huge oil reserves. They regard the city, just outside their semi-autonomous Kurdistan region in northern Iraq, as their historical capital.
The local Rudaw TV channel cited the governor of Kirkuk as saying that the Kurdistan flag should fly alongside the Iraqi national flag because the city is largely under the protection of Kurdish forces.
Turkey has long seen itself as the protector of Iraq’s Turkmen ethnic minority. Local media reported that leaders of Kirkuk’s Turkmen communities have rejected the raising of the Kurdish flag as against the constitution.
Turkey fears territorial gains by some Kurdish groups in Iraq and neighboring Syria could fuel Kurdish separatist ambitions inside Turkey, where PKK militants have fought an insurgency against the state for more than three decades. |
Effect of surface energy on the growth of boron nanocrystals
The surface energies of α-rhombohedral (α-rh), β-rhombohedral (β-rh), α-tetragonal (α-t), and β-tetragonal (β-t) boron were calculated from first principles to investigate their role in nano-scale crystal growth. Equilibrium shapes of boron crystals were obtained using Wulff's theorem. Our results shows that α-t boron, despite its low cohesive energy, is more stable than the other structures as a result of its low surface energy when the number of atoms is less than about 216. Since the nanowire of α-t boron that was obtained experimentally was larger than this, it was probably in a metastable state. The difference between the surface energy of the ab-plane and that of the ac-plane explains why the α-t nanowires grow in the c direction.
Introduction
Boron is an element in Group IIIB, and is generally a semiconductive material with covalent bonds. Whereas boron forms compounds that have a variety of structures, elemental boron itself has mainly four polymorphs: α-rhombohedral (α-rh), β-rhombohedral (β-rh), α-tetragonal (α-t), and β-tetragonal (β-t). Of these, α-rh and β-rh boron have been well studied because they are fairly stable and easy to synthesize. α-rh boron is believed to be the most stable at low temperatures. It transforms into β-rh boron at about 1400 K . α-t and β-t boron are less studied than α-rh and β-rh boron.
The synthesis of α-t boron was first reported in 1943 by Laubengayer et al and later its structure was precisely determined as B 50 by Hoard et al . However, in 1971, studies by Amberger et al concluded that pure α-t boron could not be synthesized in the absence of carbon or nitrogen as an impurity . These studies asserted that what was assumed to be α-t boron was actually B 50 C 2 or B 50 N 2 and the structures of these compounds were proposed. In 1992, Lee et al showed by firstprinciples calculations that α-t boron could be made more stable by the inclusion of carbon, and along with their calculations of lattice parameters, they concluded that the α-t boron obtained by Hoard et al was probably B 50 C 2 . It is now thought that α-t boron does not exist in pure form.
Nevertheless, we believe that this assertion is not fully confirmed. First, the original synthesis experiments were conducted using chemical vapor deposition (CVD), and it is not known what will happen if other methods are applied. Second, the work by Lee et al indicates only that B 50 C 2 is more stable than pure B 50 , and does not directly disprove the existence of B 50 .
Since 2001, the synthesis of wire-like structures from boron has been reported , with some structures adopting α-t structures (table 1). These are called nanowires , nanobelts , or nanoribbons . For the sake of simplicity, the term "nanowire" will be used throughout this paper to refer to these structures. Yang et al and Xu et al reported that α-t nanowires contain impurities, a view that is consistent with the earlier results. Zhang et al , on the other hand, suggested that the α-t nanowire that they produced consisted solely of boron atoms, and Wang et al insisted that they did not observe any impurities in their nanowire. These two groups used the laser ablation (LA) method to create the nanowires, whereas CVD was used in the other preparations. If pure α-t boron actually exists, this is a significant result, since it has long been regarded as an impossibility. For the growth of nano-sized crystals, it is more likely that the surface energy makes as large a contribution as the bulk energy. When we looked at the crystal structure of α-t boron, we noticed that its (100) surface has fewer bonds than the other surfaces. In fact, on the α-t nanowire obtained by Wang et al, the (100) surface appears very large, suggesting that it has much lower energy than the other surfaces. This prompted us to wonder whether the α-t crystal could be stabilized by its low surface energy, even though its cohesive energy is small, suggesting instability.
There have been few studies on the surface energy of boron. This is partly because the unit cells of boron crystals are large and the optimization of the geometry of the bulk and surfaces requires prolonged computation. We performed first-principle scalculations of the surface energies of four polymorphs of boron and investigated whether a nano-sized α-t crystal could be stable .
Computational Details
The calculation of the total energies and geometry optimization were performed using the CPMD code, version 3.9.1 . This code is based on the density functional theory with plane waves and pseudopotentials . The norm-conserving Troullier-Martins-type pseudopotentials were used. The generalized gradient approximation was included by means of the functional derived by Becke and by Lee, Yang, and Parr . An energy cutoff of 50 Ry for the plane-wave expansion was sufficient to provide a convergence for total energies and geometries. We have already confirmed in a previous study that the total energies converged at a smaller cutoff of 40 Ry for this pseudopotential. Because the unit cell is large, the k-point sampling in the total energy calculation was performed using Monkhorst-Pack sampling of a (2 × 2 × 2) mesh. The results were compared with those of a finer mesh, and it was found that the difference in the total energy per atom was less than 6 × 10 -4 eV. In some cases, a larger unit cell was required to construct a model of a particular surface. For example, the (111) surface of a rhombohedral structure needs a hexagonal lattice that contains three times as many atoms as the primitive unit cell. For these larger cells, the calculations were performed only at the Γ point, and a good convergence was confirmed by comparison with a (2 × 2 × 2) mesh. Calculations were performed on a parallel computer (Hitachi SR11000) using a message-passing interface. Typically, 16 CPUs were used and the computational times for a geometry optimization were a few days to a few weeks.
To evaluate the surface energy, the total energy of the bulk was first calculated. A space of about 7 Å was then inserted at a certain cross section to generate a surface and the total energy was recalculated. The geometries were optimized in both calculations. The difference between the two total energies divided by the surface area was defined as the surface energy. The space of 7 Å was sufficiently wide to render the interaction between surfaces negligible. We assumed that no structural defects like twining occur.
There are an infinite number of ways of inserting surfaces, and no strict proofs exist that a given set of surfaces is sufficient to reach the minimum surface energy. However, the experience of crystallography tells us that surfaces with high Miller indices rarely appear. In addition, surfaces that cut fewer bonds have inherently less surface energy, and those surfaces that make the crystal shape round also reduce the surface area. From these considerations, we lay down the following criteria for choosing surfaces: (i) surfaces with Miller indices of up to two; (ii) surfaces cutting fewer bonds; and (iii) surfaces that make the crystal shape round. The selected surfaces (cross sections) are indicated by red lines in figure 1.
Aside from the α-rh structure, fractional occupation sites exist for boron atoms. Because the unit cells for such structures are large, the fractional occupation does not have much effect on the surface energy. We assumed the number of atoms in a unit cell to be 105 for β-rh, 50 for α-t, and 196 for β-t.
Results and Discussion
First, we calculated the lattice constants of α-t boron and compared them with the experimental values listed in table 1. Our calculation indicates that pure α-t boron B 50 has a longer a and a shorter c value than a and c in B 50 C 2 . The calculation by Lee et al also showed a similar trend. Among the experimental lattice constants listed in table 1, the results of Wang et al , who insist that their nanowire included no impurities, show a longer a and a shorter c than the other results. This means that their α-t nanowire is almost pure, or at least much purer than the others. Their experiment adopted LA without using any catalyst, giving little probability that impurities had contaminated their sample.
The calculated surface energies are exhibited in figure 2. The minimum-energy surfaces in the same Miller index group are excerpted from references . It is seen that α-t boron has the lowest average surface energy, as we had expected. Notably, the four main surfaces of (100), (001), (101), and (110) are the lowest of all the surfaces. β-t boron is the second lowest on average, followed by βrh and α-rh boron. The surface energies of β-rh and α-rh have certain similarities, probably due to structural parallels. Both have a rhombohedral symmetry, and the orientations of the B 12 icosahedra are the same, except that β-rh boron has additional B 28 subunits at the center. When all the surface energies of a crystal are known, the crystal shape that minimizes the total surface energy at a constant volume is given by Wulff's theorem . The theorem states that the distance from the crystal center to a surface is proportional to its surface energy per unit area. Lowenergy surfaces are closer to the center and, as a result, exhibit a larger surface area. The crystal shapes of the four boron polymorphs obtained by Wulff's theorem are shown in figure 3. The surfaces are labeled by their Miller indices. Equivalent surfaces are given the same color. It is interesting that the (100) surface appears very large in α-t boron, as was observed in the experiment by Wang et al . Its rectangular shape would appear to make it suitable for nanowire growth. β-t boron has a round shape which results from its isotropic surface energies. The structure of β-t boron is rather complicated, since it includes 196 atoms per unit cell, which means that number of cut bonds does not differ very much between each surface. The shapes of β-rh and α-rh boron are similar to each other as would be expected from their surface energies. β-rh boron has additional small faces because its B 28 subunits make the surface energy more isotropic than that of α-rh boron.
Once the crystal shape has been determined, it is easy to calculate the total surface energy. When the number of atoms is N, the surface area and energy are proportional to N 2/3 , since the surface area is proportional to v 2/3 , where v is the crystal volume, and v is proportional to N. The total energy of the crystal E tot can be expressed as E tot = -C v N + C s N 2/3 .
(1) The first term is the bulk part and C v is equal to the cohesive energy per atom. The second term is the surface term. C s can be calculated from the surface energy, crystal volume, and atom density. The Table 3. Critical sizes of boron crystals calculated with equation (2).
The total energy of the crystal is dominated by C v when N is large, and by C s when N is small. When there are two phases of α and β satisfying where the superscripts α and β correspond to each phase, phase α is more stable for large N and phase β for small N. The critical size, N c , at which the total energies of the two phases become equal is calculated from equation (1) as (2) The critical sizes for each boron polymorph are listed in table 3. For α-t boron, the N c against β-t (216) is lower than that against β-rh (254) and α-rh (1000). As a result, α-t boron is the most stable when N is between 0 ~ 216. In the same way, β-t, β-rh and α-rh boron are the most stable between 216 ~ 512, 512 ~ 32800 and 32800 ~, respectively. β-t boron has a rather narrow region, which would make it hard to synthesize. β-rh and α-rh boron have a wide stable region, suggesting that they are easy to synthesize.
The thickness of nanowires obtained in the experiment by Wang et al was several tens of nanometers. This is much greater than the critical size of the α-t crystal, even if the estimated value includes some degree of error. Therefore, if the nanowire is pure α-t boron, it must be in a metastable state. In an equilibrium state, according to Wulff's theorem, the aspect ratio c/a of an α-t crystal shape is equal to the ratio between the surface energies of the (001) and the (100) surfaces, and is estimated from the values in figure 2 to be 1.09. In real nanowires, the aspect ratio is much larger than this estimated value, which makes it likely that α-t nanowires grow via a non-equilibrium process. Below we propose some possible growth mechanisms for α-t nanowires.
The first possibility is that α-t nanowires grow via a vapor-solid (VS) process. In this case, the growth rate is dominated by the sticking probability of vapor atoms to the surface rather than by the surface energy itself. The difference between the sticking probabilities of the (001) and the (100) surfaces could be greater than the difference between their surface energies, with the result that nanowires should grow more rapidly in the <001> direction than in the <100> direction. The second possibility is that α-t nanowires grow via a vapor-liquid-solid (VLS) process. In this case, the nanowires would grow in the direction normal to the surface on which a liquid droplet preferably remains. The binding energy between the droplet and the surface determines which surface is preferred. It is difficult to calculate the binding energy because the droplet is in a liquid state. It is, however, logical to expect binding energy to be correlated to the surface energy, since the surface structures are identical. A surface with a higher surface energy would have a higher binding energy to the droplet, so that the droplet would prefer the (001) surface to the (100) surface.
In summary, the following processes are suggested as the growth mechanism of pure α-t nanowires. (i) First, an equilibrium nucleation takes place of an α-t boron crystal that is smaller than N c = 216.
(ii) Second, based on this nano-sized nucleus, the crystal, in a metastable state, grows more rapidly in the <001> direction than in the <100> direction. This may be due to the difference between sticking probabilities (VS process) or between the binding energies of the droplet on the surface (VLS process). In the experiment by Wang et al , the dimensions of the nanowire were not actually tetragonal, i.e., a b. The reason for this cannot be explained by our calculations, since the surface energies of the a and b surfaces in pure α-t boron are identical. We speculate that the lack of tetragonal dimensions may be due to the presence of traces of impurities below the detectable level or to the experimental conditions, such as the angle of the laser beam.
The reason that pure α-t is formed only in gas-phase syntheses, such as LA, is that in the gas phase, the fluctuations in the atom density are large, allowing small (N < N c ) clusters to exist as isolated entities. We speculate that LA, where a high temperature and a low density are achieved, is superior to CVD for the synthesis of α-t boron crystals. |
/* Function that uses stat() to determine the timestamp to put in the
* SOA serial for when we synthesize the SOA record;
* JS_ERROR on error, JS_SUCCESS on success */
int csv2_set_soa_serial(csv2_add_state *state, js_string *filename) {
char name[256];
struct stat buf;
time_t t;
qual_timestamp q;
if(js_js2str(filename,name,200) == JS_ERROR) {
return JS_ERROR;
}
if(stat(name,&buf) == -1) {
return JS_ERROR;
}
t = buf.st_mtime;
if(t < 290805600) {
t += 2147483648U;
}
if(show_synth_soa_serial() != 2) {
q = t;
q -= 290805600;
q /= 6;
} else {
struct tm bd;
#ifndef MINGW32
if(gmtime_r(&t,&bd) == NULL) {
return 1979032815;
}
#else
return 2005032801;
#endif
q = bd.tm_year + 1900;
q *= 100;
q += bd.tm_mon + 1;
q *= 100;
q += bd.tm_mday;
q *= 100;
q += bd.tm_hour;
}
state->soa_serial = q;
return JS_SUCCESS;
} |
// FetchUpdate grabs the update indicated by the changeID.
//
// If empty changeID is provided, it grabs the default update.
func FetchUpdate(changeID string) (*Response, error) {
endpoint := StashAPIBase
if changeID != "" {
endpoint = fmt.Sprintf("%s?id=%s", StashAPIBase, changeID)
}
resp, err := http.Get(endpoint)
if err != nil {
return nil, errors.Wrap(err, "failed to call stash api")
}
defer resp.Body.Close()
var response Response
err = easyjson.UnmarshalFromReader(resp.Body, &response)
if err != nil {
return nil, errors.Wrap(err, "failed to decode stash tab response")
}
return &response, CleanResponse(&response)
} |
import { Provider } from "@ethersproject/abstract-provider";
import { Signer } from "@ethersproject/abstract-signer";
import { BigNumber } from "@ethersproject/bignumber";
import { Contract, ethers } from "ethers";
import { PickleModel } from "../..";
import { Chains } from "../../chain/Chains";
import { JAR_LQTY } from "../../model/JarsAndFarms";
import { JarDefinition, AssetProjectedApr, PickleAsset, ExternalAssetDefinition } from "../../model/PickleModelJson";
import { ExternalAssetBehavior, JarHarvestStats } from "../JarBehaviorResolver";
import erc20Abi from '../../Contracts/ABIs/erc20.json';
import stabilityPool from '../../Contracts/ABIs/stability-pool.json';
import { formatEther } from "ethers/lib/utils";
import { getOrLoadYearnDataFromDune } from "../../protocols/DuneDataUtility";
import { aprComponentsToProjectedAprImpl, createAprComponentImpl } from "../AbstractJarBehavior";
const stabilityPoolAddr = "0x66017D22b0f8556afDd19FC67041899Eb65a21bb";
const pBAMM = "0x54bC9113f1f55cdBDf221daf798dc73614f6D972";
const pLQTY = "0x65B2532474f717D5A8ba38078B78106D56118bbb";
export class PBammAsset implements ExternalAssetBehavior {
async getProjectedAprStats(definition: ExternalAssetDefinition, model: PickleModel): Promise<AssetProjectedApr> {
// LQTY APR calc
const lusdContract = new Contract(model.addr("lusd"), erc20Abi, model.providerFor(definition.chain));
const remainingLQTY = 13344950;
const lusdInSP = await lusdContract.balanceOf(stabilityPoolAddr);
const lqtyApr =
(remainingLQTY * model.priceOfSync("lqty")) / (+formatEther(lusdInSP) * model.priceOfSync("lusd"));
const duneData = await getOrLoadYearnDataFromDune(model);
const liquidationRate = duneData?.data?.get_result_by_result_id[0].data?.apr / 100;
const liquidationYield = (liquidationRate * 0.8 * lqtyApr)/2;
const total = (lqtyApr + liquidationYield)*100;
return {
components: [
{name: "lqty", apr: lqtyApr*100, compoundable: false},
{name: "liquidation", apr: liquidationYield*100, compoundable: false},
],
apr: total,
apy: total
};
}
async getDepositTokenPrice(definition: ExternalAssetDefinition, model: PickleModel): Promise<number> {
if( definition && definition.depositToken && definition.depositToken.addr) {
return await model.priceOf(definition.depositToken.addr);
}
return undefined;
}
async getAssetHarvestData(definition: ExternalAssetDefinition, model: PickleModel,
_balance: BigNumber, _available: BigNumber, _resolver: Signer | Provider): Promise<JarHarvestStats> {
const bal = await getPBammBalance(definition, model);
return {
balanceUSD: bal,
earnableUSD: 0,
harvestableUSD: 0
}
}
}
export async function getPBammBalance(asset: PickleAsset, model: PickleModel) {
const stabilityPoolContract = new ethers.Contract(stabilityPoolAddr,
stabilityPool, Chains.getResolver(asset.chain));
const lusdInStabilityPool = await stabilityPoolContract.getCompoundedLUSDDeposit(pBAMM);
const lusdPrice = await model.priceOf("lusd");
const lusdValue = parseFloat(ethers.utils.formatEther(lusdInStabilityPool)) * lusdPrice;
const pLqtyContract = new ethers.Contract(pLQTY,
erc20Abi, Chains.getResolver(asset.chain));
const pLqtyTokens = await pLqtyContract.balanceOf(pBAMM);
const lqtyPrice = await model.priceOf("lqty");
const ratio = (model.findAsset(JAR_LQTY.id) as JarDefinition).details.ratio;
const lqtyValue = parseFloat(ethers.utils.formatEther(pLqtyTokens)) * lqtyPrice * ratio;
return lusdValue + lqtyValue;
} |
Antithrombotic effect of a recombinant von Willebrand factor, VCL, on nitrogen laser-induced thrombus formation in guinea pig mesenteric arteries.
To assess the antithrombotic effectiveness of blocking the platelet glycoprotein (GP) Ib/IX receptor for von Willebrand factor (vWF), the antiaggregating and antithrombotic effects were studied in guinea pigs using a recombinant fragment of vWF, Leu 504-Lys 728 with a single intrachain disulfide bond linking residues Cys 509-Cys 695. The inhibitory effect of this peptide, named VCL, was tested in vitro on ristocetin- and botrocetin-induced platelet aggregation and compared to the ADP-induced platelet aggregation. In vivo, the antithrombotic effect of VCL was tested in a model of laser-injured mesentery small arteries and correlated to the ex vivo ristocetin-induced platelet aggregation. In this model of laser-induced thrombus formation, five mesenteric arteries were studied in each animal, and the number of recurrent thrombi during 15 min, the time to visualization and time to formation of first thrombus were recorded. In vitro, VCL totally abolished ristocetin- and botrocetin-induced platelet aggregation, but had no effect on ADP-induced platelet aggregation. Ex vivo, VCL (0.5 to 2 mg/kg) administered as a bolus i.v. injection inhibits risocetin-induced platelet aggregation with a duration of action exceeding 1 h. The maximum inhibition was observed 5 min after injection of VCL and was dose related. The same doses of VCL had no significant effect on platelet count and bleeding time.(ABSTRACT TRUNCATED AT 250 WORDS) |
<reponame>Sanjeever/node-ts-mysql-demo<filename>src/app/server.ts
import {execSQL} from "../db/mysql";
const sql: string = `select host,user from user;`;
execSQL(sql).then((tablesData) => {
console.log(tablesData);
process.exit();
});
|
def parse_pcap(pcap, pcap_path, file_name):
counter = 0
pcap_dict = {}
for ts, packet in pcap:
try:
eth = dpkt.ethernet.Ethernet(packet)
except dpkt.dpkt.NeedData:
print("dpkt.dpkt.NeedData")
if isinstance(eth.data, dpkt.ip.IP):
ip = eth.data
elif isinstance(eth.data, str):
try:
ip = dpkt.ip.IP(packet)
except dpkt.UnpackError:
continue
else:
continue
proto = ip.data
if type(ip.data)in PROTO_DICT:
session_tuple_key = (inet_to_str(ip.src), proto.sport, inet_to_str(ip.dst), proto.dport, PROTO_DICT[type(ip.data)])
pcap_dict.setdefault(session_tuple_key, (ts, [], []))
d = pcap_dict[session_tuple_key]
size = len(ip)
d[1].append(round(ts - d[0], 6)), d[2].append(size)
counter += 1
print("Total Number of Parsed Packets in " + pcap_path + ": " + str(counter))
csv_file_path = os.path.splitext(pcap_path)[0] + ".csv"
with open(csv_file_path, 'wb') as csv_file:
writer = csv.writer(csv_file)
for key, value in pcap_dict.items():
writer.writerow([file_name.split(".")[0]] + list(key) + [value[0], len(value[1])] + value[1] + [None] + value[2])
for k,v in pcap_dict.iteritems():
if len(v[1]) > 2000:
print(k, v[0], len(v[1])) |
<reponame>BNgoum/TapProject<filename>ANGclient/src/app/routes/user-page/user-page.component.ts
/*
Imports & definition
*/
// Imports
import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router"
// Inner
import { AuthService } from "../../services/auth/auth-service.service";
import { GameService } from "../../services/game/game-service.service";
// Definition
@Component({
selector: 'app-user-page',
templateUrl: './user-page.component.html',
providers: [ AuthService, GameService ],
styleUrls: ['./user-page.css']
})
//
/*
Export
*/
export class UserPageComponent implements OnInit {
numberTap: number
userId: string
isTaped: boolean
isStarted: boolean
/*
Config.
*/
// Module injection
constructor(private AuthService: AuthService, private GameService: GameService, private router: Router) {
this.numberTap = 0;
};
//
/*
Methods
*/
startGame(){
this.isStarted = true;
const timer = setTimeout(() => {
if(this.isStarted){
this.endGame();
this.isStarted = false;
clearTimeout(timer);
}
}, 10000);
}
onTapButton(){
this.numberTap++;
if(this.numberTap > 0){
this.startGame();
}
}
endGame(){
this.GameService.saveScore(this.numberTap);
this.router.navigate(['/scores']);
};
/*
Hooks
*/
ngOnInit() {
document.querySelector('#button-tap').addEventListener("mousedown", () => {
this.isTaped = true;
});
document.querySelector('#button-tap').addEventListener("mouseup", () => {
this.isTaped = false;
});
};
//
}
//
|
Does Board Structure in Banks Really Affect Their Performance?
We study whether board structure (board size, independence and gender diversity) in banks relates to performance. Using a broad panel of large US bank holding companies over the period 1997–2011, we find that both board size and independent directors decrease bank performance. Although gender diversity improves bank performance in the pre-Sarbanes-Oxley Act (SOX) period (1997–2002), the positive effect of gender diminishes in both the post-SOX (2003–2006) and the crisis periods (2007–2011). Finally, we show that board structure is particularly relevant for banks with low market power, if they are immune to the threat of external takeover and/or they are small. Our two-step system generalised method of moments estimation accounts for endogeneity concerns (simultaneity, reverse causality and unobserved heterogeneity). The findings are robust to a wide range of other sensitivity checks including alternative proxies for bank performance. |
<reponame>Eric-Arellano/rust
#![feature(box_syntax)]
fn take(_x: Box<isize>) {}
fn main() {
let x: Box<isize> = box 25;
loop {
take(x); //~ ERROR use of moved value: `x`
}
}
|
/**
* Open the javadoc location dialog or the source location dialog, and set the result
* to the selected libraries.
*/
private void edit(IStructuredSelection selection, int type) {
Object obj = selection.getFirstElement();
LibraryStandin standin = null;
if (obj instanceof LibraryStandin) {
standin = (LibraryStandin) obj;
} else if (obj instanceof SubElement) {
SubElement sub = (SubElement) obj;
standin = sub.getParent();
}
if (standin != null) {
LibraryLocation library = standin.toLibraryLocation();
if (type == SubElement.JAVADOC_URL) {
URL[] urls = BuildPathDialogAccess.configureJavadocLocation(fLibraryViewer.getControl().getShell(), library.getSystemLibraryPath().toOSString(), library.getJavadocLocation());
if (urls != null) {
fLibraryContentProvider.setJavadoc(urls[0], selection);
}
} else if (type == SubElement.SOURCE_PATH) {
IRuntimeClasspathEntry entry = JavaRuntime.newArchiveRuntimeClasspathEntry(library.getSystemLibraryPath());
entry.setSourceAttachmentPath(library.getSystemLibrarySourcePath());
entry.setSourceAttachmentRootPath(library.getPackageRootPath());
IClasspathEntry classpathEntry = BuildPathDialogAccess.configureSourceAttachment(fLibraryViewer.getControl().getShell(), entry.getClasspathEntry());
if (classpathEntry != null) {
fLibraryContentProvider.setSourcePath(classpathEntry.getSourceAttachmentPath(), classpathEntry.getSourceAttachmentRootPath(), selection);
}
} else if (type == SubElement.EXTERNAL_ANNOTATIONS_PATH) {
IRuntimeClasspathEntry entry = JavaRuntime.newArchiveRuntimeClasspathEntry(library.getSystemLibraryPath());
entry.setExternalAnnotationsPath(library.getExternalAnnotationsPath());
IClasspathAttribute[] extraAttributes = entry.getClasspathEntry().getExtraAttributes();
String annotationPathString = findClasspathAttribute(extraAttributes, IClasspathAttribute.EXTERNAL_ANNOTATION_PATH);
IPath annotationPath = null == annotationPathString ? null : new Path(annotationPathString);
IPath newPath = BuildPathDialogAccess.configureExternalAnnotationsAttachment(fLibraryViewer.getControl().getShell(), annotationPath);
if (null == newPath) {
return;
}
fLibraryContentProvider.setAnnotationsPath(newPath.segmentCount() == 0 ? null : newPath, selection);
}
}
} |
/* La classe Directory rappresenta una cartella nel filesystem, essa e' mutabile in quanto il suo contenuto
* puo' cambiare (aggiungere file o cartelle)
*
* ABS FUN: ABS(name, size, path, content) = per rappresentare la una directory utilizziamo una stringa per
* indicare il nome (name), un valore intero per indicare la dimensione (size)
* un attributo di tipo Path che indica il percorso della entry (path)
* e infine con una mappa di Entry indichiamo il contenuto della directory
* (content).
* La mappa e' formata da chiave e valore, come chiave abbiamo la path del file o
* directory, metre come valore avremo l'oggetto di tipo Entity (File o Directory)
*
* content = [pathFile1 -> file1
* pathDirectory2 -> directory2
* ...]
*
* REP INV = name != null
* size != null && size >= 0 && size = somma delle dimensioni del contenuto di content
* path != null
* content != null && content.get(path file o directory)!= null
*/
public class Directory implements Entry {
// Attributi
private final String name;
private int size;
private Path path;
private Map<String, Entry> content;
//Costruttore
public Directory(Path path) {
if(path == null) throw new IllegalArgumentException("Il percorso del file non puo' essere nullo");
this.name = path.name();
this.size = 0;
this.path = path;
this.content = new HashMap<String, Entry>();
}} |
// Return true if vp is VVVV:PPPP where V and P are hex digits:
//
DLLEXPORT(bool) usbValidateVidPid(const char *vp) {
int i;
char ch;
const size_t len = strlen(vp);
bool hasDID;
if ( !vp ) {
return false;
}
if ( len == 9 ) {
hasDID = false;
} else if ( len == 14 ) {
hasDID = true;
} else {
return false;
}
if ( vp[4] != ':' || (hasDID && vp[9] != ':') ) {
return false;
}
for ( i = 0; i < 4; i++ ) {
ch = vp[i];
if (
ch < '0' ||
(ch > '9' && ch < 'A') ||
(ch > 'F' && ch < 'a') ||
ch > 'f')
{
return false;
}
}
for ( i = 5; i < 9; i++ ) {
ch = vp[i];
if (
ch < '0' ||
(ch > '9' && ch < 'A') ||
(ch > 'F' && ch < 'a') ||
ch > 'f')
{
return false;
}
}
if ( hasDID ) {
for ( i = 10; i < 14; i++ ) {
ch = vp[i];
if (
ch < '0' ||
(ch > '9' && ch < 'A') ||
(ch > 'F' && ch < 'a') ||
ch > 'f')
{
return false;
}
}
}
return true;
} |
/**
* <p>Title: EditableStringConstraint </p>
*
* <p>Description: This constraint contains a list of values that user
* can choose from. It also allows the user to provide his own value.
* These can typically be presented in a GUI picklist.
</p>
*
* @author Nitin Gupta and Vipin Gupta
* @version 1.0
*/
public class EditableStringConstraint
extends StringConstraint {
/** Class name for debugging. */
protected final static String C = "EditableStringConstraint";
/** If true print out debug statements. */
protected final static boolean D = false;
/** ArrayList list of possible string values, i.e. allowed values. */
private ArrayList strings = new ArrayList();
public EditableStringConstraint() {
super();
}
public EditableStringConstraint(ArrayList strings) throws ConstraintException {
super(strings);
}
/** Returns a copy so you can't edit or damage the origial. */
public Object clone() {
EditableStringConstraint c1 = new EditableStringConstraint();
c1.name = name;
ArrayList v = getAllowedStrings();
ListIterator it = v.listIterator();
while (it.hasNext()) {
String val = (String) it.next();
c1.addString(val);
}
c1.setNullAllowed(nullAllowed);
c1.editable = true;
return c1;
}
} |
import UnknownImageSVG from './unknown-image.svg';
export { UnknownImageSVG };
|
import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import {FacebookInitializerService} from './facebook-initializer.service';
import {FacebookIdentifyVerifierService} from './facebook-identity-verifier.service';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Player} from '../player/player.model';
import {Observable} from 'rxjs/Observable';
import {PlayerService} from '../player/player.service';
import {from} from 'rxjs/observable/from';
class MockInitService {
public fbReady: Promise<any>;
public fbRequiredPermissions: string[];
public resolve: (result?: boolean) => void;
public reject: (reason?: any) => void;
constructor() {
this.fbReady = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
class MockPlayerService {
public subject: BehaviorSubject<Player> = new BehaviorSubject<Player>(new Player());
public loggedInPlayer: Observable<Player> = from(this.subject);
public logout: any = jest.fn();
}
declare let window: any;
describe('Service: facebook identity verifier service', () => {
let verifierService: FacebookIdentifyVerifierService;
let mockInit: MockInitService;
let playerService: MockPlayerService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: FacebookInitializerService, useClass: MockInitService},
{provide: PlayerService, useClass: MockPlayerService},
FacebookIdentifyVerifierService
]
});
mockInit = TestBed.get(FacebookInitializerService) as MockInitService;
playerService = TestBed.get(PlayerService) as MockPlayerService;
verifierService = TestBed.get(FacebookIdentifyVerifierService);
window.FB = {};
});
it('not facebook player does not check', fakeAsync(() => {
mockInit.resolve(true);
const p = new Player({sourceId: 'x', source: 'manual'});
playerService.subject.next(p);
tick();
expect(playerService.logout).not.toHaveBeenCalled();
}));
it('everything matches does not logout', fakeAsync(() => {
mockInit.resolve(true);
window.FB.getLoginStatus = (callback: (response: any) => void) => {
callback({status: 'connected', authResponse: {userID: 'x'}});
};
const p = new Player({sourceId: 'x', source: 'facebook'});
playerService.subject.next(p);
tick();
expect(playerService.logout).not.toHaveBeenCalled();
}));
describe('failures to verify performs logout', () => {
beforeEach(() => {
mockInit.resolve(true);
});
afterEach(fakeAsync(() => {
const p = new Player({sourceId: 'x', source: 'facebook'});
playerService.subject.next(p);
tick();
expect(playerService.logout).toHaveBeenCalledTimes(1);
}));
it('ids do not match', fakeAsync(() => {
window.FB.getLoginStatus = (callback: (response: any) => void) => {
callback({status: 'connected', authResponse: {userID: 'y'}});
};
}));
it('null auth response', fakeAsync(() => {
window.FB.getLoginStatus = (callback: (response: any) => void) => {
callback({status: 'connected', authResponse: null});
};
}));
it('mo auth response', fakeAsync(() => {
window.FB.getLoginStatus = (callback: (response: any) => void) => {
callback({status: 'connected'});
};
}));
it('mot connected', fakeAsync(() => {
window.FB.getLoginStatus = (callback: (response: any) => void) => {
callback({status: 'not connected'});
};
}));
});
});
|
Artist Carolina Fontoura Alzaga constructs impressive chandeliers using chains, wheels and other parts from old bicycles as part of a series she calls CONNECT. Alzaga has lived in Brazil and Mexico and now works out of a studio in Los Angeles where the Etsy Blog recently caught up with her to conduct the interview and tour above.
Of her work she says:
This developing body of work draws inspiration from the aesthetics of victorian era chandeliers, DIY and Bike Culture, and follows an art tradition of utilizing non artistic materials for sculpture. This series addresses class codes, power dynamics, reclaimed agency, and ecological responsibility. The traditional chandelier is seen as a bourgeois commodity, a cachet of affluence, excess, and as such power. The recycled bicycle parts become a representation of the dismissed, invisible, and powerless, but are also an affirmation of self-propelled movement. The bicycle chandelier thereby creates a new third meaning of reclaimed agency.
I think if I ever had need for a chandelier it would definitely be one of these. Alzaga has a number of pieces currently available in her shop. (via laughing squid) |
def residual_chaser_factory(y :Y_TYPE, s:dict, k:int, a:A_TYPE =None, t:T_TYPE =None, e:E_TYPE =None,
f1=None, f2=None, r1=None, r2=None)->([float] , Any , Any):
if k == 1:
J = [1]
else:
J = [1,k]
y0 = wrap(y)[0]
if not s.get('s1'):
s = {'sres': {},
'x': y0,
's1':{},
's2':dict([(j,{}) for j in J]),
'n_obs':0}
if y0 is None:
return None, None, s
else:
if r1 is None:
x1, x1_std, s['s1'] = f1(y=y,s=s['s1'],k=k, a=a,t=t,e=e)
else:
x1, x1_std, s['s1'] = f1(y=y, s=s['s1'], k=k, a=a, t=t, e=e, r=r1)
resid1, s['sres'] = residual(s['sres'],y=y0,x=x1)
s['n_obs']+=1
res_j_hat = [None for j in J]
res_j_std = [None for j in J]
for jpos,j in enumerate(J):
j_ahead_residual = resid1[j-1]
if r2 is None:
_x, _std, s['s2'][j] = f2(y=j_ahead_residual, s=s['s2'][j], k=j, a=a, t=t, e=e)
else:
_x, _std, s['s2'][j] = f2(y=j_ahead_residual, s=s['s2'][j], k=j, a=a, t=t, e=e,r=r2)
res_j_hat[jpos] = _x[jpos]
res_j_std[jpos] = _std[jpos]
if k==1:
res_interp = res_j_hat
res_interp_std = res_j_std
else:
import numpy as np
ks = list(range(1,k+1))
res_interp = np.interp( x=ks, xp=J, fp=res_j_hat )
res_interp_std = np.interp(x=ks, xp=J, fp=res_j_std)
x_hat = [ resj+x1j for resj, x1j in zip( res_interp, x1) ]
return x_hat, res_interp_std, s |
Family-centred services in the Netherlands: validating a self-report measure for paediatric service providers
Objective: To validate the Dutch translation of the Canadian Measure of Processes of Care for Service Providers questionnaire (MPOC-SP) for use in paediatric rehabilitation settings in the Netherlands. Design: The construct validity, content validity, face validity, and reliability of the Dutch MPOC-SP were determined. Subjects: The 163 service providers that participated in the validation study represented seven children's rehabilitation centres and affiliated schools in the Netherlands (overall response rate 55.6%). In this sample 19 disciplines were represented. Main measures: The MPOC-SP consists of 27 items (assessing four domains) and was designed to examine how service providers think about the quality of care they provide and to assess the extent to which these services are family centred. Fifty-three service providers filled out an additional face validity questionnaire. Results: All items correlated best and significantly with their own scale score (rs 0.48-0.82, P < 0.001). The Pearson's correlation coefficients were all significant and confirmed that the four scales measure different aspects of a same construct, namely family-centred service. The content validity and the face validity of the Dutch MPOC-SP were good, indicating the questionnaire measures relevant aspects of family-centred service delivery in paediatric rehabilitation settings in the Netherlands. The test-retest analyses (intraclass correlation coefficient (ICC) 0.83-0.89) and the internal consistency analyses (alpha 0.65-0.84) showed that the Dutch MPOC-SP is a reliable tool. Conclusions: The Dutch MPOC-SP is a reliable and valid instrument to measure the family-centredness of service delivery. |
<filename>Ska/Shell/tests/test_shell.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import pytest
from six.moves import cStringIO as StringIO
from Ska.Shell import (Spawn, RunTimeoutError, bash, tcsh, getenv, importenv,
tcsh_shell, bash_shell)
HAS_HEAD_CIAO = os.path.exists('/soft/ciao/bin/ciao.sh')
outfile = 'ska_shell_test.dat'
# Skip the entire test suite on Windows
pytestmark = pytest.mark.skipif(os.name == 'nt', reason='Ska.Shell not supported on Windows')
class TestSpawn:
def setup(self):
self.f = StringIO()
self.g = StringIO()
def test_ok(self):
spawn = Spawn(stdout=self.f)
spawn.run(['echo', 'hello world'])
assert spawn.exitstatus == 0
assert spawn.outlines == ['hello world\n']
assert self.f.getvalue() == 'hello world\n'
def test_os_error(self):
spawn = Spawn(stdout=None)
with pytest.raises(OSError):
spawn.run('bad command')
assert spawn.exitstatus is None
def test_timeout_error(self):
spawn = Spawn(shell=True, timeout=1, stdout=None)
with pytest.raises(RunTimeoutError):
spawn.run('sleep 5')
assert spawn.exitstatus is None
def test_grab_stderr(self, tmpdir):
tmp = tmpdir.join("test.out")
spawn = Spawn(stderr=tmp.open('w'), stdout=None)
spawn.run('perl -e "print STDERR 123456"', shell=True)
assert tmp.read() == '123456'
assert spawn.exitstatus == 0
def test_multi_stdout(self):
spawn = Spawn(stdout=[self.f, self.g])
spawn.run('perl -e "print 123456"', shell=True)
assert self.f.getvalue() == '123456'
assert self.g.getvalue() == '123456'
assert spawn.exitstatus == 0
def test_shell_error(self):
# With shell=True you don't get an OSError
spawn = Spawn(shell=True, stdout=None)
spawn.run('sadfasdfasdf')
assert spawn.exitstatus != 0
assert spawn.exitstatus is not None
class TestBash:
def test_bash(self):
outlines = bash('echo line1; echo line2')
assert outlines == ['line1', 'line2']
def test_bash_shell(self):
outlines, env = bash_shell('echo line1; echo line2')
assert outlines == ['line1', 'line2']
assert env == {}
def test_env(self):
envs = getenv('export TEST_ENV_VARA="hello"')
assert envs['TEST_ENV_VARA'] == 'hello'
outlines = bash('echo $TEST_ENV_VARA', env=envs)
assert outlines == ['hello']
def test_promptenv(self):
# Confirm that a messed up PS1 won't be a problem
# If the user messes with the prompts during use of the shell, all bets are off
# This test will just hang if the fix isn't implemented (should add pytest-timeout)
outlines = bash("echo 'hello'", env={'PS1': "(hello) \\s-\\v\\$"})
assert outlines == ['hello']
def test_importenv(self):
importenv('export TEST_ENV_VARC="hello"', env={'TEST_ENV_VARB': 'world'})
assert os.environ['TEST_ENV_VARC'] == 'hello'
assert os.environ['TEST_ENV_VARB'] == 'world'
def test_logfile(self):
logfile = StringIO()
cmd = 'echo line1; echo line2'
bash(cmd, logfile=logfile)
outlines = logfile.getvalue().splitlines()
# Note that starting bash may generate cruft at the beginning (e.g. the
# annoying message on catalina that zsh is now the default shell). So
# the tests reference expected output from the end of the log not the
# beginning.
assert outlines[-4].endswith(cmd)
assert outlines[-3] == 'line1'
assert outlines[-2] == 'line2'
assert outlines[-1].startswith('Bash')
@pytest.mark.skipif('not HAS_HEAD_CIAO', reason='Test requires /soft/ciao/bin/ciao.sh')
def test_ciao(self):
envs = getenv('. /soft/ciao/bin/ciao.sh')
test_script = ['printenv {}'.format(name) for name in sorted(envs)]
outlines = bash('\n'.join(test_script), env=envs)
assert outlines == [envs[name] for name in sorted(envs)]
class TestTcsh:
def test_tcsh(self):
outlines = tcsh('echo line1; echo line2')
assert outlines == ['line1', 'line2']
def test_tcsh_shell(self):
outlines, env = tcsh_shell('echo line1; echo line2')
assert outlines == ['line1', 'line2']
assert env == {}
def test_env(self):
envs = getenv('setenv TEST_ENV_VAR2 "hello"', shell='tcsh')
assert envs['TEST_ENV_VAR2'] == 'hello'
outlines = tcsh('echo $TEST_ENV_VAR2', env=envs)
assert outlines == ['hello']
def test_importenv(self):
importenv('setenv TEST_ENV_VAR3 "hello"', env={'TEST_ENV_VAR4': 'world'}, shell='tcsh')
assert os.environ['TEST_ENV_VAR3'] == 'hello'
assert os.environ['TEST_ENV_VAR4'] == 'world'
def test_logfile(self, tmpdir):
logfile = StringIO()
cmd = 'echo line1; echo line2'
tcsh(cmd, logfile=logfile)
out = logfile.getvalue()
outlines = out.strip().splitlines()
assert outlines[0].endswith(cmd)
assert outlines[1] == ''
assert outlines[2] == 'line1'
assert outlines[3] == 'line2'
assert outlines[4].startswith('Tcsh')
def test_ascds(self):
envs = getenv('source /home/ascds/.ascrc -r release', shell='tcsh')
test_script = ['printenv {}'.format(name) for name in sorted(envs)]
outlines = tcsh('\n'.join(test_script), env=envs)
assert outlines == [envs[name] for name in sorted(envs)]
def test_ciao(self):
envs = getenv('source /soft/ciao/bin/ciao.csh', shell='tcsh')
test_script = ['printenv {}'.format(name) for name in sorted(envs)]
outlines = tcsh('\n'.join(test_script), env=envs)
assert outlines == [envs[name] for name in sorted(envs)]
|
In what may be the largest study ever conducted on changes in Americans' religious involvement, researchers led by San Diego State University psychology professor Jean M. Twenge found that millennials are the least religious generation of the last six decades, and possibly in the nation's history.
The researchers -- including Ramya Sastry from SDSU, Julie J. Exline and Joshua B. Grubbs from Case Western Reserve University and W. Keith Campbell from the University of Georgia -- analyzed data from 11.2 million respondents from four nationally representative surveys of U.S. adolescents ages 13 to 18 taken between 1966 and 2014.
Recent adolescents are less likely to say that religion is important in their lives, report less approval of religious organizations, and report being less spiritual and spending less time praying or meditating. The results were published this month in the journal PLOS One.
"Unlike previous studies, ours is able to show that millennials' lower religious involvement is due to cultural change, not to millennials being young and unsettled," said Twenge, who is also the author of "Generation Me."
"Millennial adolescents are less religious than Boomers and GenX'ers were at the same age," Twenge continued. "We also looked at younger ages than the previous studies. More of today's adolescents are abandoning religion before they reach adulthood, with an increasing number not raised with religion at all."
Compared to the late 1970s, twice as many 12th graders and college students never attend religious services, and 75 percent more 12th graders say religion is "not important at all" in their lives. Compared to the early 1980s, twice as many high school seniors and three times as many college students in the 2010s answered "none" when asked their religion.
Compared to the 1990s, 20 percent fewer college students described themselves as above average in spirituality, suggesting that religion has not been replaced with spirituality.
"These trends are part of a larger cultural context, a context that is often missing in polls about religion," Twenge said. "One context is rising individualism in U.S. culture. Individualism puts the self first, which doesn't always fit well with the commitment to the institution and other people that religion often requires. As Americans become more individualistic, it makes sense that fewer would commit to religion." |
def generate_right_side(self):
self.rightSideWidget = QtWidgets.QWidget(self.app.searchTab)
self.rightSideLayout = QtWidgets.QVBoxLayout()
return self.rightSideWidget |
Possibilities for formal models of smart environments
This paper is devoted to a recently running project descript ion with a purpose to get some necessary feedback from the AmI community as to the project ambitions. The project intends to study possibilities of several formal approaches towards modeling intelligent environments based on principles of ambient intelligence. The main goal is in contributing towards theoretical foundations of ambient intelligence via modeling of intelligent environments functionality using three basic approaches: multi-agent systems of various kind, algebraic methods, and grammar systems and colonies, namely eco-grammar systems. |
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/XXUnknownSuperclass.h>
@class NSMutableArray;
__attribute__((visibility("hidden")))
@interface OADStyleMatrix : XXUnknownSuperclass {
@private
NSMutableArray *mFills; // 4 = 0x4
NSMutableArray *mStrokes; // 8 = 0x8
NSMutableArray *mEffects; // 12 = 0xc
NSMutableArray *mBgFills; // 16 = 0x10
}
- (id)init; // 0xbda31
- (void)dealloc; // 0x8d0d9
- (void)addFill:(id)fill; // 0x1886e5
- (unsigned)fillCount; // 0x2a6add
- (id)fillAtIndex:(unsigned)index; // 0x1b137d
- (id)fillAtIndex:(unsigned)index color:(id)color; // 0x2a6afd
- (void)addStroke:(id)stroke; // 0x189365
- (unsigned)strokeCount; // 0x2a6b55
- (id)strokeAtIndex:(unsigned)index; // 0x1b9bd5
- (id)strokeAtIndex:(unsigned)index color:(id)color; // 0x2a6b75
- (void)addEffects:(id)effects; // 0x189935
- (unsigned)effectsCount; // 0x2a6bcd
- (id)effectsAtIndex:(unsigned)index; // 0x1b9c49
- (id)effectsAtIndex:(unsigned)index color:(id)color; // 0x2a6bed
- (void)addBgFill:(id)fill; // 0x189959
- (unsigned)bgFillCount; // 0x2a6c75
- (id)bgFillAtIndex:(unsigned)index; // 0x1ad645
@end
|
// Extract page setup from settings.
GtkPageSetup* wxGtkPrintNativeData::GetPageSetupFromSettings(GtkPrintSettings* settings)
{
GtkPageSetup* page_setup = gtk_page_setup_new();
gtk_page_setup_set_orientation (page_setup, gtk_print_settings_get_orientation (settings));
GtkPaperSize *paper_size = gtk_print_settings_get_paper_size (settings);
if (paper_size != NULL)
gtk_page_setup_set_paper_size_and_default_margins (page_setup, paper_size);
return page_setup;
} |
Rep. Charlie Dent (R-Pa.), a key House moderate from a swing district, announced Thursday that he would not seek reelection next year for an eighth term.
"I've worked to instill stability, certainty, and predictability in Washington," Dent, a co-chairman of the moderate Tuesday Group, said in a statement.
"Regrettably, that has not been easy given the disruptive outside influences that profit from increased polarization and ideological rigidity that leads to dysfunction, disorder, and chaos," he said.
Dent indicated that he decided in "mid-summer" to retire from Congress after having "periodic discussions" with family about his future in public office since the 2013 government shutdown.
ADVERTISEMENT
The Pennsylvania Republican had a history of stressing bipartisanship, including urging Democratic support for a bill to fund the government earlier in the summer, which had been stalled by infighting among Republicans.
He had also criticized the White House for failing to communicate key principles on health care reform after Republicans failed to repeal and replace ObamaCare in July.
In his statement announcing his retirement, Dent touted his appointment to the House Ethics Committee for 2015-2016, noting that it is "the only Committee that requires bipartisan cooperation to act."
"I promise to continue my role, both inside and soon outside the government, of giving voice to the sensible center and working to solve problems for the American people through smart policy- the product of negotiation, cooperation and inevitably, compromise," he said.
Dent joins other Republicans from potential swing districts who have announced their retirement, including Reps. Dave Reichert David (Dave) George ReichertYoder, Messer land on K Street Ex-GOP lawmaker from Washington joins lobbying firm Outgoing GOP rep says law enforcement, not Congress should conduct investigations MORE (R-Wash.) and Ileana Ros-Lehtinen (R-Fla.).
Dent represents Pennsylvania's 15th District, which President Trump won in 2016 with 51.8 percent of the vote.
His district includes all of Lehigh County and parts of Berks County, Dauphin County, Lebanon County and Northampton County. Lehigh County and Dauphin County voted in favor of Democratic nominee Hillary Clinton Hillary Diane Rodham ClintonSanders: 'I fully expect' fair treatment by DNC in 2020 after 'not quite even handed' 2016 primary Sanders: 'Damn right' I'll make the large corporations pay 'fair share of taxes' Former Sanders campaign spokesman: Clinton staff are 'biggest a--holes in American politics' MORE in 2016, while Trump won the other three counties.
— Updated: 8:45 p.m. |
<filename>src/hardware/platforms/M1/JointM1.h
/**
* \file JointM1.h
* \author <NAME>, <NAME> borrowing heavily from <NAME>
* \brief An M1 actuated joint
* \version 0.1
* \date 2020-07-08
*
* \copyright Copyright (c) 2020
*
*/
#ifndef JointM1_H_INCLUDED
#define JointM1_H_INCLUDED
#include <cmath>
#include "Joint.h"
#include "KincoDrive.h"
/**
* \brief M1 actuated joint, using Kinco drive.
*
*/
class JointM1 : public Joint {
private:
double qMin, qMax, dqMin, dqMax, tauMin, tauMax;
double d2j_Pos, d2j_Vel, d2j_Trq, j2d_Pos, j2d_Vel, j2d_Trq;
double d2r, r2d;
short int sign;
int encoderCounts; //Encoder counts per turn
double reductionRatio; // Reduction ratio due to gear head
double Ipeak; //Kinco FD123 peak current
double motorTorqueConstant; //SMC60S-0020 motor torque constant
// KincoDrive *drive;
/**
* \brief Conversion between drive unit (encoder count) and joint unit (radian).
*
* \return drive unit for low-level control purpose
* \return joint unit for high-level control purpose
*/
double driveUnitToJointPosition(int driveValue);
int jointPositionToDriveUnit(double jointValue);
double driveUnitToJointVelocity(int driveValue);
int jointVelocityToDriveUnit(double jointValue);
double driveUnitToJointTorque(int driveValue);
int jointTorqueToDriveUnit(double jointValue);
motorProfile posControlMotorProfile{4000000, 240000, 240000};
public:
JointM1(int jointID, double q_min, double q_max, short int sign_ = 1, double dq_min = 0, double dq_max = 0, double tau_min = 0, double tau_max = 0, KincoDrive *drive = NULL, const std::string& name="");
~JointM1();
bool updateValue();
/**
* \brief Check if current velocity and torque are within limits.
*
* \return OUTSIDE_LIMITS if outside the limits (!), SUCCESS otherwise
*/
setMovementReturnCode_t safetyCheck();
setMovementReturnCode_t setPosition(double qd);
setMovementReturnCode_t setVelocity(double dqd);
setMovementReturnCode_t setTorque(double taud);
bool initNetwork();
/**
* \brief Get error message
*
* \return true if succesful
* \return false if drive is currently not in the correct state to enable
*/
void errorMessage(setMovementReturnCode_t errorCode);
};
#endif
|
<reponame>tranquangduy/dranim
import { ApolloContext, InMemoryCache } from '@masterthesis/shared';
import { graphql } from 'graphql';
import { addMockFunctionsToSchema } from 'graphql-tools';
import schema, { resolvers } from '../../../src/graphql/schema';
import { doTestWithDb, QueryTestCase } from '../../test-utils';
import { anonymUserTest } from './anonym-user';
import { calculationsTest } from './calculations';
import { datasetTest } from './dataset';
import { datasetsTest } from './datasets';
import { resultsTest } from './results';
import { unknownDatasetTest } from './unknown-dataset';
import { unknownWorkspaceTest } from './unknown-workspace';
import { uploadsTest } from './uploads';
import { userTest } from './user';
import { workspaceTest } from './workspace';
import { workspacesTest } from './workspaces';
const cases: Array<QueryTestCase> = [
calculationsTest,
datasetTest,
unknownDatasetTest,
datasetsTest,
workspacesTest,
workspaceTest,
unknownWorkspaceTest,
uploadsTest,
anonymUserTest,
userTest,
resultsTest
];
describe('Query Tests', () => {
addMockFunctionsToSchema({
schema,
preserveResolvers: true
});
cases.forEach(obj => {
const { id, query, expected, beforeTest } = obj;
test(`should pass test: ${id}`, () =>
doTestWithDb(async db => {
const reqContext: ApolloContext = {
db,
userId: '123',
cache: new InMemoryCache()
};
const { variables, reqContext: overwrittenContext } = await beforeTest(
reqContext
);
const { data, errors } = await graphql(
schema,
query,
null,
{
...reqContext,
cache: new InMemoryCache(),
...overwrittenContext
},
variables,
undefined,
resolvers
);
expect(errors).toBeUndefined();
expect(data).toMatchObject(expected);
}));
});
});
|
def update_points(api: ApiClient, points_id, points, note):
awarded_at = int(time.time())
api.update_shadow_assignment_points(points_id, points, note, awarded_at) |
/**
* tests cat. This one has IDREFs.
*/
public void testCat() throws Exception {
Cat cat = new Cat();
Circle face = new Circle();
face.setRadius(20);
cat.setFace(face);
Triangle ear = new Triangle();
ear.setBase(5);
ear.setHeight(10);
ear.setId("earId");
cat.setEars(Arrays.asList(ear, ear));
cat.setEyes(new Triangle[] {ear, ear});
Line noseLine = new Line();
noseLine.setId("noseId");
Line mouthLine = new Line();
mouthLine.setId("mouthLine");
cat.setNose(noseLine);
cat.setMouth(mouthLine);
cat.setWhiskers(Arrays.asList(noseLine, mouthLine));
JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
ObjectMapper catMapper = provider.locateMapper(Cat.class, MediaType.APPLICATION_JSON_TYPE);
ObjectMapper clientMapper = new ObjectMapper();
ByteArrayOutputStream out = new ByteArrayOutputStream();
catMapper.writeValue(out, cat);
shapes.json.animals.Cat clientCat = clientMapper.readValue(new ByteArrayInputStream(out.toByteArray()), shapes.json.animals.Cat.class);
shapes.json.Circle clientFace = clientCat.getFace();
assertEquals(20, clientFace.getRadius());
assertEquals(2, clientCat.getEars().size());
shapes.json.Triangle[] clientEars = clientCat.getEars().toArray(new shapes.json.Triangle[2]);
assertNotSame("referential integrity should NOT have been preserved since Jackson doesn't support it yet", clientEars[0], clientEars[1]);
assertEquals(5, clientEars[0].getBase());
assertEquals(10, clientEars[0].getHeight());
assertEquals("earId", clientEars[0].getId());
assertEquals(5, clientEars[1].getBase());
assertEquals(10, clientEars[1].getHeight());
assertEquals("earId", clientEars[1].getId());
shapes.json.Triangle[] clientEyes = clientCat.getEyes();
assertEquals(2, clientEyes.length);
assertNotSame(clientEyes[0], clientEyes[1]);
assertEquals(5, clientEyes[0].getBase());
assertEquals(10, clientEyes[0].getHeight());
assertEquals("earId", clientEyes[0].getId());
assertEquals(5, clientEyes[1].getBase());
assertEquals(10, clientEyes[1].getHeight());
assertEquals("earId", clientEyes[1].getId());
assertFalse("The ears should NOT be the same object as one of the eyes since Jackson doesn't support referential integrity.", clientEars[0] == clientEyes[0] || clientEars[0] == clientEyes[1]);
shapes.json.Line clientNose = clientCat.getNose();
assertEquals("noseId", clientNose.getId());
shapes.json.Line clientMouth = clientCat.getMouth();
assertEquals("mouthLine", clientMouth.getId());
assertFalse("The nose line should NOT also be one of the whiskers since Jackson doesn't support referential integrity.", clientCat.getWhiskers().contains(clientNose));
assertFalse("The mouth line should NOT also be one of the whiskers since Jackson doesn't support referential integrity.", clientCat.getWhiskers().contains(clientMouth));
out = new ByteArrayOutputStream();
clientMapper.writeValue(out, clientCat);
cat = catMapper.readValue(new ByteArrayInputStream(out.toByteArray()), Cat.class);
face = cat.getFace();
assertEquals(20, face.getRadius());
assertEquals(2, cat.getEars().size());
Triangle[] ears = cat.getEars().toArray(new Triangle[2]);
assertNotSame("referential integrity should NOT have been preserved since Jackson doesn't support referential integrity.", ears[0], ears[1]);
assertEquals(5, ears[0].getBase());
assertEquals(10, ears[0].getHeight());
assertEquals("earId", ears[0].getId());
Triangle[] eyes = cat.getEyes();
assertEquals(2, eyes.length);
assertNotSame(eyes[0], eyes[1]);
assertEquals(5, eyes[0].getBase());
assertEquals(10, eyes[0].getHeight());
assertEquals("earId", eyes[0].getId());
assertEquals(5, eyes[1].getBase());
assertEquals(10, eyes[1].getHeight());
assertEquals("earId", eyes[1].getId());
assertFalse("The ears should NOT be the same object as one of the eyes since Jackson doesn't support referential integrity.", ears[0] == eyes[0] || ears[0] == eyes[1]);
Line nose = cat.getNose();
assertEquals("noseId", nose.getId());
Line mouth = cat.getMouth();
assertEquals("mouthLine", mouth.getId());
assertFalse("The nose line should also be one of the whiskers since Jackson doesn't support referential integrity.", cat.getWhiskers().contains(nose));
assertFalse("The mouth line should also be one of the whiskers since Jackson doesn't support referential integrity.", cat.getWhiskers().contains(mouth));
} |
/**
* Adds the given path component to the beginning of the current documentation path.
*
* @param pathComponent the path component to add
*/
public void addPath(String pathComponent) {
if (pathComponent != null) {
docPath.insert( 0, pathComponent );
}
} |
//===----------------------------------------------------------------------===//
// WebAssembly ABI Implementation
//
// This is a very simple ABI that relies a lot on DefaultABIInfo.
//===----------------------------------------------------------------------===//
class WebAssemblyABIInfo final : public DefaultABIInfo {
public:
explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
: DefaultABIInfo(CGT) {}
private:
ABIArgInfo classifyReturnType(QualType RetTy) const;
ABIArgInfo classifyArgumentType(QualType Ty) const;
void computeInfo(CGFunctionInfo &FI) const override {
if (!getCXXABI().classifyReturnType(FI))
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
for (auto &Arg : FI.arguments())
Arg.info = classifyArgumentType(Arg.type);
}
Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
QualType Ty) const override;
} |
OFDM technology anti-multipath performance analysis in China Mobile Multimedia Broadcasting (CMMB) system
The Orthogonal Frequency Division Multiplexing (OFDM) is one of the key technologies for new moblie communication. Multipath interference to send and receive signals. In the China Mobile Multimedia Broadcasting (CMMB) system will cause serious SNR loss, influence on the reliability of the system and timing accuracy. Through the research of OFDM technology of anti-jamming, understand many advantages of OFDM technology anti-multipath performace, combined with the simulation tool matlab simulation under Rayleigh channel, verify its under the condition of the signal-to-noise ratio of 20dB error rate have obvious improvement, proves that ofdm technology in CMMB system has a good anti-multipath performance, to improve the overall performance of the whole CMMB system, using CMMB system for navigation and timing for the future laid a good foundation. |
def check_setup(engine):
with engine.connect() as conn:
for row in conn.execute(select([Config]).where(Config.key == 'setup')):
if row[2] == '1':
quit(1)
conn.close() |
<filename>User/Include/BootServices.h
/** @file
Copyright (c) 2020, PMheart. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
**/
#ifndef OC_USER_BOOT_SERVICES_H
#define OC_USER_BOOT_SERVICES_H
#include <Uefi.h>
#include <Library/UefiLib.h>
#include <Library/UefiApplicationEntryPoint.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/DebugLib.h>
#include <stdio.h>
extern EFI_BOOT_SERVICES mBootServices;
extern EFI_SYSTEM_TABLE mSystemTable;
extern EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL mConOut;
STATIC
EFI_TPL
EFIAPI
DummyRaiseTPL (
IN EFI_TPL NewTpl
);
STATIC
EFI_STATUS
EFIAPI
NullTextOutputString (
IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
IN CHAR16 *String
);
#endif // OC_USER_BOOT_SERVICES_H
|
<gh_stars>1-10
import * as HLS from '../../../../../src';
import * as utils from '../../../../helpers/utils';
describe('4_Playlists/4.3_Playlist-Tags/4.3.2_Media-Segment-Tags', () => {
// It applies to every Media Segment that appears after it in the
// Playlist until the next EXT-X-MAP tag or until the end of the
// playlist.
test('#EXT-X-MAP_01', () => {
let playlist;
// Until the end of the Playlist
playlist = HLS.parse(`
#EXTM3U
#EXT-X-VERSION:6
#EXT-X-TARGETDURATION:10
#EXTINF:10,
http://example.com/1
#EXT-X-MAP:URI="http://example.com/map-1"
#EXTINF:10,
http://example.com/2
#EXTINF:10,
http://example.com/3
`);
expect(playlist.segments[0].map).toBeFalsy();
expect(playlist.segments[1].map).toBeTruthy();
expect(playlist.segments[2].map).toBeTruthy();
// Until the next EXT-X-MAP tag
playlist = HLS.parse(`
#EXTM3U
#EXT-X-VERSION:6
#EXT-X-TARGETDURATION:10
#EXT-X-MAP:URI="http://example.com/map-1"
#EXTINF:10,
http://example.com/1
#EXTINF:10,
http://example.com/2
#EXT-X-MAP:URI="http://example.com/map-2"
#EXTINF:10,
http://example.com/3
`);
expect(playlist.segments[0].map.uri).toBe('http://example.com/map-1');
expect(playlist.segments[1].map.uri).toBe('http://example.com/map-1');
expect(playlist.segments[2].map.uri).toBe('http://example.com/map-2');
HLS.stringify(playlist);
});
// URI: This attribute is REQUIRED.
test('#EXT-X-MAP_02', () => {
utils.parseFail(`
#EXTM3U
#EXT-X-VERSION:6
#EXT-X-TARGETDURATION:10
#EXT-X-MAP:BYTERANGE="256@128"
#EXTINF:10,
http://example.com/1
`);
utils.bothPass(`
#EXTM3U
#EXT-X-VERSION:6
#EXT-X-TARGETDURATION:10
#EXT-X-MAP:URI="http://example.com/map-1",BYTERANGE="256@128"
#EXTINF:10,
http://example.com/1
`);
});
// Use of the EXT-X-MAP tag in a Media Playlist that contains the
// EXT-X-I-FRAMES-ONLY tag REQUIRES a compatibility version number of 5
// or greater.
// URI: This attribute is REQUIRED.
test('#EXT-X-MAP_03', () => {
utils.parseFail(`
#EXTM3U
#EXT-X-VERSION:4
#EXT-X-TARGETDURATION:10
#EXT-X-I-FRAMES-ONLY
#EXT-X-MAP:URI="http://example.com/map-1",BYTERANGE="256@128"
#EXTINF:10,
http://example.com/1
`);
utils.bothPass(`
#EXTM3U
#EXT-X-VERSION:5
#EXT-X-TARGETDURATION:10
#EXT-X-I-FRAMES-ONLY
#EXT-X-MAP:URI="http://example.com/map-1",BYTERANGE="256@128"
#EXTINF:10,
http://example.com/1
`);
});
// Use of the EXT-X-MAP tag in a Media Playlist that DOES
// NOT contain the EXT-X-I-FRAMES-ONLY tag REQUIRES a compatibility
// version number of 6 or greater.
test('#EXT-X-MAP_04', () => {
utils.parseFail(`
#EXTM3U
#EXT-X-VERSION:5
#EXT-X-TARGETDURATION:10
#EXT-X-MAP:URI="http://example.com/map-1",BYTERANGE="256@128"
#EXTINF:10,
http://example.com/1
`);
utils.bothPass(`
#EXTM3U
#EXT-X-VERSION:6
#EXT-X-TARGETDURATION:10
#EXT-X-MAP:URI="http://example.com/map-1",BYTERANGE="256@128"
#EXTINF:10,
http://example.com/1
`);
});
// The tag place should be preserved
test('#EXT-X-MAP_05', () => {
const sourceText = `
#EXTM3U
#EXT-X-VERSION:6
#EXT-X-TARGETDURATION:10
#EXT-X-MAP:URI="http://example.com/map-1"
#EXTINF:10,
http://example.com/1
#EXTINF:10,
http://example.com/2
#EXT-X-MAP:URI="http://example.com/map-2"
#EXTINF:10,
http://example.com/3
#EXTINF:10,
http://example.com/4
`;
const obj = HLS.parse(sourceText);
const text = HLS.stringify(obj);
expect(text).toBe(utils.stripCommentsAndEmptyLines(sourceText));
});
// The same tag can appear multiple times
test('#EXT-X-MAP_06', () => {
const sourceText = `
#EXTM3U
#EXT-X-VERSION:6
#EXT-X-TARGETDURATION:10
#EXT-X-MAP:URI="http://example.com/map-1"
#EXTINF:10,
http://example.com/1
#EXT-X-MAP:URI="http://example.com/map-2"
#EXTINF:10,
http://example.com/2
#EXT-X-MAP:URI="http://example.com/map-1"
#EXTINF:10,
http://example.com/3
#EXT-X-MAP:URI="http://example.com/map-2"
#EXTINF:10,
http://example.com/4
`;
const obj = HLS.parse(sourceText);
const text = HLS.stringify(obj);
expect(text).toBe(utils.stripCommentsAndEmptyLines(sourceText));
});
});
|
Interior Minister Chaudhry Nisar Ali Khan will not be able to hold his press conference today due to an extreme backache, said his spokesperson on Sunday.
Chaudhry Nisar has been recommended complete bed rest, and the press conference has been rescheduled for Monday at 5pm, according to his spokesperson.
Insisting that the press conference was delayed solely because of the interior minister's ill health, the spokesperson requested the media to avoid reading too much into the matter.
Earlier, TV channels had reported that federal ministers Saad Rafiq, Shahid Khaqan Abbasi and Rana Tanvir Hussain met Chaudhry Nisar on Saturday to persuade him to cancel his press conference where, the channels claimed, he would announce an end to his 35-year association with Prime Minister Nawaz Sharif.
This was the only news report about him in recent days that was not rebutted by the interior ministry.
Interior minister is reported to have been unhappy with the way some PML-N leaders handled Panama Papers crisis
When contacted, a spokesperson for the minister had said that he had seen none of the ministers coming to Punjab House to hold a meeting with Chaudhry Nisar.
Abbasi said that he had not held a meeting with the interior minister on Saturday to convince him to change his plan. Giving his personal assessment, he said there were no differences in the PML-N, and that "Nisar is going nowhere”.
The interior minister had attended a meeting of the federal cabinet on July 13 where members of the cabinet reposed confidence in the PM’s leadership. But he skipped two important meetings of the PML-N after that.
While many members of the cabinet kept on issuing vociferous statements against the Joint Investigation Team constituted in the Panama Papers case and some even indirectly uttered remarks against the judiciary, Chaudhry Nisar was not among the crowd as he chose to remain silent on the issue at the height of the controversy. |
<gh_stars>0
import numpy as np
import pathlib
from .core import legendre2ggf, stress2ggf, stress2legendre # noqa: F401
from . import lut
from . import stress
from .stress.geometry import fiber_distance_capillary # noqa: F401
def get_ggf(model, semi_major, semi_minor, object_index, medium_index,
effective_fiber_distance=100e-6, mode_field_diameter=3e-6,
power_per_fiber=.6, wavelength=1064e-9, poisson_ratio=0.5,
n_poly=120, use_lut=None, verbose=False):
"""Model the global geometric factor
Parameters
----------
model: str
Model to use, one of: `boyde2009`
semi_major: float
Semi-major axis of an ellipse fit to the object perimeter [m]
semi_minor: float
Semi-minor axis of an ellipse fit to the object perimeter [m]
object_index: float
Refractive index of the object
medium_index: float
Refractive index of the surrounding medium
effective_fiber_distance: float
Effective distance between the two trapping fibers relative
to the medium refractive index [m]. For an open setup, this is
the physical distance between the fibers. For a closed setup
(capillary), this distance takes into account the refractive
indices and thicknesses of the glass capillary and index
matching gel. For the closed setup, the convenience function
:func:`ggf.fiber_distance_capillary` can be used.
mode_field_diameter: float
The mode field diameter MFD of the fiber used [m]. Note that
the MFD is dependent on the wavelength used. If the
manufacturer did not provide a value for the MFD, the MFD
can be approximated as ``3*wavelenth`` for a single-mode
fiber.
power_per_fiber: float
The laser power coupled into each of the fibers [W]
wavelength: float
The laser wavelength used for the trap [m]
poisson_ratio: float
The Poisson's ratio of the stretched material. Set this
to 0.5 for volume conservation.
n_poly: int
Number of Legendre polynomials to use for computing the GGF.
Note that only even Legendre polynomials are used and thus,
this number is effectively halved. To reproduce the GGF as
computed with the Boyde2009 Matlab script, set this value
to `None`.
use_lut: None, str, pathlib.Path or bool
Use look-up tables to compute the GGF. If set to `None`,
the internal LUTs will be used or the GGF is computed if
it cannot be found in a LUT. If `True`, the internal LUTs
will be used and a `NotInLUTError` will be raised if the
GGF cannot be found there. Alternatively, a path to a
LUT hdf5 file can be passed.
verbose: int
Increases verbosity
Returns
-------
ggf: float
global geometric factor
"""
if use_lut not in [False]:
try:
if isinstance(use_lut, (str, pathlib.Path)):
lut_path = use_lut
else:
lut_path = None
ggf = lut.get_ggf_lut(
model=model,
semi_major=semi_major,
semi_minor=semi_minor,
object_index=object_index,
medium_index=medium_index,
effective_fiber_distance=effective_fiber_distance,
mode_field_diameter=mode_field_diameter,
power_per_fiber=power_per_fiber,
wavelength=wavelength,
poisson_ratio=poisson_ratio,
n_poly=n_poly,
lut_path=lut_path,
verbose=verbose)
except lut.NotInLUTError:
if use_lut: # user specifically defined to ONLY use LUT
raise
else: # force computation of the GGF
ggf = get_ggf(
model=model,
semi_major=semi_major,
semi_minor=semi_minor,
object_index=object_index,
medium_index=medium_index,
effective_fiber_distance=effective_fiber_distance,
mode_field_diameter=mode_field_diameter,
power_per_fiber=power_per_fiber,
wavelength=wavelength,
poisson_ratio=poisson_ratio,
n_poly=n_poly,
use_lut=False,
verbose=verbose)
else:
theta, sigma = stress.get_stress(
model=model,
semi_major=semi_major,
semi_minor=semi_minor,
object_index=object_index,
medium_index=medium_index,
effective_fiber_distance=effective_fiber_distance,
mode_field_diameter=mode_field_diameter,
power_per_fiber=power_per_fiber,
wavelength=wavelength,
verbose=verbose)
if n_poly is None:
# number of orders (estimate from Boyde 2009)
alpha = semi_minor * 2 * np.pi / wavelength # size parameter
n_poly = np.int(np.round(2 + alpha + 4 * (alpha)**(1 / 3) + 10))
else:
n_poly = int(np.round(n_poly))
ggf = stress2ggf(stress=sigma,
theta=theta,
poisson_ratio=poisson_ratio,
n_poly=n_poly)
return ggf
|
/**
* The Class Machine.
*/
@Entity
public class Machine extends Persistent {
private String hostAddress;
private String canonicalHostName;
@ManyToOne
private MachineGroup machineGroup;
/**
* Instantiates a new machine.
*/
protected Machine() {
}
/**
* Instantiates a new machine.
*
* @param hostAddress the host address
* @param canonicalHostName the canonical host name
* @param machineGroup the machine group
*/
public Machine(String hostAddress, String canonicalHostName, MachineGroup machineGroup) {
this.hostAddress = hostAddress;
this.canonicalHostName = canonicalHostName;
this.machineGroup = machineGroup;
}
/**
* Gets the host address.
*
* @return the host address
*/
public String getHostAddress() {
return hostAddress;
}
/**
* Gets the canonical host name.
*
* @return the canonical host name
*/
public String getCanonicalHostName() {
return canonicalHostName;
}
/**
* Gets the machine group.
*
* @return the machine group
*/
public MachineGroup getMachineGroup() {
return machineGroup;
}
/**
* New machine.
*
* @return the machine
*/
public static Machine newMachine() {
try {
InetAddress address = InetAddress.getLocalHost();
return new Machine(address.getHostAddress(), address.getCanonicalHostName(), null);
} catch (UnknownHostException x) {
throw new RuntimeException(x);
}
}
} |
def _check_ver_change(self, datapath):
try:
version = os.environ['SUGAR_BUNDLE_VERSION']
except KeyError:
version = 'unknown'
filename = 'version.dat'
version_data = []
new_version = True
try:
file_handle = open(os.path.join(datapath, filename), 'r')
if file_handle.readline() == version:
new_version = False
file_handle.close()
except IOError:
_logger.debug("Couldn't read version number.")
version_data.append(version)
try:
file_handle = open(os.path.join(datapath, filename), 'w')
file_handle.writelines(version_data)
file_handle.close()
except IOError:
_logger.debug("Couldn't write version number.")
return new_version |
<filename>code/CNN_LSTM/train.py
import os
import keras
from keras.layers import concatenate
from sklearn.metrics import cohen_kappa_score
import math
import random
from keras import optimizers
import numpy as np
import scipy.io as spio
from sklearn.metrics import f1_score, accuracy_score
np.random.seed(0)
from keras.preprocessing import sequence
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Layer,Dense, Dropout, Input, Activation, TimeDistributed, Reshape
from keras.layers import GRU, Bidirectional
from keras.layers import Conv1D, Conv2D, MaxPooling2D, Flatten, BatchNormalization, LSTM, ZeroPadding2D, GlobalAveragePooling2D
from keras.callbacks import History
from keras.models import Model
from keras.layers.noise import GaussianNoise
from collections import Counter
from sklearn.utils import class_weight
from myModel import build_model
import sys
sys.path.append("..")
from loadData import *
from utils import *
n_rec = 8
batch_size = 128
n_ep = 8
fs = 200;
w1 = 200;
step = 50; #0.25 s
# half_size of the sliding window in samples
w_len = (20*50+200)
data_dim = w1
half_prec = 50
prec = 1
n_cl = 2
data_dir = './../../data/files/'
f_set = './../../data/file_sets.mat'
create_tmp_dirs(['./models/', './predictions/'])
mat = spio.loadmat(f_set)
files_train = []
files_val = []
files_test = []
skip = 10
tmp = mat['files_train']
for i in range(len(tmp)):
file = [str(''.join(l)) for la in tmp[i] for l in la]
files_train.extend(file)
tmp = mat['files_val']
for i in range(len(tmp)):
file = [str(''.join(l)) for la in tmp[i] for l in la]
files_val.extend(file)
tmp = mat['files_test']
for i in range(len(tmp)):
file = [str(''.join(l)) for la in tmp[i] for l in la]
files_test.extend(file)
def my_generator(data_train, targets_train, sample_list, shuffle = True, batch_size = 200):
if shuffle:
random.shuffle(sample_list)
sample_list = sample_list[::skip]
while True:
for batch in batch_generator(sample_list, batch_size):
batch_data = []
batch_targets = []
for sample in batch:
[f, b, e, c] = sample
sample_xx1 = data_train[f][c][b:e]
sample_xx2 = data_train[f][2][b:e]
sample_xx = np.concatenate( ( sample_xx1, sample_xx2 ), axis = 2 )
sample_yy = targets_train[f][c][b:e]
sample_x = []
sample_y = []
z = 0
while z<len(sample_xx)-w1:
sample_x.append(sample_xx[z:z+w1])
tmp_lbl = sample_yy[z+w1//2-20:z+w1//2+20]
a = Counter(tmp_lbl)
r = a.most_common(1)[0][0]
sample_y.append(r)
z += step
print(len(sample_x))
trgt = np.stack(sample_y, axis=0)
sample_x = np.stack(sample_x, axis=0)
batch_data.append(sample_x)
batch_targets.append( np.stack(trgt, axis=0))
batch_data = np.stack(batch_data, axis=0)
batch_targets = np.stack(batch_targets, axis=0)
batch_targets = np.array(batch_targets)
batch_targets_tmp = np.copy(batch_targets)
batch_targets[batch_targets==2] = 0
batch_targets[batch_targets==3] = 0
batch_targets = np_utils.to_categorical(batch_targets, n_cl)
batch_data = (batch_data +100)/200
batch_data = np.clip(batch_data, 0, 1)
y = batch_targets_tmp
s_w = np.zeros((y.shape[0], y.shape[1]))
for i in range(y.shape[0]):
for j in range(y.shape[1]):
s_w[i, j] = cl_w[y[i,j]]
yield batch_data, batch_targets, s_w
n_channels = 3
st0 = classes_global(data_dir, files_train)
cl_w = [ 0.28157203, 3.57512078, 35.6736615, 7.10387778]
cl_w[2] = 0
cl_w[3] = 0
print("=====================")
print("class weights ")
print(cl_w)
print("=====================")
print("=====================")
print("Reading training dataset:")
( data_train, targets_train, N_samples) = load_data(data_dir,files_train, w_len)
N_samples = N_samples
print('N_samples ',N_samples)
print('w_len ',w_len)
print('batch_size ',batch_size)
N_batches = int(math.ceil((N_samples+0.0)/(batch_size)))
print('N batches ',N_batches)
print("=====================")
print("Reading validation dataset:")
( data_val, targets_val, N_samples_val) = load_data(data_dir,files_val, w_len)
# create indexes of samples
# each element is [file number in data_train, index in its targets, index of the beginning, index of the end of the window]
def create_sample_list(targets_train):
sample_list = []
for ch in range(2):
for i in range(len(targets_train)):
l= len(targets_train[i])
for j in range((len(targets_train[i][0])-2*w_len)//prec):
mid = j*prec
# we add the padding size
mid += w_len//2
wnd_begin = mid-w_len//2
wnd_end = mid+w_len//2
sample_list.append([i,wnd_begin, wnd_end, ch ])
return sample_list
sample_list_val = []
for i in range(len(targets_val)):
sample_list_val.append([])
l= len(targets_val[i][0])
kk = (len(targets_val[i][0])-w1-w_len)//prec
wnd_end = kk*prec+w1
sample_list_val[i].append([i, w_len//2, wnd_end+w_len//2, 0])
ordering = 'tf';
keras.backend.common.set_image_dim_ordering(ordering)
learning_rate = 0.1
decay_rate = learning_rate / n_ep
[ model] = build_model(data_dim, n_channels, n_cl)
Nadam = optimizers.Nadam( clipnorm=1.)
model.compile(optimizer=Nadam, loss='categorical_crossentropy', metrics=['accuracy'], sample_weight_mode="temporal")
print(model.summary())
print(model.metrics_names)
history = History()
K_cv_tmp = []
K_tst_tmp = []
K_val = np.zeros( (n_ep, n_cl) )
K_tst = np.zeros( (n_ep, n_cl) )
acc_val = []
acc_tst = []
acc_tr = []
K_tr = []
loss_tr = []
loss_tst = []
loss_val = []
sample_list = create_sample_list(targets_train)
for i in range(n_ep):
print("Epoch = " + str(i))
generator_train = my_generator(data_train, targets_train, sample_list, shuffle = True, batch_size = batch_size)
model.fit_generator(generator_train, steps_per_epoch = N_batches//skip, epochs = 1, verbose=1, initial_epoch=0 )
val_y_ = []
val_y = []
loss_val_tmp = []
f_list = files_val
val_l = []
for j in range(len(data_val)):
f = f_list[j]
generator_val = my_generator(data_val, targets_val, sample_list_val[j], shuffle = False)
scores = model.evaluate_generator( generator_val, 1, workers=1)
print(scores)
generator_val = my_generator(data_val, targets_val, sample_list_val[j], shuffle = False)
y_pred = model.predict_generator( generator_val, 1, workers=1)
val_y_tmp = []
generator_val = my_generator(data_val, targets_val, sample_list_val[j], shuffle = False)
for ii in range(int(math.ceil((len(sample_list_val[j],)+0.0)/batch_size))):
[x, y, _] = next(generator_val)
for k in range(y.shape[0]):
val_y_tmp.append( y[k] )
loss_val_tmp.append(scores[0])
val_y_tmp = np.stack(val_y_tmp, axis=0)
val_l.append(len(np.argmax(y_pred, axis=2).flatten()))
val_y_.extend( np.argmax(y_pred, axis=2).flatten() )
val_y.extend( np.argmax(val_y_tmp, axis=2).flatten() )
loss_val.append(np.mean(loss_val_tmp))
t1 = kappa_metric( val_y, val_y_, n_cl )
K_val_tmp = t1
K_val[i,:] = K_val_tmp
t2 = cohen_kappa_score(val_y, val_y_)
acc_val.append(t2)
print( "K val per class = ", t1 )
print( "K val = ", t2 )
print( "loss val = ", loss_val[-1] )
spio.savemat('./predictions_'+str(i)+'.mat', mdict={'val_y': val_y, 'val_y_': val_y_, 'val_l': val_l, 'files_test':files_test, 'files_val':files_val, 'acc_tr': acc_tr, 'loss_tr':loss_tr, 'loss_val':loss_val, 'acc_val':acc_val, 'K_val':K_val })
model.save('./models/model_ep'+str(i)+'.h5')
model.save('./model.h5')
spio.savemat('./predictions.mat', mdict={'val_y': val_y, 'val_y_': val_y_, 'val_l': val_l, 'files_test':files_test, 'files_val':files_val, 'acc_tr': acc_tr, 'loss_tr':loss_tr, 'loss_val':loss_val, 'acc_val':acc_val, 'K_val':K_val }) |
Microresonator for Microwave Cancer Therapy
This paper presents a numerical analysis on metallic micro/nanoparticles as LC-circuit resonators at microwave frequencies and with strong absorption for cancer therapy. We pushed the LC -structure design to the limit to provide an optimized structure within desired size limits, which can achieve resonance at the frequencies commonly used in interstitial microwave thermal therapies. Moreover, we discovered that the limitation of the microresonator is not the low resonance frequency tradeoff with the small size, but the low Q-value due to insufficient conductivity of materials. This issue can be solved by using multiple-layer-inductor design of LC structures, which could increase the Q-value linearly with the number of inductor layers, but at the cost of fabrication process complexity. |
<filename>src/sam/fx/helpers/FxConstants.java
package sam.fx.helpers;
import javafx.geometry.Insets;
public interface FxConstants {
Insets INSETS_5 = new Insets(5);
Insets INSETS_10 = new Insets(10);
}
|
package com.baeldung.listassert;
import org.apache.commons.collections4.CollectionUtils;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class OrderAgnosticListComparisonUnitTest {
private final List<Integer> first = Arrays.asList(1, 3, 4, 6, 8);
private final List<Integer> second = Arrays.asList(8, 1, 6, 3, 4);
private final List<Integer> third = Arrays.asList(1, 3, 3, 6, 6);
@Test
public void whenTestingForOrderAgnosticEquality_ShouldBeTrue() {
assertTrue(first.size() == second.size() && first.containsAll(second) && second.containsAll(first));
}
@Test
public void whenTestingForOrderAgnosticEquality_ShouldBeFalse() {
assertFalse(first.size() == third.size() && first.containsAll(third) && third.containsAll(first));
}
@Test
public void whenTestingForOrderAgnosticEquality_ShouldBeEqual() {
MatcherAssert.assertThat(first, Matchers.containsInAnyOrder(second.toArray()));
}
@Test
public void whenTestingForOrderAgnosticEquality_ShouldBeTrueIfEqualOtherwiseFalse() {
assertTrue(CollectionUtils.isEqualCollection(first, second));
assertFalse(CollectionUtils.isEqualCollection(first, third));
}
@Test
void whenTestingForOrderAgnosticEqualityBothList_ShouldBeEqual() {
assertThat(first).hasSameElementsAs(second);
}
@Test
void whenTestingForOrderAgnosticEqualityBothList_ShouldNotBeEqual() {
List<String> a = Arrays.asList("a", "a", "b", "c");
List<String> b = Arrays.asList("a", "b", "c");
assertThat(a).hasSameElementsAs(b);
}
}
|
Chitosan/Calcium–Alginate Encapsulated Flaxseed Oil on Dairy Cattle Diet: In Vitro Fermentation and Fatty Acid Biohydrogenation
Simple Summary Most unsaturated fatty acids in the ruminant’s diet are hydrogenated in their rumen so that the composition of the fatty acids entering the rumen and their output is significantly different. Therefore, minimizing the ruminal biohydrogenation process of unsaturated fatty acids is one of the most important issues for feed supplements manufacturers and animal nutritionists to increase the availability of these fatty acids in the intestine. In recent years, encapsulation has been used to preserve the active ingredient in livestock; it is a method used to control the release of feed additives during digestion. There is a clear need to find a more effective method by which unsaturated fatty acids present in fat supplements can be protected to bypass rumen environment and its biohydrogenation, without negative effect on digestive efficiency, and be available in lower digestive tracts. For these reasons, this study aims to evaluate the use of natural materials to encapsulate fats and their effect on in vitro fermentation and fatty acid biohydrogenation. The results indicated that the percentage of ruminal saturated fatty acids decreased by encapsulation of flaxseed oil with chitosan (14% and 7%). The percentage of oleic unsaturated fatty acid by encapsulating flaxseed oil with chitosan (14%) had a significant increase compared to the control treatment (p < 0.05). Encapsulation of flaxseed oil with chitosan (14%) reduced the unsaturated fatty acids of ruminal biohydrogenation. Abstract The aim of this study was to investigate the effect of using chitosan nanoparticles and calcium alginate in the encapsulation of flaxseed oil on the biohydrogenation of unsaturated fatty acids and in vitro fermentation. The experiments were performed in a completely randomized design with 7 treatments. The experimental treatments included: diets without oil additive (control), diet containing 7% flaxseed oil, diet containing 14% flaxseed oil, diet containing 7% oil encapsulated with 500 ppm chitosan nanocapsules, diet containing 14% flaxseed oil encapsulated with 1000 ppm chitosan nanocapsules, diet containing 7% of flaxseed oil encapsulated with 500 ppm of calcium alginate nanocapsules, diet containing 14% flaxseed oil encapsulated with 1000 ppm calcium alginate nanocapsules. The results showed that encapsulation of flaxseed oil with calcium alginate (14%) had a significant effect on gas production (p < 0.05). The treatment containing calcium alginate (14%) increased the digestibility of dry matter compared to the control treatment, but the treatments containing chitosan caused a significant reduction (p < 0.05). The results indicated that the percentage of ruminal saturated fatty acids decreased by encapsulation of flaxseed oil with chitosan (14% and 7%). The percentage of oleic unsaturated fatty acid by encapsulating flaxseed oil with chitosan (14%) had a significant increase compared to the control treatment (p < 0.05). As a result, encapsulating flaxseed oil with chitosan (14%) reduced the unsaturated fatty acids generated during ruminal biohydrogenation.
Introduction
The importance of using fats as an energy source in the diets of high-yielding ruminants, especially dairy cows at the beginning of lactation, has long been known for its negative energy balance . In addition, the physiological importance of some unsaturated fatty acids has led to the targeted use of various fatty acids regardless of energy supply . Nowadays, the use of oils and oilseeds in animal feed has been considered by researchers due to numerous biological roles. Reducing energy demand in livestock by reducing milk fat at the beginning of lactation by certain fatty acids , increasing the nutrition of carbohydrates and fats to meet the metabolic needs of livestock , and the tendency to increase the concentration of conjugated linoleic acid in livestock products due to its effects on human health can be cited as some of the reasons for this approach. However, when unprotected oils are fed to cows, there is an extensive hydrolyzation and biohydrogenation by ruminal microorganisms that results in marginal increases in passage to intestine . Moreover, potential detrimental side effects must be considered, such as altered rumen biohydrogenation pathways associated with alteration in digestive efficiency .
Biohydrogenation is the process in the rumen during which hydrogen is added to the double bonds of unsaturated fatty acids . Biohydrogenation is mainly performed by rumen bacteria, while it is not well known the protozoa role . However, it is accepted that ciliate protozoa are not directly involved in biohydrogenations activity , but actively contribute to lipolysis and influence biohydrogenation by different mechanisms. It seems that ciliate protozoa ingest and directly incorporate dietary PUFA in their cellular membranes, protecting them from hydrogenation by bacteria . Moreover, recent studies reported that rumen protozoa have a high content of vaccenic acid and conjugated linoleic acid , suggesting that they may give a significant contribution to these acids flow from the rumen . Most unsaturated fatty acids in the ruminant's diet are hydrogenated in their rumen so that the composition of the fatty acids entering the rumen and their output is significantly different.
Therefore, minimizing the ruminal biohydrogenation process of unsaturated fatty acids is one of the most important issues for feed supplements manufacturers and animal nutritionists to increase the availability of these fatty acids in the intestine . There are several ways to protect fats and oils from rumen biohydrogenation. Many techniques have been studied and developed to bypass ruminal biohydrogenation and degradation of unsaturated fatty acids. One of them is the utilization of rumen inert as their supplementation as calcium salts (although it provides little to no protection to polyunsaturated fatty acids). Differently, rumen-protected oils may represent an opportunity to achieve this goal . The use of new techniques, such as microencapsulation of fatty acids in the last decade, has been used by food industry researchers as an effective method to protect unsaturated fatty acids from oxidation and reduce unpleasant odors and tastes .
Encapsulation is when a substance or several substances are coated with or trapped within a substance or system. In recent years, a technology called encapsulation has been used to preserve the active ingredient in livestock and to create a proper product quality and effectiveness; it is a method used to control the release of feed additives during digestion. In recent years, studies have been done on encapsulation and its effect .
In studies on encapsulated plant application in livestock production, it has been emphasized that encapsulation application can be applied as a good strategy to increase the potency of herbal components that can be used instead of synthetic antioxidants and AGF . Like the antibacterial activity in the studies, it was determined that the antioxidant activity increased as a result of chitosan encapsulation .
Trends in demands for safer products have encouraged a search for natural alternatives to direct fed antibiotics. Chitosan (an N-acetyl-d-glucosamine polymer) is a natural non-toxic, biodegradable biopolymer derived from deacetylation of chitin, a major component of the shells of crustaceans. The antimicrobial activity of chitosan has been noted as one of its most interesting properties , which has led to evaluation of its use in ruminant nutrition . Apart from its biodegradable character in physiological conditions, chitosan has reactive amine and hydroxyl groups, which offer possibilities of graft reactions (i.e., carboxymethyl chitosan) and ionic interactions . Chitosan is polycationic at pH less than 6 and reacts easily with negatively charged compounds such as proteins, anionic polysaccharides, fatty acids, and phospholipids, which can structure and texture products that Chitosan is used in their production to affect. Due to the presence of amino groups in the structure of chitosan, this substance has a better solubility in acidic environments.
Alginic acid, or sodium and potassium alginates (ALG), is one of the biomaterials of the adhesive mucosa due to its cell compatibility, biocompatibility, biodegradability, SOL-GEL transfer properties, and chemical versatility, which allows further modifications. To make it possible to adapt its properties, it has been studied for drug delivery. This substance is prepared from different types of seaweed. The many benefits of this material have led to an increase in the interest of the scientific community in alginate as a platform for the development of new nanodrug delivery systems in recent decades . One of the most useful properties of alginate is its ability to crosslink in aqueous solutions by a mechanism through the carboxylic acid moiety of G units with calcium ions and in divalent cations (such as Ba 2+ , Ca 2+ , Zn 2+ ) to form a three-dimensional network. It has been used for over 3 decades to encapsulate a wide range of drugs, proteins, genes, and cells.
In the light of all this information, there is a clear need to find a more effective method by which unsaturated fatty acids present in fat supplements can be protected to bypass rumen environment and its biohydrogenation, without negative effect on digestive efficiency, and be available in lower digestive tracts. For these reasons, this study aims to evaluate the use of natural materials to encapsulate fats and their effect on in vitro fermentation and fatty acid biohydrogenation.
Experimental treatments were (1) control (diet without oil), (2) diet with 7% flaxseed oil, (3) diet with 14% flaxseed oil, (4) diet with 7% encapsulated flaxseed oil (500 ppm chitosan nanocapsule, (5) diet with 14% encapsulated flaxseed oil (1000 ppm chitosan nanocapsule, (6) diet with 7% encapsulated flaxseed oil (500 ppm calcium alginate nanocapsule), and (7) diet with 14% encapsulated flaxseed oil (1000 ppm calcium alginate nanocapsule. The diet contains alfalfa hay (21%), maize silage (19%), beet pulp (7%), wheat bran (2%), and dairy cattle concentrate (51%). The chemical composition of diet was DM 59%, CP 20%, NDF 38%, and ADF 20% (Table 1). Dairy cattle concentrate was purchased from feed manufactory (Eris ® Animal Feed Manufacture, Ahar, Iran). The chitosan and calcium alginate nanoparticles were prepared according to methods described by Hosseini et al. and Keawchaoon and Yoksan , with some modifications. Chitosan NPs and calcium alginate NPs were prepared separately using the oil-in-water emulsion technique in chitosan and calcium alginate solutions. Droplet solidification was carried out by pentasodium tripolyphosphate (PTP) solution to achieve nanoparticles (NPs) through the ionic gelation method. Briefly, two concentrations of chitosan and calcium alginate (1000 and 2000 ppm) in glacial acetic acid (1% (v/v)) were produced by stirring at room temperature (25 • C) for 12 h to the formation of aqueous phases. Büchner funnel and Whatman 42 paper were used to filtrate solutions after pH adjustment to 4.6 using NaOH (0.1 N). Then, Tween 80 (1%, w/v) was added to the aqueous solutions as a surfactant and stirred at 25 • C for 30 min to achieve homogeneous mixtures. The different levels of flaxseed oil (7 and 14%) were then gradually dropped in solutions prepared by chitosan and calcium alginate to produce four different mass ratios of chitosan to oil (500:7 and 1000: 14) and calcium alginate to oil (500:7 and 1000:14). At the same time, the agitation (700 rpm for 10 min) was carried out at room temperature to produce oil-in-water emulsions. PTP (0.3%, w/v) was then prepared in distilled water and flush-mixed with prepared emulsions to obtain two mass ratios of chitosan to PTP and calcium alginate to PTP of 1:1. Subsequently, the mixtures were held to agitation at 25 • C for 30 min to effect crosslinking. The same method without flaxseed oil addition was used for unloaded nanoparticles. The produced particles were collected by centrifuge (SIGMA 8K, Germany) at 10,000× g for 35 min (4 • C) and washed five times with Tween 80 solution 1% (v/v), then dispersed in distilled water and treated by ultrasonic homogenizer (TOPSONICS, UP400, Iran) at 60 W (6 min) with a sequence of 3 s sonication and 7 s rest. The obtained dispersions were then freeze-dried and stored until further analysis (for measuring the particle size and zeta potential).
Measurement of Particle Size and Zeta Potential
A dynamic light scattering (DLS) instrument measured the mean particle size and zeta potential of freshly prepared chitosan, and calcium alginate NPs were measured by a dynamic light scattering (DLS) instrument (Zetasizer Nano ZS90, Malvern, UK). Results were represented as the means of three measurements ± standard deviation. The Zeta potential of chitosan and calcium alginate nanoparticles was evaluated at pH 4.6 and 25 • C. One mg of NPs were added in 10 mL of distilled water to the preparation of nanoparticles stock solution. According to Dilbaghi et al. , clear zeta cells (disposable) with 15 runs and equipoise time of 2 min were used for scanning of 1 mL stock solution.
Encapsulation Efficiency
The percentage of encapsulated flaxseed oil for chitosan NPs and calcium alginate NPs were determined by ultraviolet-visible (UV-vis) spectrophotometry (Shimadzu UV 2450, Japan) according to Chopra et al.'s method after centrifugation the mixture at 11,000 rpm
Fourier Transform Infrared (FTIR) Characterization
The structural properties of chitosan and calcium alginate nanoparticles were analyzed at 25 • C by utilizing FTAR spectra (Bruker Co., Germany). The samples were mixed at the ratio of 1:100 with potassium bromide and pressed into a pallet for analysis. The spectra had a 4 cm −1 resolution and was recorded from 400 to 4000 cm −1 .
In Vitro Gas Production Technique
The method of Fedorah and Hrudey was used to measure gas production. First, the feedstuffs (all experimental treatments) were ground by a mill with a sieve diameter of 1 mm. The amount of 300 mg of each ground food was carefully weighed and transferred to 50 mL sterile serum bottles, and 5 repetitions were considered for each treatment for a total of 35 runs. Rumen fluid was prepared from 3 slaughtered sheep, mixed in a unique rumen fluid, and after straining by a four-layer mesh cloth inside the thermos flask (previously filled with sterile distilled water at 39 • C to avoid thermal shock to rumen fluid) and insufflating CO 2 to ensure the anaerobic environment, it was immediately transferred to the laboratory. After transport, it was mixed and blended under a CO 2 headspace for 30 s to remove any additional particles and/or attached organisms and then strained through 6 layers of cheesecloth . Before transferring ruminal fluid into serum bottles, it was mixed with a buffer prepared by McDougall in a ratio of 1:2 (ruminal fluid: buffer). In each bottle containing 300 mg of each experimental treatment, 20 mL of the mixture of ruminal fluid and buffer was added, and after anesthesia inside the bottle by infusion carbon dioxide gas, the bottle lid was closed with a rubber cap and metal press. It was tightly closed. All glasses were transferred to the shaker incubator at 120 rpm and at a temperature of 39 • C to measure the produced gas, and the operation of reading and recording the amount of gas produced due to food fermentation by Fedorah and Hrudey method (gas volume) in 2, 4,6,8,12,24,36,48,72, and 96 h after incubation. Ingredients and chemical composition of the experimental diet are shown in Table 1.
In Vitro Digestibility
This experiment was performed based on the gas production method. In this method, 15 replicates were prepared for each of the available treatments, and at 2, 4, 8, 12, and 24 h. Three replicates of each treatment were removed from the incubator, and all their contents were poured into laboratory falcons. All analysis for nutrient parameters performed before and after digestion and percentage of disappearance for each parameter was calculated as: (PB-PA)/PB, where PB is the quantity (g/kg) of parameter in the samples before the digestion and PA is the quantity (g/kg) of the parameter after digestion. Results were expressed as percentage . Dry matter (DM) was determined using standard procedures (method 930.15). Ash was determined by standard procedures (method 942.05) using a muffle furnace at 550 • C for 16 h. Fat was determined using the Soxhlet extraction procedure (Method 991.36), crude protein (CP) was determined by Kjeldahl N × 6.25 procedures (Method 968.06). Neutral detergent fiber (NDF) and acid detergent fiber (ADF) were determined with the ANKOM fiber analyzer according to Van Soest et al. and was corrected for residual acid-insoluble ash.
In Vitro Biohydrogenation
This experiment was also performed according to the method for measuring gas production and laboratory digestibility, with the difference that 9 repetitions are considered for each treatment and three replicates of each treatment are removed from the incubator at 2, 4, Animals 2022, 12, 1400 6 of 20 and 24 h. Their contents are stored at −20 • C to determine ruminal biohydrogenation , which is described below.
Preparation of Samples for Determination of Fatty Acid Profiles Fatty Acid Extraction
Azadmard-Damirchi and Dutta;s method was used to extract fatty acid from experimental treatments left over from incubation. In short, the procedure was as follows.
The ruminal fluid and the remaining sample after incubation were poured into an Erlenmeyer flask and 25 mL of 1: 1 chloroform solution was added to methanol. A magnet was then placed in each Erlenmeyer to accelerate homogenization and extraction and mixed for 10 min. Then, 60-65 mL of the above solution was added into each Erlenmeyer flask and stirred for 1 h every 5 min.
Erlenmeyer was kept at room temperature, then Erlenmeyer contents were filtered using a Buchner funnel and filter paper. The remaining water was separated using a Buchner funnel and the oil and solvent layer was separated using an evaporator. The extracted oils were stored at −20 • C for later use .
Methylation Procedure
About 10 mg of fat was dissolved in 0.5 mL of n-hexane in the test tube and then 2 mL of 0.01 M NaOH was added to the dry methanol. The test tubes containing these solutions were kept in a 60 • C water bath for 10 min. Next, it was kept in room air for 10 min, and after the reaction, the test tube was placed under cold water, and 2 mL of 20% salt solution and 1 mL of n-hexane were added. After complete mixing, it was centrifuged at 2000 rpm for 5 min and the hexane layer containing the fatty acid methyl ester derivative was separated . The fatty acid profile was determined with the model GC-mas (Agilent Technologies 7890B).
For GC-MS analysis, an Agilent 6890 gas chromatography with a 30 m to 0.25 mm HP-5MS capillary column coupled with an Agilent 5973 mass spectrometer (Agilent Technologies, Palo Alto, CA, USA) operating in EI mode at 70 eV was used. The injector and detector ports temperatures were set at 250 and 150 • C, respectively. Initially, the column temperature was held at 60 • C for 3 min and then was increased at a rate of 5 • C /min to 220 • C. The temperature of the column was held at 220 • C for 10 min.
Statistical Analysis
The obtained data were analyzed in a completely randomized statistical design according to the Proc mixed procedure of the SAS. To compare the means, Duncan's multiple range was used. Significance was set at p < 0.05, and the results were expressed as means and mean standard error. All the analysis was performed using SAS 9.1 software (2018).
Zeta Potential
The zeta potential values for 500 and 1000 ppm of chitosan and 500 ppm and 1000 ppm of calcium alginate are shown in Table 2, for each of +56.2 mV, +45.5 mV, and +0.9 mL, respectively. Volts and +0.6 mV were measured.
Particle Size Distribution
The results of the DLS test for the average numerical size of nanoparticles formed using 500 ppm chitosan and 500 ppm calcium alginate are shown in Figure 1, which are 190.2 nm and 334 nm, respectively. Because encapsulation efficiency and zeta potential were better for 500 ppm treatments, particle size distribution tests and infrared spectroscopy were considered only for these treatments.
Zeta Potential
The zeta potential values for 500 and 1000 ppm of chitosan and 500 ppm and 1000 ppm of calcium alginate are shown in Table 2, for each of +56.2 mV, +45.5 mV, and +0.9 mL, respectively. Volts and +0.6 mV were measured.
Particle Size Distribution
The results of the DLS test for the average numerical size of nanoparticles formed using 500 ppm chitosan and 500 ppm calcium alginate are shown in Figure 1, which are 190.2 nm and 334 nm, respectively. Because encapsulation efficiency and zeta potential were better for 500 ppm treatments, particle size distribution tests and infrared spectroscopy were considered only for these treatments.
Fourier Transform Infrared Spectroscopy Test (FTIR)
The results of FTIR spectroscopy, chitosan 500 ppm, and calcium alginate 500 ppm are shown in Figure 2.
Fourier Transform Infrared Spectroscopy Test (FTIR)
The results of FTIR spectroscopy, chitosan 500 ppm, and calcium alginate 500 ppm are shown in Figure 2.
Infrared spectroscopy is a tool to study the state of bonds and microstructure of materials in organic chemistry-in other words, to study hydrogen bonds and other reactions in addition to the ability to combine polymers. Since different functional groups have absorption at certain frequencies and changes in the structure of materials cause changes in absorption frequencies, IR spectroscopy is introduced as a suitable tool for detecting and displaying structural changes in the method. As can be seen, the general structure of the peaks for both samples is very similar to each other. The ones observed in 623.44 and 777.81 are related to the off-plane bends of C-H bonds of phenolic rings . The peaks of 817. 80 Infrared spectroscopy is a tool to study the state of bonds and microstructure terials in organic chemistry-in other words, to study hydrogen bonds and other re in addition to the ability to combine polymers. Since different functional groups h sorption at certain frequencies and changes in the structure of materials cause cha absorption frequencies, IR spectroscopy is introduced as a suitable tool for detect displaying structural changes in the method. As can be seen, the general structur peaks for both samples is very similar to each other. The ones observed in 623 777.81 are related to the off-plane bends of C-H bonds of phenolic rings . The p 817. 80
Effect of Encapsulation on In Vitro Gas Production
The gas production of the experimental treatments at different incubation times is presented in Table 3. Table 3. The effect of flaxseed oil encapsulation on total gas production of dairy cattle diet in incubation times (mL/g dry matter). At the 2 h incubation, the treatment containing chitosan (7%) had the highest gas production among the experimental and control treatments. However, this increase in gas production was not significant, and the treatments containing flaxseed oil (14%) and chitosan (14%) had significantly lower gas production compared to control and other treatments (p < 0.05). During incubation times 4 to 12 h, the treatment containing calcium alginate (14%) had the highest gas production compared to the control treatment and other treatments, and this increase in gas production was also statistically significant (p < 0.05). At the incubation times, 16 to 96 h, the treatment containing flaxseed oil (7%) had more gas production among the treatments, and after that, the treatment containing calcium alginate (14%) had more than the control treatment and other treatments (p < 0.05). Additionally, the lowest gas production during the incubation period (2-96 h) is for treatment containing flaxseed oil (14%).
The Effect of Flaxseed oil Encapsulation on the In Vitro Digestibility of Dairy Cattle Diets
The effect of flaxseed oil encapsulation on the in vitro digestibility of dairy cattle diets is shown in Table 4.
After 24 h of incubation, the results show that the experimental treatments had less dry matter digestibility than the control treatment and only the treatment containing calcium alginate (14%) significantly increased the digestibility compared to the control treatment and the treatment containing Chitosan (7%) had the lowest dry matter disappearance among experimental treatments (p < 0.05). After 2 h of incubation, the highest rate of organic matter disappearance was related to the control treatment, but with the incubation process continuing until 24, the treatment containing calcium alginate (14%) had the highest digestibility of organic matter. The lowest levels at incubation times of 2, 4, 8, and 12 were related to treatments containing chitosan (7%), calcium alginate (7%), flaxseed oil (14%), and chitosan (14%) (p < 0.05).
The crude protein disappearance of the experimental treatments is presented in Table 4, the difference between which was statistically significant with the control treatment (p < 0.05). During 24 h of incubation, the treatment containing flaxseed oil (14%) had the highest crude protein digestibility compared to the control and other treatments. The lowest rate of crude protein disappearance related to treatments containing chitosan (7%) (p < 0.05).
The results of the in vitro digestibility of neutral detergent fiber and acid detergent fiber are presented in Table 4. According to the presented results, 2 h after incubation, the highest rate of digestibility of neutral detergent fiber is related to the treatment containing chitosan (14%), and the lowest rate is related to the treatment containing flaxseed oil (14%). At 4 h after incubation, the treatment containing calcium alginate (14%) had the highest, and the treatment containing chitosan (7%) had the lowest rate of fiber digestibility. This trend changed in 8 h after incubation, and the treatment containing chitosan (7%) had the highest rate, and the treatment containing flaxseed oil (14%) after the control treatment had the lowest rate among the treatments (p < 0.05). At 12 and 24 h after incubation, the rate of disappearance of insoluble fibers in the neutral detergent changed again, and this time the treatment containing calcium alginate (14%) had the highest amount, and the treatments containing flaxseed oil (14%) and chitosan (7%) had the lowest rate (p < 0.05). The presented results on the disappearance of acid detergent fiber show that at 2 and 4 h after incubation, the treatment containing calcium alginate (14%) has the highest digestibility of acid detergent fiber detergent. However, 8 h after incubation, this trend changed, and the treatment containing calcium alginate (7%) had the highest amount, and at 12 h after incubation, the treatment containing flaxseed oil (14%) had the highest digestibility (p < 0.05). Finally, at 24 h after incubation, the treatment containing calcium alginate (14%) caused a significant increase in the digestibility of acid detergent fiber compared to other experimental treatments (p < 0.05).
The Effect of Flaxseed Oil Encapsulation on Biohydrogenation of Fatty Acids in Experimental Treatments
The effect of flaxseed oil encapsulation on in vitro ruminal biohydrogenation of fatty acids of experimental treatments is presented in Table 5. The results show that the percentage of saturated fatty acids in the treatment containing calcium alginate (7%) during incubation time increased significantly compared to the control treatment and other treatments, while the percentage of unsaturated fatty acids in this treatment showed a significant decrease (p < 0.05). Encapsulation of flaxseed oil with chitosan reduces the hydrogenation of saturated fatty acids so that the treatment containing chitosan (14%) at 2 and 4 h of incubation and the treatment containing chitosan (7%) at 24 h of incubation increases the percentage of unsaturated fatty acids and the amount of saturated fatty acids significantly reduced (p < 0.05). Treatments containing calcium alginate (7% and 14%) and treatments containing flaxseed oil (7% and 14%) significantly reduced the percentage of unsaturated fatty acids compared to the control treatment. Encapsulation reduced the percentage of short-chain fatty acids after 24 h of incubation for treatment with chitosan (7%), but treatment with calcium alginate (7%) increased it significantly. The percentage of medium-chain fatty acids among the experimental treatments was significantly higher than the control treatment, and its highest amount was found in 2 h of incubation with chitosan (14%) and in 4 h of incubation treatment with calcium alginate (7%), with no significant difference between chitosan (7%) and flaxseed oil (14%). Encapsulation of flaxseed oil protects long-chain unsaturated fatty acids from ruminal biohydrogenation so that the percentage of these fatty acids in the treatment containing chitosan (7%) increased significantly (p < 0.05), and the treatment containing calcium alginate (7%) after 24 h of incubation reduced the percentage of these fatty acids compared to the control treatment and other treatments.
Capsulation Efficiency
The micro coating efficiency was 87.47% for 500 ppm chitosan, 67.45% for 1000 ppm chitosan, 74.5% for 500 ppm calcium alginate, and 53.28% for 1000 ppm calcium alginate. The efficiency of the micro coating is to determine the amount of oil that has been successfully coated and is calculated from the amounts of surface oil and total oil. This parameter is one of the important factors in determining the stability of micro coated compounds because it indicates the presence of oil on the surface of powder particles and the ability of the walls to prevent the release of internal oil . In general, there is a view that the stability of the compounds increases with increasing the efficiency of micro coating, and in order to achieve optimal conditions, one should try to increase the efficiency of micro coating as much as possible . Previous studies have shown that wall, core types, emulsion properties, and drying parameters can affect the performance of micro coating . Swetank et al. observed that the combination of two wall materials (protein and polysaccharide) reduces the efficiency of the micro coating compared to the use of each alone. The main factors affecting the micro coating efficiency of micro coating oils and flavors are the type of wall material, the properties of the core material (concentration and volatility), the properties of the emulsion (total solids, viscosity, and particle size), and the drying conditions, thus optimizing the drying process. Liu et al. showed that in flaxseed oil microencapsulation by compound aggregation method, increasing the homogenizer speed to 9000 increases productivity. Additionally, in another study, the efficiency of microencapsulation of drug compounds in chitosan coatings by emulsion method was very high and in the range of 52.2 to 80.1% for different treatments .
Zeta Potential
The significantly higher zeta potential of the prepared nanoparticles indicates excellent colloidal dispersion stability. The positive zeta potential also enhances the formation of non-stoichiometric nanoparticles . The higher zeta potential means that the treatment has good conditions for emulsion surface charge and electrostatic repulsion between the particles, which prevents the particles from sticking together and clumping in the emulsion. Surface charge, also known as the zeta potential, affects encapsulation efficiency, colloidal stability, and particle interaction with the cell and the environment. The high zeta potential of colloidal particles increases the electrostatic repulsion force and thus increases the physical stability of the system. Various factors such as ionic strength, type and concentration of polysaccharide and protein biopolymers used, and the ratio between them on the effective surface charge and zeta-complex potential are effective .
Particle Size Distribution
The accumulation of non-stoichiometric chitosan nanoparticles is probably due to the presence of more than one chemical. Of course, there is also the possibility of selfmassification . Additionally, the diagram of the particle size distribution of microcapsules after formation is shown in Figure 1. Dynamic Light Scattering (DLS) is a physical method that uses particles, particles, and particles in all directions. Reducing the particle size to the nanometer scale increases the desired properties such as stability, transparency, and encapsulation efficiency of the system. The results of research by Swetank, Karthik, and Anandharamakrishnan on vanilla oil micro coated with different methods show that both wall materials and micro coating techniques significantly affect the shape, size, and overall structure of microcapsules.
In the study of Soottitantawat, Bigeard, Yoshii, Furuta, Ohkawara, and Linko , it was reported that the particle size of the emulsion has a very significant effect on the preservation of flavorings. According to Calvo et al. , the particle size obtained depends on the concentration of chitosan and alginate polymer, so when the concentration of chitosan and alginate is low, the particle size will be smaller. The higher the alginate, the larger the particle size produced, and under the same conditions, as the concentration of biopolymers increases, the particle size increases. Hosseini, Zandi, Rezaei, and Farahmandghavi , for their research with the method of particle oil extract of oregano essential oil in azan, have been used in the treatment of acne. The data of the weighting particles and the charged particles in the chitosan range from 40 to 80 nm. The weight of nanoparticles was greater than that of oregano essential oil particles. In an experiment, micro coatings using soy isolate on the wall on the micro coating efficiency of fish oil stated that the presence of alginate in the wall increases the particle size .
Effect of Encapsulation on In Vitro Gas Production
The volume of gas produced increases as it approaches the end of the incubation time because in the gas production test method, the microbial population is still stable at all hours of incubation, and there is no entry and exit for microorganisms. However, as incubation progresses, some microorganisms die and become an additional substrate for other microorganisms. Eventually, this process leads to an increase in cumulative gas production at the end of the incubation period . In a study by Sinclair et al. on the effect of flaxseed oil and fish oil on gas production, it was observed that treatments containing flaxseed oil and fish oil produced less gas than the control group due to the presence of linolenic acid in this oil, which was consistent with the results of this experiment, and the treatment containing octane oil (14%) had lower gas production. Additionally, in the gas production and batch culture experiments of Safari et al. , statistical comparison of treatments with protected fish oil compared to treatments containing unprotected fish oil showed better performance of encapsulated treatments. Their experiments showed that the total gas production and gas production in the first 24 h of in vitro incubation was significantly reduced by adding unprotected fish oil to the diet. Da Silva et al. showed that adding 3.5% sunflower oil increased in vitro gas production but did not affect methane production. Differences in the results of different experiments are due to differences in the source of fat used, percentage of fat used, ruminant species, experimental conditions, used rations, and base substrate. Several investigations on the inclusion of unsaturated oils have indicated that it has an adverse effect on fiber digestion and the rumen bacterial population . In general, by adding less than 10% fat to the diet, the digestibility of structural carbohydrates in the rumen is reduced by about 50% or even more. This decrease in digestibility is accompanied by a decrease in the production of volatile fatty acids and methane and hydrogen gases .
The Effect of Flaxseed Oil Encapsulation on the In Vitro Digestibility of Dairy Cattle Diets
Supplementation diet with flaxseed oil at levels of 7, 14% decreased DM digestibility compared to control (p < 0.05). The results of Zinn et al. showed that using unsaturated fat at the level of 6% of the dry matter in the diet of fattening calves reduced the rumen digestion of organic matter insoluble fibers in neutral detergent. The results of a study on fattening lambs showed that the digestibility of nutrients, including organic and crude protein, was significantly affected by the treatment containing unsaturated fatty acids . The data obtained from the study of Mansuri, Nikkhah, Rezaeian, Moradi Shahrbaback, and Mirhadi are consistent with the present study results. Many researchers have reported that the addition of oil negatively affects dry matter digestion . Machmüller et al. added coconut oil to the lambs' diets and found that methane production was reduced by 26% without affecting digestibility. Machmüller et al. also reported that when coconut oil is used in the diet of ruminants, it has no effect on the absorption of all nutrients in the gastrointestinal tract but reduces the activity of ruminal methanogenesis. It has been confirmed that the total fat in the diet should not exceed 6 to 7% of dry matter because it negatively affects digestion and absorption of nutrients . According to Jordan, Kenny, Hawkins, Malone, Lovett, and O'Mara , adding high levels (24% dry matter) of coconut oil to the diet of fattened cows fed 50% forage and 50% concentrate reduced the digestibility and consumption of the diet, but lower levels of oil (between 10-28% dry matter) did not affect these indicators. Decreased digestibility by encapsulating treatments can be explained by factors such as the effects of fat coating, reduced cellulolytic bacteria, and inability to bind to fibers. The different effects of different microcapsule sources on different digestibility parameters can be due to differences in the amount of oil released from different microcapsules per unit time and the total amount of oil released from the microcapsules. A study reported that rumen-protected fat supplementation did not affect dry matter, organic matter, crude protein, neutral, or acidic insoluble fibers in sheep . In contrast, Bhatt and Sahoo reported higher organic matter digestibility with rumen-protected fat supplementation. The inclusion of chitosan in the diet reduced nutrient digestibility. This reduction in nutrient digestibility was likely due to antimicrobial action of chitosan against ruminal microbes (protozoa and fibrolytic bacteria) . Protozoa play an important role in protein degradation in ruminant .
The Effect of Flaxseed Oil Encapsulation on Biohydrogenation of Fatty Acids in Experimental Treatments
Fatty acid protection methods, using the method of making calcium salts and coated calcium salts, eliminated the negative effect of unsaturated fatty acids on the parameters of the cell wall, dry matter, and organic matter digestibility. They did not have a negative effect on fat digestibility and fat supplements. This indicated that the type of coating used was appropriate. Chouinard et al. investigated the effect of calcium salts of three types of canola, soybean, and flaxseed oils on nutrient digestibility. They found that none of them had a significant effect on NDF and ADF digestibility and increased dry matter, organic matter, and protein digestibility.
Jenkins and Fotouhi reported that the addition of flaxseed oil reduced protein degradability compared to the control group (p < 0.05). The different effects of different types of unsaturated fatty acids on the degradability parameters can be considered as the effect of their unsaturation and the subsequent effects on the microbial population of the gastrointestinal tract. In addition, the different rate and extent of biogenic hydrogenation of ruminal fatty acids may explain some of this effect . By inhibiting bacterial proteases, the active and effective compounds in essential oils reduce protein digestion in the rumen and their use in the intestine. After absorption in the small intestine, it is effectively used in the body of ruminants and improves animal production efficiency. Schauff and Clark stated that supplementation of calcium salt of long-chain fatty acid in dairy animals increased the crude protein digestibility.
Geraeily reported that flaxseed oil increased the digestibility of insoluble fibers in neutral detergents. Schroeder et al. reported that adding your grain with different treatments did not significantly affect the digestibility of NDF and ADF. In studies on unsaturated fats, this type of reduction in digestibility has been reported as a result of the negative effect of unsaturated fatty acids on cellulose-degrading microorganisms and the physical coating of feed particles, and the prevention of microorganisms from adhering to that . However, unsaturated fats inhibit gram-positive bacteria that break down cellulose .
Encapsulation of flaxseed oil protects long-chain unsaturated fatty acids from ruminal biohydrogenation so that the percentage of these fatty acids in the treatment containing chitosan (7%) increased significantly (p < 0.05) and the treatment containing calcium alginate (7%) after 24 h of incubation, reducing the percentage of these fatty acids compared to the control treatment and other treatments. The antimicrobial properties of chitosan may have prevented the growth of microorganisms and, consequently, prevented ruminal biohydrogenation. Yuan et al. 's research on the antimicrobial and antioxidant activity of chitosan coatings and films containing essential oils and their effectiveness in feeding systems. Their research showed that the combination of essential oils significantly increased the antimicrobial, antioxidant, and fungal properties of chitosan films. These films are commonly used to increase shelf life and reduce lipid oxidation in fish and meat products. Glasser et al. stated that increasing the concentration of C18:3 isomers with oilseed supplements in the form of seeds and oil is only possible to a limited extent unless protected fats are used. The linolenic fatty acid is converted to a saturated fatty acid by biohydrogenation in ruminants. The longer passage rate of forage through the rumen and the more biohydrogenation of linolenic acid compared to linoleic acid limits the amount of accessibility of this fatty acid to be absorbed into tissues . Increasing the incubation time increases the apparent biohydrogenation of unsaturated fatty acids. In the study of Dohme et al. , by increasing the incubation time from 12 to 24 and 48 h, the amount of biohydrogenation of fatty acids in fish oil composition increased, which can be increased by increasing lipolysis and availability of non-esterified fatty acids. Increasing the incubation time from 12 to 24 and 48 h increased the rate of bio-hydrogenation in calcium salts, which can be justified by increasing the release of fatty acids from the salt structure by reducing the acidity of ruminal fluid as a result of fermentation in the culture medium.
Today, to change the fatty acid profile of cow's milk, extensive research has been done to reduce short-chain fatty acids and increase long-chain unsaturated fatty acids. The easiest way to change the fat content of milk is to change the diet of livestock and use compounds and nutrients containing unsaturated fatty acids . Liu et al. reported that short-chain milk fatty acids (6-to 14 C fatty acids) are formed mainly by the intrathecal synthesis in mammary epithelial cells of acetate and butyrate produced in the rumen, and C:16 milk fatty acid from two ways of intra-tissue synthesis and receiving from blood. The researchers reported that increasing the amount of long-chain unsaturated fatty acids reduces the intra-tissue synthesis of short-chain fatty acids in the breast. The amount of biohydrogenation can be explained by the efficiency of micro coating, which increases the amount of surface oil and decreases the efficiency of micro coating, increases the access of microbial enzymes to the oil in the microcapsules, and ultimately increases lipolysis and biohydrogenation. In general, unlike calcium salt technology, which involves chemical changes in the structure of a fatty acid to make the carboxyl group inaccessible, in microencapsulation, the goal is to use physical protection by creating a suitable coating around the fatty acid source in order to reduce the availability of microorganisms or microbial and plant enzymes in the rumen environment with fatty acids and ultimately increase the passage of unsaturated fatty acids into the small intestine.
Khalili et al. investigated the encapsulation of thyme oil in a chitosan-benzoic acid nanogel that may have increased antimicrobial activity against Aspergillus flavus. Observation of the obtained results showed that chitosan-benzoic acid nanogel has a synergistic effect on the antimicrobial properties of thyme. In addition, because essential oils are volatile and unstable, encapsulation by this nanogel significantly increased its shelf life and antimicrobial properties. Szumacher-Strabel et al. studied the effect of linoleic acid-rich oils on rumen fermentation parameters in sheep, goats, and dairy cows using the Batch culture system. They also showed that saturated fatty acids did not decrease numerically. While the amount of unsaturated fatty acids in dairy cows' ruminal fluid increased numerically, it was not significant in the ruminal fluid of sheep and goats after fermentation. In experiments performed by Elnashar et al. on the encapsulation method to protect unsaturated fatty acids from in vitro ruminal biohydrogenation, the encapsulation process had no significant effect on the polyunsaturated fatty acids (PUFA) fraction. Their results showed no significant difference between the fatty acid content of flaxseed oil before and after the encapsulation process. After encapsulation in the batch culture system, the total content of unsaturated and rumen saturated fatty acids in flaxseed decreased. In a recent laboratory study, a high protective effect (99%) of rumen microbes was reported for flaxseed oil encapsulated with hydrogenated palm oil after 8 h of incubation . According to Khalilvandi-Behroozyar et al. , coating of calcium salts in fish oil using saturated fatty acids increased the amount of total fatty acids and increased the ratio of saturated fatty acids to unsaturated fatty acids. The use of calcium salts in fish fatty acids significantly reduced the bio-hydrogenation of unsaturated fatty acids compared to unprotected sources. Comparison of the rate of bio-hydrogenation shows the appropriate efficiency of calcium salts in reducing the rate of bio-hydrogenation of unsaturated fatty acids in fish oil. However, coating increased the protective effect of calcium salts. In addition, there was a significant difference between the rate of bio-hydrogenation of coated supplements with different amounts of coating material. Certainly, this study was conducted in vitro, and the results obtained are to be considered valid as described. Future research will also have to be able to deepen these aspects in vivo, performing studies in different ruminant species.
Conclusions
It was concluded that chitosan and calcium alginate at 500 ppm is suitable for encapsulating flaxseed oil with high encapsulation efficiency. Encapsulation of flaxseed oil with calcium alginate (14%) increased gas production (compared to control and flaxseed oil (14%)), the disappearance of dry matter, organic matter, and crude protein, NDF and ADF. Encapsulation of flaxseed oil with chitosan (7%) reduced hydrogenation of rumen unsaturated fatty acids. Encapsulation of flaxseed oil with calcium alginate (7% and 14%) increased saturated fatty acids. Funding: This work has been supported by University of Tabriz, International and Academic Cooperation Directorate, in the framework of TabrizU-300 program.
Institutional Review Board Statement:
The study was conducted in accordance with the Declaration of Helsinki, and approved by the Institutional Review Board (or Ethics Committee) of University of Tabriz (protocol code TabrizU-300/10M-2021.
Informed Consent Statement: Not applicable.
Data Availability Statement: Not applicable. |
/**
* @ClassName SpringConfiguration
* @Author Leo
* @Description //TODO
* @Date: 2019/5/23 10:37
**/
@Configuration
public class SpringConfiguration {
@Bean
public SpringBeanRegistry customBeanDefinitionRegistry() {
return new SpringBeanRegistry();
}
} |
/**
* This is the main connector class for the NATS Connector.
* It operates as follows:
*
* It is entirely java properties driven - these can be set as parameters
* to the JVM or passed in as a file.
*
* The Connector starts a thread which drives a DataFlowHandler.
* The handler connects to NATS and invokes various interfaces on
* a supplied plugin.
*
* The plugin has a few APIs that allow it to publish messages,
* flush the NATS connection, and subscribe to various subjects.
*
* A plugin can both subscribe to receive data and export it to another
* system, feed data into NATS, or both.
*
* The plugin's responsibilities include:
*
* Ensuring performance out of nats. This may include some buffering
* if the destination of the data consumer slower than NATS produces it.
*
* Translation of external origin/destination and the subject namespace.
*/
public class Connector implements Runnable
{
/**
* Name of the property to set the plugin class name.
*/
static public final String USER_PROP_PLUGIN_CLASS = "com.io.nats.connector.plugin";
static final Logger logger = LoggerFactory.getLogger(Connector.class);
NATSConnectorPlugin plugin = null;
Properties gwProps = null;
String configFile = null;
DataFlowHandler flowHandler = null;
private NATSConnectorPlugin loadPlugin(String className) throws
ClassNotFoundException, InstantiationException,
IllegalAccessException
{
logger.debug("Loading plugin: " + className);
try {
return (NATSConnectorPlugin)Class.forName(className).newInstance();
}
catch (ClassNotFoundException cnfe) {
logger.error("Unable to find class " + className);
logger.debug("Exception: ", cnfe);
throw cnfe;
}
catch (InstantiationException ie)
{
logger.error("Unable to instantiate class " + className);
logger.debug("Exception: ", ie);
throw ie;
}
catch (IllegalAccessException iae)
{
logger.error("Illegal access of class " + className);
logger.debug("Exception: ", iae);
throw iae;
}
}
@Override
public void run()
{
try
{
logger.info("NATS Connector starting up.");
flowHandler = new DataFlowHandler(plugin, gwProps, logger);
Runtime.getRuntime().addShutdownHook(
new Thread()
{
public void run()
{
logger.debug("Cleaning up from shutdown hook.");
flowHandler.cleanup();
}
});
flowHandler.process();
logger.info("NATS Connector has shut down.");
}
catch (Exception e)
{
logger.error("Exception: ", e.getMessage());
throw e;
}
}
/**
* Shuts down a running Connector.
*/
public void shutdown()
{
flowHandler.shutdown();
}
private void traceProperties()
{
logger.trace("Properties:");
for (String s : gwProps.stringPropertyNames())
{
logger.trace("{}={}", s, gwProps.get(s));
}
}
public Connector(String[] args) throws Exception
{
if (args != null)
parseArgs(args);
gwProps = getProperties();
traceProperties();
String className = gwProps.getProperty(USER_PROP_PLUGIN_CLASS);
if (className == null)
{
logger.error("Required property " + USER_PROP_PLUGIN_CLASS + " is not set.");
throw new Exception("Connector plugin class not set.");
}
plugin = loadPlugin(className);
}
public Connector() throws Exception {
this(null);
}
private void usage()
{
System.out.printf("java {} -config <properties file>", Connector.class.toString());
System.exit(-1);
}
private void parseArgs(String args[])
{
if (args == null)
return;
if (args.length == 0)
return;
if (args.length < 2)
usage();
// only one arg, so keep it simple
if ("-config".equalsIgnoreCase(args[0]))
configFile = args[1];
else
usage();
}
private Properties getProperties() throws Exception{
// add those from the VM.
Properties p = new Properties(System.getProperties());
if (configFile == null)
return p;
logger.debug("Loading properties from '" + configFile + '"');
FileInputStream in = new FileInputStream(configFile);
try {
p.load(in);
}
catch (Exception e) {
logger.error("Unable to load properties.", e);
throw e;
}
finally {
in.close();
}
return p;
}
public static void main(String[] args)
{
try
{
// We could create and executor, etc, but just run it. It'll add a
// shutdown hook, etc. The NATS connector can be run as a thread
// from anywhere.
new Connector(args).run();
}
catch (Exception e)
{
logger.error("Severe Error: ", e);
}
}
} |
Image copyright PA Image caption The first minister argued that the Scottish economy would suffer from continuing to be part of the UK
The first minister has warned that rejecting independence would leave Scotland subject to continuing economic austerity.
Alex Salmond said that spending cuts planned by the UK government would do further damage to public services.
Mr Salmond argued it was "vital" for Scotland to pursue an alternative path.
He made the comments in a letter to the Chief Secretary to the Treasury, Danny Alexander.
Mr Alexander claimed in a letter to Mr Salmond at the weekend that spending plans set out by Scottish Ministers would put Scotland on a different economic path from the rest of the UK - and make a currency union impossible in the event of independence.
The Scottish Finance Minister John Swinney has outlined plans to boost public spending in Scotland by 3% in each of the first three years after independence.
Anything other than a vote for independence would be a vote for continuing Conservative austerity Alex Salmond , Scottish first minister
This contrasts with a figure of 1% planned by the Chancellor, George Osborne.
The Scottish expenditure would be funded by borrowing. The objective would be to grow the economy and thus reduce the deficit in a "sustainable" fashion.
Mr Alexander argued that this level of borrowing would mean that the economies of Scotland and the remainder of the UK would be divergent.
This explained, he argued, why he and his counterparts in other UK parties had ruled out a currency union.
But, in his letter of reply, the first minister argued that the austerity programme pursued by the UK government has had a "detrimental effect both on the economy and on public services."
Spending plans
He said public services in Scotland have had to cope with a 26% reduction in capital spending "at the very time we should have been investing in the economy".
Mr Salmond noted that Mr Alexander presumed that the UK will be in budget surplus by 2018/19 after a period of deficit.
According to Mr Salmond, this also presumed that the current spending plans by the UK government will be maintained whoever wins the UK election.
Mr Salmond said in his letter to Mr Alexander that this was a "significant political admission and blunder".
He concluded: "Your letter leaves the Scottish electorate with little option but to conclude that anything other than a vote for independence would be a vote for continuing Conservative austerity."
Responding to Mr Salmond's letter, a Treasury spokesman said: "Yet again the first minister has failed to address any of the questions the chief secretary put to him.
"Asked to lay out his currency plan for a separate Scotland all he has done is thrown sand in the air and ignored the fact that the UK government's economic policies are working. The deficit is down and the UK, including Scotland, is growing faster than any other country in the G7." |
Effects of pupil size on canine visual evoked potential with pattern stimulation
The purpose of this study was to investigate the effects of pupil diameter on canine visual evoked potentials with pattern stimulation (P-VEP). Atropine eye drop (1.0%) was applied to both eyes as a cycloplegic drug, and tafluprost eye drop (0.015%) was applied to one eye that was selected randomly for miosis (miosis group). The other eye did not receive tafluprost (mydriasis group). P-VEP was recorded at three pattern sizes. The P100 implicit time at a small pattern size in the mydriasis group was significantly prolonged compared to the miosis group. We hypothesized that the prolonged P100 implicit time under mydriatic conditions was due to increased spherical aberrations and concluded that mydriatic conditions affected P100 implicit time in canine P-VEP recordings.
The visual evoked potential (VEP) test is an examination that can objectively evaluate visual acuity. The method works detecting brain wave signals from the visual cortex that are induced by a light stimulus . VEP is classified into flashstimulated VEP (F-VEP), which uses a flash stimulus, and pattern-stimulated VEP (P-VEP), which uses a contrast-reversing checkerboard pattern stimulus. In our previous studies, the effects of the refractive power of the eye and anesthesia on canine P-VEP were reported, and we measured canine visual acuity using P-VEP .
The refractive power of the eye affects P100 implicit time in canine P-VEP recordings, and P-VEP is recorded stably when this power is adjusted to a stimulus monitor . To measure the refractive power of the eye, cycloplegic drugs such as atropine or cyclopentrate . However, since cycloplegic drugs are cholinergic antagonists, pupillary dilation also occurs . As the pupil dilates, the effective diameter of the lens increases, and spherical aberrations also increase .
Spherical aberration is a phenomenon in which the focus position of the light differs due to differences in the incident angle, refraction angle, and optical path length of paraxial rays that pass near the optical axis of the lens, and peripheral rays that pass away from the optical axis . Because increasing spherical aberration reduces visual perception due to the differing focus positions of light on the retina, P-VEP is also affected. In this study, P-VEPs with different pupil diameters were recorded to investigate the effects of pupil diameter on canine P-VEP.
Twelve eyes from six clinically normal beagle dogs (3 males and 3 females) were used in this study. The dogs were 3 to 4 years of age and weighed 11.1 to 14.4 kg. These animals showed no abnormalities in ophthalmic examinations before the study. The examinations included pupillary light reflex, dazzle reflex, menace response, applanation tonometry (Tono-Pen XL, Medtronic Solan, Jacksonville, FL, USA), slit-lamp biomicroscopy (SL-7, Kowa, Nagoya, Japan), ophthalmoscopy (TRC-50IX, TOPCON, Tokyo, Japan) and electroretinography (LE-3000, TOMEY, Nagoya, Japan). This study was conducted in accordance with the guidelines of Experimental Animal Research Committee of Rakuno Gakuen University and was approved by the committee (No. VH17B21).
A single drop of atropine sulfate eye drop (Nitten ATROPINE Ophthalmic Solution 1%, Nitten Pharmaceutical Co., Ltd., Nagoya, Japan) was applied to both eyes as a cycloplegic and mydriatic drug. Thirty minutes later, a single drop of tafluprost (TAPROS ophthalmic solution 0.0015%, Santen Pharmaceutical Co., Ltd., Osaka, Japan) eye drop was applied to one eye that was randomly selected for miosis (miosis group) and was not applied to the other eye (mydriasis group). The refractive power of each recorded eye was measured using skiascopy in accordance with our previous report . Refractive power was measured with a streak retinoscope (Streak Retinoscope RX-3A, Neits Instruments Co., Ltd., Tokyo, Japan) and a skiascopic lens (Hatake Skiascope, Handaya Co., Ltd., Tokyo, Japan) under dim light 90 min after applying atropine eye drops. The refractive power of doi: 10.1292/jvms.20-0169 each recorded eye was corrected to −2 diopters according to a testing distance of 0.5 m using soft contact lenses (Premio, Menicon, Nagoya, Japan) based on the obtained skiascopy data.
Prior to VEP recording, the pupil diameter of the eye was measured. VEP were recorded under sedation using a combination of 0.01 mg/kg medetomidine (Domitor, ZENOAQ, Fukushima, Japan), 0.15 mg/kg midazolam (Dormicam, Astellas Pharma, Tokyo, Japan) and 0.025 mg/kg butorphanol (Vetorphale, Meiji Seika Pharma, Tokyo, Japan) injected intravenously. A portable ERG/ VEP system and pattern stimulus display (PS-410, TOMEY) were used for this study. The details of this display were as follows: indicated color, yellow (580 nm); resolution, 640 × 400 dots; indicated area, 122 × 195 mm; pixel size, 0.22 × 0.22 mm; frame frequency, 60 Hz; contrast, 75%; and mean luminosity, 15 cd/m 2 . The stimulus monitor was placed 0.5 m in front of the eye, and three stimulus pattern sizes were used. The length of one side of each square pattern was 31.72 (No. 1), 7.31 (No. 2) and 1.22 mm (No. 3). For P-VEP recordings, needle electrodes (VEP needle electrodes, Mayo Corp., Nagoya, Japan) were positioned at the inion (external occipital protuberance) for the recording electrode and at the nasion (nasal point) for the reference electrode. A plate-type electrode (LE ear electrode, Mayo Corp.) was positioned on the inner surface of the right auricle as an earth electrode, in accordance with previous reports . During VEP recordings, the eyelid was retracted with a speculum, and a supporting thread was placed in the dorsal conjunctiva using 6-0 silk (MANI, Utsunomiya, Japan) to fix the eye position. The VEP was recorded for each eye, and the eye that did not record VEP was shielded with a hand. The stimulation rate was 3 reversals/sec, and the P-VEP signal was averaged from 128 repetitions.
The P100 implicit time and N75-P100 amplitude were estimated according to a standard determined by the International Society for Clinical Electrophysiology of Vision . The P100 implicit time and N75-P100 amplitude recorded for each pattern size were compared between the miosis and mydriasis group using a Student's t-test. The P100 implicit time and N75-P100 amplitude recorded each testing pattern size in each group were compared using one-way factorial analysis of variance (ANOVA) with Fisher's PLSD test. The statistical significance of differences was determined with P<0.05 as the minimum level of acceptable significance.
The pupil diameter before VEP recording in the miosis and mydriasis groups were 1.1 ± 0.4 (mean ± SD) and 10.2 ± 0.9 mm, respectively. Photographs of one eye in each group are shown in Fig. 1.
The typical VEP waveforms obtained for one dog are shown in Fig. 2. The P100 implicit time and N75-P100 amplitude in each group are shown in Tables 1 and 2, respectively. The P100 implicit time in the mydriasis group was significantly prolonged compared to the miosis group at pattern sizes Nos. 2 and 3 (P<0.05). In the miosis group, there was no significant difference between pattern sizes, while in the mydriasis group, the P100 implicit time at Nos. 2 and 3 was significantly prolonged compared to No. 1 (P<0.05). There was no significant difference in the N75-P100 amplitude between the two groups and between pattern sizes in each group.
In the present study, P-VEPs in miotic and mydriatic conditions were recorded, and the waveforms were compared. Under mydriatic conditions, prolongation of P100 implicit time was detected. This result was likely due to decreased visual recognition resulting from increased spherical aberration under mydriatic conditions.
In this study, tafluprost eye drops were used to obtain miosis conditions. Tafluprost is a prostaglandin analogues used in glaucoma therapy . The stimulation of miosis in dogs by prostaglandins is thought to occur by direct action on prostaglandin receptor located on the iridal sphincter muscle . Generally, the cholinergic agonist pilocarpine is a miotic drug used in dogs. However, it has been reported that pilocarpine eye drops can cause uveitis due to irritation when applied . The influence of uveitis on refraction and P-VEP has not been reported. Therefore, tafluprost, which is a prostaglandin analogue, was used instead of pilocarpine to obtain miosis conditions in this study.
Prolongation of the P100 implicit time decreases visual recognition. In human medical science, prolonged P100 implicit times has been observed in patients with optic neuritis . In dogs, prolongation of the P100 implicit time has been reported when the refractive power of the eye is not adjusted to the distance of the stimulus pattern monitor . In the miotic condition in this study, P100 implicit time was observed around 100 msec after stimulation for all pattern sizes, while under mydriatic conditions, the P100 implicit time was prolonged at the small pattern size. This suggests that visual recognition was decreased under mydriatic conditions compared with miotic conditions.
We suspect that prolongation of the P100 implicit time in mydriatic conditions, that is, the decrease in visual recognition, was due to an increase in spherical aberration. Aberration refer to a phenomenon in which the position of the focusing light differs depending on the wavelength of light, and the position and direction of the passing lens . Monochromatic aberrations include coma, astigmatism, field curvature, distortion, and spherical aberration, and these are called Seidel's five aberrations. Spherical aberration is a phenomenon in which the focus position of the light differs as a result of differences in incident angle, refraction angle, and optical path length of paraxial rays that pass near the optical axis of the lens, and peripheral rays that pass away from the optical axis . In humans, it has been reported that a reduction in pupil diameter reduces spherical aberration and improves retinal imaging . Heilman et al. also reported that peripheral rays were more challenging to focus on than paraxial rays in cynomolgus monkey lens . In the mydriasis group in our study, we hypothesize that the effective diameter of the lens was increased and spherical aberration was increased due to pupil dilation, and this resulted in a prolonged P100 implicit time compared to the miosis group.
Alternatively, the possibility of diffraction has to be considered in the miotic eye. Diffraction is the phenomenon where light rays passing through the edge of an opaque object go behind obstacles . Diffraction can also lead to a decrease in visual recognition. However, the P100 implicit time in the miosis group in our study was almost 100 msec after stimulation. We believe that diffraction caused by miosis has a small effect on recording P-VEP in dogs. The limitation of this study is that our P-VEP data were recorded from eyes with extremely different pupil conditions. In future studies, it will be necessary to compare VEPs obtained from eyes with various pupil sizes, rather than miotic and mydriatic eyes. The other limitation of this study was that our data were obtained from only young dogs. The lens state is changed by aging; for example, lenses develop nuclear sclerosis with aging , and the refractive value of a lens changes due to nuclear sclerosis . Changes in the refraction of the lens may affect spherical aberration, and therefore age-related changes should be investigated in future studies.
There was no significant difference in the N75-P100 amplitude between the two groups and pattern sizes in each group. It has been reported that many factors (e.g., illumination in the laboratory room, the condition of the optic media, fixation to the stimulus device, and drowsiness) affect the N75-P100 amplitude in human P-VEP recording . In previous reports on canine P-VEP, it was difficult to evaluate the N75-P100 amplitude as a result of variation . As in previous reports, the N75-P100 amplitude had a large standard deviation and individual differences in the present study.
From the results of this study, we suggest that it is necessary to consider pupil size when recording and evaluating canine P-VEPs, and note that P100 implicit time may be prolonged, especially under mydriatic conditions. |
import { Account } from '../Server/Model';
export enum AccessRight {
CREATE,
READ,
UPDATE,
DELETE
}
export interface UserCredentials extends Account {
accessRights: AccessRight[]
}
export enum HTTP_CODES {
OK = 200,
CREATED = 201,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
NOT_FOUND = 404
}
export enum HTTP_METHODS {
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
DELETE = 'DELETE',
OPTIONS = 'OPTIONS'
}
export interface User {
id: string,
name: string,
age: number,
email: string,
workingPosition: WorkingPosition
}
export enum WorkingPosition {
JUNIOR,
PROGRAMMER,
ENGINEER,
EXPERT,
MANAGER
} |
#ifndef METALLIC_PREC_EXPF_H
#define METALLIC_PREC_EXPF_H
#include "kernel/expf.h"
#include "../double/shift.h"
#include <math.h>
static double expf_(double x)
{
const double minimum = -708.39641853226410622;
const double maximum = 709.78271289338399684;
const double log2e = 1.442695040888963407;
const double ln2 = 0.6931471805599453094;
if (x < minimum)
return 0;
if (x > maximum)
return x * HUGE_VAL;
double n = rint(x * log2e);
double y = 1 + kernel_expf_(x - n * ln2);
return shift_(y, n);
}
#endif
|
<reponame>afdaniele/run-batch<gh_stars>1-10
import os
import sys
import time
import logging
import threading
from queue import Queue
def get_logger(console):
# create logger
logging.basicConfig()
logger = BrLogger(console, 'brun', logging.INFO)
return logger
class BrLogger(logging.Logger):
def __init__(self, console, name, level=logging.NOTSET):
super(BrLogger, self).__init__(name, level)
self.console = console
def _log(self, lvl, msg, *args, **kwargs):
pre = ''
if 'step' in kwargs:
pre = '[{}] '.format(kwargs['step'])
# build message
if not msg.endswith('\n'):
msg += '\n'
if 'clear' in kwargs and kwargs['clear']:
out = msg
else:
out = '{}:{}{}'.format(logging._levelToName[lvl], pre, msg)
# add message to buffer
self.console.write(out)
# force flush
self.console.flush()
|
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table litemall_vip
*
* @mbg.generated
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andIdEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("id = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andIdNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("id <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andIdGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("id > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andIdGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("id >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andIdLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("id < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andIdLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("id <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andLevelIsNull() {
addCriterion("`level` is null");
return (Criteria) this;
}
public Criteria andLevelIsNotNull() {
addCriterion("`level` is not null");
return (Criteria) this;
}
public Criteria andLevelEqualTo(Byte value) {
addCriterion("`level` =", value, "level");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andLevelEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`level` = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andLevelNotEqualTo(Byte value) {
addCriterion("`level` <>", value, "level");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andLevelNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`level` <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andLevelGreaterThan(Byte value) {
addCriterion("`level` >", value, "level");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andLevelGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`level` > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andLevelGreaterThanOrEqualTo(Byte value) {
addCriterion("`level` >=", value, "level");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andLevelGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`level` >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andLevelLessThan(Byte value) {
addCriterion("`level` <", value, "level");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andLevelLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`level` < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andLevelLessThanOrEqualTo(Byte value) {
addCriterion("`level` <=", value, "level");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andLevelLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`level` <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andLevelIn(List<Byte> values) {
addCriterion("`level` in", values, "level");
return (Criteria) this;
}
public Criteria andLevelNotIn(List<Byte> values) {
addCriterion("`level` not in", values, "level");
return (Criteria) this;
}
public Criteria andLevelBetween(Byte value1, Byte value2) {
addCriterion("`level` between", value1, value2, "level");
return (Criteria) this;
}
public Criteria andLevelNotBetween(Byte value1, Byte value2) {
addCriterion("`level` not between", value1, value2, "level");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("`name` is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("`name` is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("`name` =", value, "name");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andNameEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`name` = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("`name` <>", value, "name");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andNameNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`name` <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("`name` >", value, "name");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andNameGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`name` > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("`name` >=", value, "name");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andNameGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`name` >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("`name` <", value, "name");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andNameLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`name` < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("`name` <=", value, "name");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andNameLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("`name` <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("`name` like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("`name` not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("`name` in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("`name` not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("`name` between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("`name` not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andPriceIsNull() {
addCriterion("price is null");
return (Criteria) this;
}
public Criteria andPriceIsNotNull() {
addCriterion("price is not null");
return (Criteria) this;
}
public Criteria andPriceEqualTo(BigDecimal value) {
addCriterion("price =", value, "price");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andPriceEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("price = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPriceNotEqualTo(BigDecimal value) {
addCriterion("price <>", value, "price");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andPriceNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("price <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPriceGreaterThan(BigDecimal value) {
addCriterion("price >", value, "price");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andPriceGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("price > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPriceGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("price >=", value, "price");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andPriceGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("price >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPriceLessThan(BigDecimal value) {
addCriterion("price <", value, "price");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andPriceLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("price < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPriceLessThanOrEqualTo(BigDecimal value) {
addCriterion("price <=", value, "price");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andPriceLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("price <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPriceIn(List<BigDecimal> values) {
addCriterion("price in", values, "price");
return (Criteria) this;
}
public Criteria andPriceNotIn(List<BigDecimal> values) {
addCriterion("price not in", values, "price");
return (Criteria) this;
}
public Criteria andPriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("price between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andPriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("price not between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andDiscountIsNull() {
addCriterion("discount is null");
return (Criteria) this;
}
public Criteria andDiscountIsNotNull() {
addCriterion("discount is not null");
return (Criteria) this;
}
public Criteria andDiscountEqualTo(BigDecimal value) {
addCriterion("discount =", value, "discount");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountNotEqualTo(BigDecimal value) {
addCriterion("discount <>", value, "discount");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountGreaterThan(BigDecimal value) {
addCriterion("discount >", value, "discount");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("discount >=", value, "discount");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountLessThan(BigDecimal value) {
addCriterion("discount <", value, "discount");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountLessThanOrEqualTo(BigDecimal value) {
addCriterion("discount <=", value, "discount");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountIn(List<BigDecimal> values) {
addCriterion("discount in", values, "discount");
return (Criteria) this;
}
public Criteria andDiscountNotIn(List<BigDecimal> values) {
addCriterion("discount not in", values, "discount");
return (Criteria) this;
}
public Criteria andDiscountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("discount between", value1, value2, "discount");
return (Criteria) this;
}
public Criteria andDiscountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("discount not between", value1, value2, "discount");
return (Criteria) this;
}
public Criteria andDiscountNameIsNull() {
addCriterion("discount_name is null");
return (Criteria) this;
}
public Criteria andDiscountNameIsNotNull() {
addCriterion("discount_name is not null");
return (Criteria) this;
}
public Criteria andDiscountNameEqualTo(String value) {
addCriterion("discount_name =", value, "discountName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountNameEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount_name = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountNameNotEqualTo(String value) {
addCriterion("discount_name <>", value, "discountName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountNameNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount_name <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountNameGreaterThan(String value) {
addCriterion("discount_name >", value, "discountName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountNameGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount_name > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountNameGreaterThanOrEqualTo(String value) {
addCriterion("discount_name >=", value, "discountName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountNameGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount_name >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountNameLessThan(String value) {
addCriterion("discount_name <", value, "discountName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountNameLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount_name < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountNameLessThanOrEqualTo(String value) {
addCriterion("discount_name <=", value, "discountName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDiscountNameLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("discount_name <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDiscountNameLike(String value) {
addCriterion("discount_name like", value, "discountName");
return (Criteria) this;
}
public Criteria andDiscountNameNotLike(String value) {
addCriterion("discount_name not like", value, "discountName");
return (Criteria) this;
}
public Criteria andDiscountNameIn(List<String> values) {
addCriterion("discount_name in", values, "discountName");
return (Criteria) this;
}
public Criteria andDiscountNameNotIn(List<String> values) {
addCriterion("discount_name not in", values, "discountName");
return (Criteria) this;
}
public Criteria andDiscountNameBetween(String value1, String value2) {
addCriterion("discount_name between", value1, value2, "discountName");
return (Criteria) this;
}
public Criteria andDiscountNameNotBetween(String value1, String value2) {
addCriterion("discount_name not between", value1, value2, "discountName");
return (Criteria) this;
}
public Criteria andValidDaysIsNull() {
addCriterion("valid_days is null");
return (Criteria) this;
}
public Criteria andValidDaysIsNotNull() {
addCriterion("valid_days is not null");
return (Criteria) this;
}
public Criteria andValidDaysEqualTo(Integer value) {
addCriterion("valid_days =", value, "validDays");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andValidDaysEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("valid_days = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andValidDaysNotEqualTo(Integer value) {
addCriterion("valid_days <>", value, "validDays");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andValidDaysNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("valid_days <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andValidDaysGreaterThan(Integer value) {
addCriterion("valid_days >", value, "validDays");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andValidDaysGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("valid_days > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andValidDaysGreaterThanOrEqualTo(Integer value) {
addCriterion("valid_days >=", value, "validDays");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andValidDaysGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("valid_days >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andValidDaysLessThan(Integer value) {
addCriterion("valid_days <", value, "validDays");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andValidDaysLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("valid_days < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andValidDaysLessThanOrEqualTo(Integer value) {
addCriterion("valid_days <=", value, "validDays");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andValidDaysLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("valid_days <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andValidDaysIn(List<Integer> values) {
addCriterion("valid_days in", values, "validDays");
return (Criteria) this;
}
public Criteria andValidDaysNotIn(List<Integer> values) {
addCriterion("valid_days not in", values, "validDays");
return (Criteria) this;
}
public Criteria andValidDaysBetween(Integer value1, Integer value2) {
addCriterion("valid_days between", value1, value2, "validDays");
return (Criteria) this;
}
public Criteria andValidDaysNotBetween(Integer value1, Integer value2) {
addCriterion("valid_days not between", value1, value2, "validDays");
return (Criteria) this;
}
public Criteria andAddTimeIsNull() {
addCriterion("add_time is null");
return (Criteria) this;
}
public Criteria andAddTimeIsNotNull() {
addCriterion("add_time is not null");
return (Criteria) this;
}
public Criteria andAddTimeEqualTo(LocalDateTime value) {
addCriterion("add_time =", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andAddTimeEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("add_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeNotEqualTo(LocalDateTime value) {
addCriterion("add_time <>", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andAddTimeNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("add_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeGreaterThan(LocalDateTime value) {
addCriterion("add_time >", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andAddTimeGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("add_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("add_time >=", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andAddTimeGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("add_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeLessThan(LocalDateTime value) {
addCriterion("add_time <", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andAddTimeLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("add_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("add_time <=", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andAddTimeLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("add_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeIn(List<LocalDateTime> values) {
addCriterion("add_time in", values, "addTime");
return (Criteria) this;
}
public Criteria andAddTimeNotIn(List<LocalDateTime> values) {
addCriterion("add_time not in", values, "addTime");
return (Criteria) this;
}
public Criteria andAddTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("add_time between", value1, value2, "addTime");
return (Criteria) this;
}
public Criteria andAddTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("add_time not between", value1, value2, "addTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(LocalDateTime value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andUpdateTimeEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("update_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(LocalDateTime value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andUpdateTimeNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("update_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(LocalDateTime value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andUpdateTimeGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("update_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andUpdateTimeGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("update_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(LocalDateTime value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andUpdateTimeLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("update_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andUpdateTimeLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("update_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<LocalDateTime> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<LocalDateTime> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andDeletedIsNull() {
addCriterion("deleted is null");
return (Criteria) this;
}
public Criteria andDeletedIsNotNull() {
addCriterion("deleted is not null");
return (Criteria) this;
}
public Criteria andDeletedEqualTo(Boolean value) {
addCriterion("deleted =", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDeletedEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("deleted = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedNotEqualTo(Boolean value) {
addCriterion("deleted <>", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDeletedNotEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("deleted <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedGreaterThan(Boolean value) {
addCriterion("deleted >", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDeletedGreaterThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("deleted > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedGreaterThanOrEqualTo(Boolean value) {
addCriterion("deleted >=", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDeletedGreaterThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("deleted >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedLessThan(Boolean value) {
addCriterion("deleted <", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDeletedLessThanColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("deleted < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedLessThanOrEqualTo(Boolean value) {
addCriterion("deleted <=", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_vip
*
* @mbg.generated
*/
public Criteria andDeletedLessThanOrEqualToColumn(LitemallVip.Column column) {
addCriterion(new StringBuilder("deleted <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedIn(List<Boolean> values) {
addCriterion("deleted in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotIn(List<Boolean> values) {
addCriterion("deleted not in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedBetween(Boolean value1, Boolean value2) {
addCriterion("deleted between", value1, value2, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotBetween(Boolean value1, Boolean value2) {
addCriterion("deleted not between", value1, value2, "deleted");
return (Criteria) this;
}
} |
/**
* @author: xquan
* A Kad Server's information.
* @since: 2018-6-29
**/
public class ServerInfo implements Serializable{
private String name;
private String ip;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
} |
// overly-simple dead-zoning for now.
// really should wait until polling time, and then use
// the matching axes per stick and magnitude checks like XINPUT gamepad does.
static float MapCenteredAxis(int valueS16, int deadi) {
const float value = (valueS16 / 32767.0f);
const float deadZone = (deadi / 32767.0f);
if (value > deadZone)
return (value - deadZone) / (1.0f - deadZone);
else if (value < -deadZone)
return (value + deadZone) / (1.0f - deadZone);
else
return 0.0f;
} |
/**
* DOM - Comment implementation.
*
* @author BaseX Team 2005-13, BSD License
* @author Christian Gruen
*/
public final class BXComm extends BXChar implements Comment {
/**
* Constructor.
* @param n node reference
*/
public BXComm(final ANode n) {
super(n);
}
} |
/**
* Fog monitor meteo edit dialog
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------- -------- --------- --------------------------------------------
* Sep 21, 2016 5901 randerso Remove unused style parameter to super
* constructor
*
* </pre>
*
* @author ????
*/
public class FogMonitorMeteoEditDlg extends EditThresholdsDlg
{
private Text visRTF;
private Button visIncR;
private Button visDecR;
private Text visYTF;
private Button visIncY;
private Button visDecY;
private FogMonitorMeteoData fmmd;
private IUpdateMonitorMeteo updateCB;
public FogMonitorMeteoEditDlg(Shell parent, FogMonitorMeteoData fmmd, IUpdateMonitorMeteo updateCB)
{
super(parent);
this.fmmd = fmmd;
this.updateCB = updateCB;
}
/**
* Initialize the components on the display.
*/
@Override
protected void initializeComponents()
{
shell.setText("FOG: Display Edit Meteo");
rangeUtil = RangesUtil.getInstance();
createControls();
addSeparator(getDialogShell());
}
private void createControls()
{
GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false);
GridLayout gl = new GridLayout(4, false);
gl.verticalSpacing = 10;
Composite meteoComp = new Composite(getDialogShell(), SWT.NONE);
meteoComp.setLayout(gl);
meteoComp.setLayoutData(gd);
createRYRangeLabels(meteoComp);
/*
* Visibility
*/
gd = new GridData(SWT.DEFAULT, SWT.CENTER, false, true);
Label visLbl = new Label(meteoComp, SWT.RIGHT);
visLbl.setText("Vis (mi):");
visLbl.setLayoutData(gd);
Text[] textArray = createVisControls(meteoComp, visRTF, visIncR, visDecR, visYTF, visIncY, visDecY);
visRTF = textArray[0];
visYTF = textArray[1];
}
@Override
protected void updateControlsWithData()
{
double val = Double.NaN;
/*
* Visibility
*/
val = fmmd.getMeteoVisR();
this.visRIndex = rangeUtil.getIndexOfValue((int)val);
this.visRTF.setText(rangeUtil.getVisString((int)val));
val = fmmd.getMeteoVisY();
this.visYIndex = rangeUtil.getIndexOfValue((int)val);
this.visYTF.setText(rangeUtil.getVisString((int)val));
}
/**
* Update the data structure with the data in the controls.
*/
@Override
protected void updateData()
{
double val = Double.NaN;
/*
* Visibility
*/
val = rangeUtil.getVisValueAtIndex(this.visRIndex);
fmmd.setMeteoVisR(val);
val = rangeUtil.getVisValueAtIndex(this.visYIndex);
fmmd.setMeteoVisY(val);
}
@Override
protected void applyAction()
{
updateData();
this.updateCB.updateThresholdData(fmmd);
}
} |
/* cpdma_chan_get_min_rate - get minimum allowed rate for channel
* Should be called before cpdma_chan_set_rate.
* Returns min rate in Kb/s
*/
u32 cpdma_chan_get_min_rate(struct cpdma_ctlr *ctlr)
{
unsigned int divident, divisor;
divident = ctlr->params.bus_freq_mhz * 32 * 1000;
divisor = 1 + CPDMA_MAX_RLIM_CNT;
return DIV_ROUND_UP(divident, divisor);
} |
def __check_for_duplicated_field(title: str, info: str, long_info: str, request: dict) -> dict:
_tn = Translator(get_language_from_cookie(request))
error = _tn.get(_.duplicate) + ': '
title_is_duplicate = DBDiscussionSession.query(Issue).filter_by(title=title).all()
info_is_duplicate = DBDiscussionSession.query(Issue).filter_by(info=info).all()
long_info_is_duplicate = DBDiscussionSession.query(Issue).filter_by(long_info=long_info).all()
if title_is_duplicate:
error = error + _tn.get(_.newIssueTitle) + ', '
if info_is_duplicate:
error = error + _tn.get(_.newIssueInfo) + ', '
if long_info_is_duplicate:
error = error + _tn.get(_.newIssueLongInfo) + ', '
return {
"contains_duplicated_field": title_is_duplicate or info_is_duplicate or long_info_is_duplicate,
"error": error[:-2]
} |
import { IEnumerable } from "../Enumerable/IEnumerable";
import { IQueryResult } from "../Query/IQueryResult";
import { ICacheItem } from "./ICacheItem";
import { ICacheOption } from "./ICacheOption";
import { IResultCacheManager } from "./IResultCacheManager";
export class DefaultResultCacheManager implements IResultCacheManager {
private _keyMap = new Map<string, [ICacheItem, any]>();
private _tagMap = new Map<string, string[]>();
public async clear(): Promise<void> {
const titems = Array.from(this._keyMap.values());
for (const titem of titems) {
clearTimeout(titem[1]);
}
this._keyMap.clear();
this._tagMap.clear();
}
public async get(key: string): Promise<IQueryResult[]> {
const res = await this.gets([key]);
return res.first();
}
public async gets(keys: IEnumerable<string>): Promise<IQueryResult[][]> {
return keys.select((key) => {
const titem = this._keyMap.get(key);
if (!titem) {
return null;
}
const item = titem[0];
if (!item) {
return null;
}
if (item.slidingExpiration) {
const expiredDate = (new Date()).addMilliseconds(item.slidingExpiration.totalMilliSeconds());
if (item.expiredTime < expiredDate) {
item.expiredTime = expiredDate;
if (item.expiredTime) {
titem[1] = clearTimeout(titem[1]);
titem[1] = setTimeout(() => this.remove([item.key]), item.expiredTime.getTime() - Date.now());
}
}
}
return item.data;
}).toArray();
}
public async remove(keys: IEnumerable<string>): Promise<void> {
for (const key of keys) {
const titem = this._keyMap.get(key);
const item = titem[0];
this._keyMap.delete(key);
if (item) {
if (item.tags) {
for (const tag of item.tags) {
const keyList = this._tagMap.get(tag);
if (keyList) {
keyList.delete(key);
}
}
}
clearTimeout(titem[1]);
}
}
}
public async removeTag(tags: IEnumerable<string>): Promise<void> {
for (const tag of tags) {
const keys = this._tagMap.get(tag);
if (keys) {
this._tagMap.delete(tag);
for (const key of keys) {
this._keyMap.delete(key);
}
}
}
}
public async set(key: string, cache: IQueryResult[], option?: ICacheOption): Promise<void> {
const item = {} as ICacheItem<IQueryResult[]>;
if (option) {
Object.assign(item, option);
}
item.data = cache;
item.key = key;
const titem: [ICacheItem, any] = [item, null];
this._keyMap.set(key, titem);
if (!item.expiredTime && item.slidingExpiration) {
item.expiredTime = (new Date()).addMilliseconds(item.slidingExpiration.totalMilliSeconds());
}
if (item.expiredTime) {
titem[1] = setTimeout(() => this.remove([item.key]), item.expiredTime.getTime() - Date.now());
}
if (item.tags) {
for (const tag of item.tags) {
let tagList = this._tagMap.get(tag);
if (!tagList) {
tagList = [];
this._tagMap.set(tag, tagList);
}
tagList.push(key);
}
}
}
}
|
<reponame>cherouvim/cicn-nrs<filename>ccnxlibs/libccnx-common/ccnx/common/ccnx_Interest.c
/*
* Copyright (c) 2017 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*/
#include <config.h>
#include <LongBow/runtime.h>
#include <ccnx/common/ccnx_Interest.h>
#include <ccnx/common/internal/ccnx_InterestDefault.h>
#include <ccnx/common/ccnx_InterestPayloadId.h>
#include <ccnx/common/ccnx_WireFormatMessage.h>
#include <parc/algol/parc_Memory.h>
#include <parc/algol/parc_DisplayIndented.h>
#include <stdio.h>
//by wschoi
//#define LOG_CHECK
static const CCNxInterestInterface *_defaultImplementation = &CCNxInterestFacadeV1_Implementation;
CCNxInterest *
ccnxInterest_Create(const CCNxName *name,
uint32_t lifetime,
const PARCBuffer *keyId,
const PARCBuffer *contentObjectHash)
{
return ccnxInterest_CreateWithImpl(_defaultImplementation,
name,
lifetime,
keyId,
contentObjectHash,
CCNxInterestDefault_HopLimit);
}
CCNxInterest *
ccnxInterest_CreateWithImpl(const CCNxInterestInterface *impl,
const CCNxName *name,
const uint32_t interestLifetime,
const PARCBuffer *keyId,
const PARCBuffer *contentObjectHash,
const uint32_t hopLimit)
{
CCNxInterest *result = NULL;
if (impl->create != NULL) {
result = impl->create(name, interestLifetime, keyId, contentObjectHash, hopLimit);
// And set the dictionary's interface pointer to the one we just used to create this.
ccnxTlvDictionary_SetMessageInterface(result, impl);
} else {
trapNotImplemented("Interest implementations must implement create()");
}
return result;
}
CCNxInterest *
ccnxInterest_CreateSimple(const CCNxName *name)
{
return ccnxInterest_Create(name,
CCNxInterestDefault_LifetimeMilliseconds,
NULL,
NULL);
}
void
ccnxInterest_AssertValid(const CCNxInterest *interest)
{
assertNotNull(interest, "Must be a non-null pointer to a CCNxInterest.");
// Check for required fields in the underlying dictionary. Case 1036
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
assertNotNull(impl, "Interest must have an valid implementation pointer.");
if (impl->assertValid != NULL) {
impl->assertValid(interest);
}
}
CCNxInterest *
ccnxInterest_Acquire(const CCNxInterest *instance)
{
return ccnxTlvDictionary_Acquire(instance);
}
void
ccnxInterest_Release(CCNxInterest **instanceP)
{
ccnxTlvDictionary_Release(instanceP);
}
bool
ccnxInterest_Equals(const CCNxInterest *a, const CCNxInterest *b)
{
if (a == b) {
return true;
}
if (a == NULL || b == NULL) {
return false;
}
CCNxInterestInterface *implA = ccnxInterestInterface_GetInterface(a);
CCNxInterestInterface *implB = ccnxInterestInterface_GetInterface(b);
if (implA != implB) {
return false;
}
CCNxName *nameA = implA->getName(a);
CCNxName *nameB = implB->getName(b);
PARCBuffer *keyA = implA->getKeyIdRestriction(a);
PARCBuffer *keyB = implB->getKeyIdRestriction(b);
uint64_t lifetimeA = implA->getLifetime(a);
uint64_t lifetimeB = implB->getLifetime(b);
if (ccnxName_Equals(nameA, nameB)) {
if (parcBuffer_Equals(keyA, keyB)) {
// Must compare the excludes.
if (lifetimeA == lifetimeB) {
return true;
}
}
}
return false;
}
CCNxName *
ccnxInterest_GetName(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
CCNxName *result = NULL;
if (impl->getName != NULL) {
result = impl->getName(interest);
} else {
trapNotImplemented("ccnxInterest_GetName");
}
return result;
}
//by wschoi
CCNxName *
ccnxInterest_GetKeyName(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
CCNxName *result = NULL;
if (impl->getName != NULL) {
result = impl->getKeyName(interest);
} else {
trapNotImplemented("ccnxInterest_GetKeyName");
}
return result;
}
bool
ccnxInterest_SetContentObjectHashRestriction(CCNxInterest *interest, const PARCBuffer *contentObjectHash)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setContentObjectHashRestriction != NULL) {
result = impl->setContentObjectHashRestriction(interest, contentObjectHash);
} else {
trapNotImplemented("ccnxInterest_SetContentObjectHashRestriction");
}
return result;
}
PARCBuffer *
ccnxInterest_GetContentObjectHashRestriction(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getContentObjectHashRestriction != NULL) {
result = impl->getContentObjectHashRestriction(interest);
} else {
trapNotImplemented("ccnxInterest_GetContentObjectHash");
}
return result;
}
bool
ccnxInterest_SetKeyIdRestriction(CCNxInterest *interest, const PARCBuffer *keyId)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setKeyIdRestriction != NULL) {
result = impl->setKeyIdRestriction(interest, keyId);
} else {
trapNotImplemented("ccnxInterest_SetKeyIdRestriction");
}
return result;
}
PARCBuffer *
ccnxInterest_GetKeyIdRestriction(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getKeyIdRestriction != NULL) {
result = impl->getKeyIdRestriction(interest);
} else {
trapNotImplemented("ccnxInterest_GetKeyIdRestriction");
}
return result;
}
bool
ccnxInterest_SetLifetime(CCNxInterest *interest, uint32_t lifetime)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setLifetime != NULL) {
result = impl->setLifetime(interest, lifetime);
} else {
trapNotImplemented("ccnxInterest_SetLifetime");
}
return result;
}
uint32_t
ccnxInterest_GetLifetime(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
uint32_t result = 0;
if (impl->getLifetime != NULL) {
result = impl->getLifetime(interest);
} else {
trapNotImplemented("ccnxInterest_GetLifetime");
}
return result;
}
//by wschoi
#if 0
bool
ccnxInterest_SetPayload_lookup(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload != NULL) {
result = impl->setPayload_lookup(interest, payload);
printf("##########ccnxInterest_SetPayload_lookup\n\n");
}else {
trapNotImplemented("ccnxInterest_SetPayload");
}
return result;
}
#endif
//by wschoi
//refresh
#if 0
bool
ccnxInterest_SetPayload_refresh_key(CCNxInterest *interest, const PARCBuffer *payload)
{
printf("ccnxInterest_SetPayload_refresh_key() start\n");
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_refresh_key != NULL) {
result = impl->setPayload_refresh_key(interest, payload);
}else {
trapNotImplemented("ccnxInterest_SetPayload_refresh_key");
}
printf("ccnxInterest_SetPayload_refresh_key() end\n");
return result;
}
bool
ccnxInterest_SetPayload_refresh_value(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_refresh_value != NULL) {
result = impl->setPayload_refresh_value(interest, payload);
}else {
trapNotImplemented("cccnxInterest_SetPayload_refresh_value");
}
return result;
}
#endif
//by wschoi
//dereg
#if 1
bool
ccnxInterest_SetPayload_dereg_key(CCNxInterest *interest, const PARCBuffer *payload)
{
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_dereg_key() start\n");
#endif
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_dereg_key != NULL) {
result = impl->setPayload_dereg_key(interest, payload);
}else {
trapNotImplemented("ccnxInterest_SetPayload_dereg_key");
}
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_dereg_key() end\n");
#endif
return result;
}
bool
ccnxInterest_SetPayload_dereg_value(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_dereg_value != NULL) {
result = impl->setPayload_dereg_value(interest, payload);
}else {
trapNotImplemented("cccnxInterest_SetPayload_dereg_value");
}
return result;
}
#endif
//by wschoi
//del
#if 1
bool
ccnxInterest_SetPayload_del_key(CCNxInterest *interest, const PARCBuffer *payload)
{
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_del_key() start\n");
#endif
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_del_key != NULL) {
result = impl->setPayload_del_key(interest, payload);
}else {
trapNotImplemented("ccnxInterest_SetPayload_del_key");
}
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_del_key() end\n");
#endif
return result;
}
bool
ccnxInterest_SetPayload_del_value(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_del_value != NULL) {
result = impl->setPayload_del_value(interest, payload);
}else {
trapNotImplemented("cccnxInterest_SetPayload_del_value");
}
return result;
}
#endif
//by wschoi
//add
#if 1
bool
ccnxInterest_SetPayload_add_key(CCNxInterest *interest, const PARCBuffer *payload)
{
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_add_key() start\n");
#endif
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_add_key != NULL) {
result = impl->setPayload_add_key(interest, payload);
}else {
trapNotImplemented("ccnxInterest_SetPayload_add_key");
}
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_add_key() end\n");
#endif
return result;
}
bool
ccnxInterest_SetPayload_add_value(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_add_value != NULL) {
result = impl->setPayload_add_value(interest, payload);
}else {
trapNotImplemented("cccnxInterest_SetPayload_add_value");
}
return result;
}
#endif
//by wschoi
//registration
#if 1
bool
ccnxInterest_SetPayload_reg_key(CCNxInterest *interest, const PARCBuffer *payload)
{
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_reg_key() start\n");
#endif
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_reg_key != NULL) {
result = impl->setPayload_reg_key(interest, payload);
}else {
trapNotImplemented("ccnxInterest_SetPayload_reg_key");
}
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_reg_key() end\n");
#endif
return result;
}
bool
ccnxInterest_SetPayload_reg_value(CCNxInterest *interest, const PARCBuffer *payload)
{
#ifdef LOG_CHECK
printf("ccnxInterest_SetPayload_reg_value() start\n");
#endif
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_reg_value != NULL) {
result = impl->setPayload_reg_value(interest, payload);
}else {
trapNotImplemented("cccnxInterest_SetPayload_reg_value");
}
printf("ccnxInterest_SetPayload_reg_value() end\n");
return result;
}
#endif
//by wschoi
#if 1
bool
ccnxInterest_SetPayload_lookup(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload_lookup != NULL) {
result = impl->setPayload_lookup(interest, payload);
}else {
trapNotImplemented("ccnxInterest_SetPayload_lookup");
}
return result;
}
#endif
bool
ccnxInterest_SetPayload(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayload != NULL) {
result = impl->setPayload(interest, payload);
} else {
trapNotImplemented("ccnxInterest_SetPayload");
}
return result;
}
bool
ccnxInterest_SetPayloadAndId(CCNxInterest *interest, const PARCBuffer *payload)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayloadAndId != NULL) {
result = impl->setPayloadAndId(interest, payload);
} else {
trapNotImplemented("ccnxInterest_SetPayloadAndId");
}
return result;
}
bool
ccnxInterest_SetPayloadWithId(CCNxInterest *interest, const PARCBuffer *payload, const CCNxInterestPayloadId *payloadId)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayloadWithId != NULL) {
result = impl->setPayloadWithId(interest, payload, payloadId);
} else {
trapNotImplemented("ccnxInterest_SetPayloadWithId");
}
return result;
}
//by wschoi
bool
ccnxInterest_SetPayloadWithId_lookup(CCNxInterest *interest, const PARCBuffer *payload, const CCNxInterestPayloadId *payloadId)
{
#ifdef LOG_CHECK
printf("##########ccnxInterest_SetPayloadWithId_lookup\n\n");
#endif
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setPayloadWithId != NULL) {
result = impl->setPayloadWithId_lookup(interest, payload, payloadId);
#ifdef LOG_CHECK
printf("##########ccnxInterest_SetPayloadWithId_lookup\n\n");
#endif
} else {
trapNotImplemented("ccnxInterest_SetPayloadWithId");
}
return result;
}
//by wschoi
//LOOKUP TYPE
PARCBuffer *
ccnxInterest_GetPayload_lookup(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload != NULL) {
result = impl->getPayload_lookup(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_lookup");
}
return result;
}
PARCBuffer *
ccnxInterest_GetPayload_KeyName(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload != NULL) {
result = impl->getPayload_KeyName(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_KeyName");
}
return result;
}
//REGISTRATION TYPE
//registration
PARCBuffer *
ccnxInterest_GetPayload_reg_key(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_reg_key != NULL) {
result = impl->getPayload_reg_key(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_reg_key");
}
return result;
}
PARCBuffer *
ccnxInterest_GetPayload_reg_value(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_reg_value != NULL) {
result = impl->getPayload_reg_value(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_reg_value");
}
return result;
}
//add
PARCBuffer *
ccnxInterest_GetPayload_add_key(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_add_key != NULL) {
result = impl->getPayload_add_key(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_add_key");
}
return result;
}
PARCBuffer *
ccnxInterest_GetPayload_add_value(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_add_value != NULL) {
result = impl->getPayload_add_value(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_add_key");
}
return result;
}
//delete
PARCBuffer *
ccnxInterest_GetPayload_del_key(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_del_key != NULL) {
result = impl->getPayload_del_key(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_del_key");
}
return result;
}
PARCBuffer *
ccnxInterest_GetPayload_del_value(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_del_value != NULL) {
result = impl->getPayload_del_value(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_del_value");
}
return result;
}
//dereg
PARCBuffer *
ccnxInterest_GetPayload_dereg_key(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_dereg_key != NULL) {
result = impl->getPayload_dereg_key(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_dereg_key");
}
return result;
}
PARCBuffer *
ccnxInterest_GetPayload_dereg_value(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_dereg_value != NULL) {
result = impl->getPayload_dereg_value(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_dereg_value");
}
return result;
}
//refresh
#if 0
PARCBuffer *
ccnxInterest_GetPayload_refresh_key(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_refresh_key != NULL) {
result = impl->getPayload_refresh_key(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_refresh_key");
}
return result;
}
PARCBuffer *
ccnxInterest_GetPayload_refresh_value(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload_refresh_value != NULL) {
result = impl->getPayload_refresh_value(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload_refresh_value");
}
return result;
}
#endif
PARCBuffer *
ccnxInterest_GetPayload(const CCNxInterest *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
PARCBuffer *result = NULL;
if (impl->getPayload != NULL) {
result = impl->getPayload(interest);
} else {
trapNotImplemented("ccnxInterest_GetPayload");
}
return result;
}
bool
ccnxInterest_SetHopLimit(CCNxTlvDictionary *interest, uint32_t hopLimit)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
bool result = false;
if (impl->setHopLimit != NULL) {
result = impl->setHopLimit(interest, hopLimit);
} else {
trapNotImplemented("ccnxInterest_GetSetHopLimit");
}
// Make sure any attached wire format buffers are in sync with the dictionary
ccnxWireFormatMessage_SetHopLimit(interest, hopLimit);
return result;
}
uint32_t
ccnxInterest_GetHopLimit(const CCNxTlvDictionary *interest)
{
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
uint32_t result = 0;
if (impl->getHopLimit != NULL) {
result = impl->getHopLimit(interest);
} else {
trapNotImplemented("ccnxInterest_GetHopLimit");
}
return result;
}
void
ccnxInterest_Display(const CCNxInterest *interest, int indentation)
{
ccnxInterest_OptionalAssertValid(interest);
parcDisplayIndented_PrintLine(indentation, "CCNxInterest@%p {\n", interest);
ccnxName_Display(ccnxInterest_GetName(interest), indentation + 1);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
if (impl->display != NULL) {
impl->display(interest, 1);
}
parcDisplayIndented_PrintLine(indentation, "}\n");
}
char *
ccnxInterest_ToString(const CCNxInterest *interest)
{
char *result = NULL;
ccnxInterest_OptionalAssertValid(interest);
CCNxInterestInterface *impl = ccnxInterestInterface_GetInterface(interest);
if (impl->toString != NULL) {
result = impl->toString(interest);
} else {
char *name = ccnxName_ToString(ccnxInterest_GetName(interest));
uint32_t lifetime = ccnxInterest_GetLifetime(interest);
char *string;
int failure = asprintf(&string, "CCNxInterest{.name=\"%s\" .lifetime=%dms}", name, lifetime);
assertTrue(failure > 0, "Error from asprintf");
parcMemory_Deallocate((void **) &name);
result = parcMemory_StringDuplicate(string, strlen(string));
free(string);
}
return result;
}
|
<filename>src/resolvers/userResolvers/index.ts
export * as userMutations from './mutations/index'
export * as userQueries from './queries/index' |
// StringValue is a convenience to create a String value. If tt is nil, a value of
// StringType is returned, otherwise requires tt must be of the String kind.
func StringValue(tt *Type, x string) *Value {
if tt == nil {
tt = StringType
}
v := ZeroValue(tt)
v.AssignString(x)
return v
} |
// DashboardRowLayoutRowsWidgetsScorecardToProto converts a DashboardRowLayoutRowsWidgetsScorecard object to its proto representation.
func MonitoringDashboardRowLayoutRowsWidgetsScorecardToProto(o *monitoring.DashboardRowLayoutRowsWidgetsScorecard) *monitoringpb.MonitoringDashboardRowLayoutRowsWidgetsScorecard {
if o == nil {
return nil
}
p := &monitoringpb.MonitoringDashboardRowLayoutRowsWidgetsScorecard{}
p.SetTimeSeriesQuery(MonitoringDashboardRowLayoutRowsWidgetsScorecardTimeSeriesQueryToProto(o.TimeSeriesQuery))
p.SetGaugeView(MonitoringDashboardRowLayoutRowsWidgetsScorecardGaugeViewToProto(o.GaugeView))
p.SetSparkChartView(MonitoringDashboardRowLayoutRowsWidgetsScorecardSparkChartViewToProto(o.SparkChartView))
sThresholds := make([]*monitoringpb.MonitoringDashboardRowLayoutRowsWidgetsScorecardThresholds, len(o.Thresholds))
for i, r := range o.Thresholds {
sThresholds[i] = MonitoringDashboardRowLayoutRowsWidgetsScorecardThresholdsToProto(&r)
}
p.SetThresholds(sThresholds)
return p
} |
Parallel Selection with High Probability
Given a set of n elements in some unknown order, parallel comparison algorithms to select the tth highest with probability $1- o(1)$ as $n \to \infty $ are considered, where each order is assumed to be equally likely. Such an algorithm is given using four rounds and $cn$ comparisons per round, and it is shown that no such algorithm exists using three rounds and $cn$ comparisons per round. |
<reponame>haddocking/haddock3
"""Running CNS scripts"""
import os
import shlex
import subprocess
from haddock.core.defaults import CNS_EXE, NUM_CORES
from haddock.core.exceptions import CNSRunningError, JobRunningError
from haddock.libs.libparallel import Scheduler
class Job:
"""A job to be executed by the engine"""
def __init__(self, input, output, executable, *args):
self.input = input
self.output = output
self.executable = executable
self.args = args
def run(self):
cmd = " ".join([
os.fspath(self.executable),
''.join(map(str, self.args)), # empty string if no args
os.fspath(self.input),
])
with open(self.output, 'w') as outf:
p = subprocess.Popen(shlex.split(cmd),
stdout=outf,
close_fds=True)
out, error = p.communicate()
p.kill()
if error:
raise JobRunningError(error)
return out
class CNSJob:
"""A CNS job script"""
def __init__(self, input_file, output_file, cns_folder='.',
cns_exec=CNS_EXE):
"""
:param input_file: input CNS script
:param output_file: CNS output
:cns_folder: absolute execution path
:cns_exec: CNS binary including absolute path
"""
self.input_file = input_file
self.output_file = output_file
self.cns_folder = cns_folder
self.cns_exec = cns_exec
def run(self):
"""Run this CNS job script"""
with open(self.input_file) as inp:
with open(self.output_file, 'w+') as outf:
env = {'RUN': self.cns_folder}
p = subprocess.Popen(self.cns_exec,
stdin=inp,
stdout=outf,
close_fds=True,
env=env)
out, error = p.communicate()
p.kill()
if error:
raise CNSRunningError(error)
return out
|
About This Game A classical fairy-tale springs to life in this charming, chalk-art puzzle/platformer!
Dokuro puts players in command of a charming little skeleton who is fed up with his master, the Dark Lord, and resolves to rescue a recently kidnapped princess. The princess is blind to the various dangers and pitfalls of the castle and will continue to move forward -- potentially to her doom-- if our hero doesn't do something! Upon coiffing down a magical blue elixir, Dokuro gains the ability to transform into a swashbuckling hero. This noble form allows him to save the day and simultaneously catch the eye of the otherwise unaware princess.
Push, pull, jump and toggle to solve unique and increasingly difficult puzzles. Handle inhospitable situations with the power of the almighty chalk! Different colors of chalk allow our little bonehead to draw lines of flame, create great bodies of water, and repair broken ropes. If those challenges aren't harrowing enough, there’s also a fair amount of skillful jumping, slashing, and dodging required to get through the tough-as-nails platforming segments!
With new visual effects, a revamped UI, and a full set of Steam achievements, the critically acclaimed Dokuro is finally arriving on the PC!
Main Features:
*Captivating chalk style art – Immerse yourself in the gorgeous fairytale setting as you help Dokuro save the Princess from the Dark Lord.
*Unique, intuitive controls – Toggle switches, hack away at your foes, and draw your solutions in chalk to help keep the Princess safe.
*Tons of engrossing content – Features almost 150 platform/puzzle filled levels that will require dexterity of both body and mind as you fight through 20-30 hours of gameplay.
*Full complement of Steam Achievements to earn – Master the Dark Lord’s treacherous puzzles, collect the coins in each level, and complete all challenges ahead of you bolster your collection of achievements. |
/**
* identifies that this object can be destroyed
*/
export interface Destroyable {
/**
* destroys this object
*/
destroy(): void;
}
|
The viewing figures got off to a solid start, and the early weekend coverage in the U.S. means the games have been given a chance to grow a fanbase.
NBC's decision to bet big on soccer, signing a three-year deal to snatch U.S. rights for England's Premier League away from Fox, was considered one of the riskier rights deals of the past few years.
Many have tried to sell the world's favorite game to American fans. Many have failed.
But expect a surprising, that is a surprisingly large, number of Americans to tune in to NBCUniversal's live Premier League coverage this weekend.
The first two weeks of top-flight soccer have exceeded everyone's U.S. rating expectations, reaching a peak with NBC Sports Network and NBC Sports Live Extra drawing record numbers for coverage of Monday afternoon's Manchester United vs. Chelsea Premier League match.
NBC Sports Network's telecast averaged 536,000 viewers – its best weekday audience since the 2012 London Olympics. Viewership peaked at 682,000.
While numbers like that are "not great if you're trying to keep a sitcom on the air," for soccer coverage in the U.S. they rate "at least a triple if not a home run," Dave Morgan, managing editor, international at sports industry news site Sports Business Daily Global told The Hollywood Reporter.
Jon Miller, president of programming for NBC and NBC Sports Network, credits that initial success to not dumbing down or otherwise "Americanizing" its Premier League coverage for a U.S. audience.
"In the past, NBC has been as guilty as all the other networks in trying to fit a square peg in a round hole when it comes to soccer and the U.S. audience," Miller said. "This time we were determined not to Americanize this product. The Premier League is English and our broadcasts are uniquely English with a great English host in (former BBC Sports presenter) Rebecca Lowe and knowledgeable commentators who know the Premier League and can talk about it intelligently."
Speaking to THR, Lowe said she makes only minor adjustments in presenting to a U.S. audience such as paraphrasing the meaning of local derby (a match between teams from the same city or locality) "so that casual fans aren't left out."
Lowe, however, admits to having to explain the offside rule. "Because actually nobody anywhere understands the offside rule. It has changed so much and become so complicated."
NBC's approach to the beautiful game has won plaudits from U.S. fans, but Miller admits the network has also come to soccer at the right time, when interest in the sport is surging in the States. "Things have changed a lot. The U.S. audience has changed, its become more cosmopolitan, more open to new properties, he said. "I think the game itself has also changed in the way it's produced and in the way it's distributed, which provides many more possibilities to reach audiences."
"Soccer is gaining an audience here, you can see that from the growth of the MLS all the way down to the youth leagues," Morgan added. "And NBC's put together a good package. Technically it's strong, lots of camera angles, smartly shot, and without commercials that ruin the natural flow of the games."
Interestingly for NBC's ad team, the demographics of U.S. soccer fans seem to skew much younger than that of the average American sports fan.
"It's also a much better educated demo, much closer to the demo we get for the Olympics or for hockey," Miller said.
Even with the solid start, Premier League soccer in the U.S. is still a long ways from being a mainstream spectator sport.
Critics also point to the fact that for the first two weekends NBC's soccer games had no real competition since they air in the early morning in the U.S. when no other live sports are on.
That could change with the start of the college football season, where kickoff times mean a few Premier League matches will go head-to-head with the NCAA games.
Miller, however, argues the impact will be minimal.
The U.S. soccer audience is still tiny compared to the millions that tune in every week in the U.K. and around the world to watch the English Premier League. But NBC's initial success has set off speculation as to how big soccer could get in America.
Said Morgan: "Is it going to knock college football off the top off the charts? No. But I don't think that is NBC's goal with this package."
Miller avoided giving a concrete ratings forecast for the Premier League, saying the initial numbers have "already far exceeded our expectations. … Our biggest challenge right now isn't to grow the figures, our biggest challenge is to not to mess it up."
It remains, as always, a game of two halves for everyone. |
// Actions the card should do.
@Override
public void use(AbstractPlayer p, AbstractMonster m) {
if (playedBySwarm && m.isDeadOrEscaped()){
m = AbstractDungeon.getMonsters().getRandomMonster((AbstractMonster)null, true, AbstractDungeon.cardRandomRng);
}
if (isHornet) {
AbstractDungeon.actionManager.addToBottom(new DamageAction(m, new DamageInfo(p, damage, damageTypeForTurn), AbstractGameAction.AttackEffect.SLASH_DIAGONAL));
}
if (isBumblebee) {
AbstractDungeon.actionManager.addToBottom(new GainBlockAction(p, p, block));
}
if (isHoneyBee) {
AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new Nectar(p, p, magicNumber), magicNumber));
}
if (isDrone && !isUpgradedDrone) {
AbstractDungeon.actionManager.addToBottom(new DrawCardAction(p, 1));
}
if (isDrone && isUpgradedDrone) {
AbstractDungeon.actionManager.addToBottom(new DrawCardAction(p, 2));
}
if (isHornetCommander) {
AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new HornetCommanderPower(p, p, this.defaultSecondMagicNumber), this.defaultSecondMagicNumber));
}
if (isBumbleBeeCommander) {
AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new BumbleBeeCommanderPower(p, p, this.defaultSecondMagicNumber), this.defaultSecondMagicNumber));
}
if (isDroneCommander) {
AbstractDungeon.actionManager.addToBottom(new UpgradeSpecificCardInDrawPileAction(p, new Drone(), true));
}
} |
/**
* @brief Armazena float do topo da pilha de operandos no array de variaveis locais no indice 2
* @param *curr_frame Ponteiro para o frame atual
* @return void
*/
void fstore_2(Frame* curr_frame) {
Operand *op = curr_frame->operand_stack.top();
curr_frame->operand_stack.pop();
curr_frame->local_variables_array[2] = op;
curr_frame->pc++;
} |
/// Run all schema migrations.
///
/// When multiple `graph-node` processes start up at the same time, we ensure
/// that they do not run migrations in parallel by using `blocking_conn` to
/// serialize them. The `conn` is used to run the actual migration.
fn migrate_schema(logger: &Logger, conn: &PgConnection) -> Result<(), StoreError> {
// Collect migration logging output
let mut output = vec![];
info!(logger, "Running migrations");
let result = embedded_migrations::run_with_output(conn, &mut output);
info!(logger, "Migrations finished");
// If there was any migration output, log it now
let msg = String::from_utf8(output).unwrap_or_else(|_| String::from("<unreadable>"));
let msg = msg.trim();
let has_output = !msg.is_empty();
if has_output {
let msg = msg.replace('\n', " ");
if let Err(e) = result {
error!(logger, "Postgres migration error"; "output" => msg);
return Err(StoreError::Unknown(e.into()));
} else {
debug!(logger, "Postgres migration output"; "output" => msg);
}
}
if has_output {
// We take getting output as a signal that a migration was actually
// run, which is not easy to tell from the Diesel API, and reset the
// query statistics since a schema change makes them not all that
// useful. An error here is not serious and can be ignored.
conn.batch_execute("select pg_stat_statements_reset()").ok();
}
Ok(())
} |
{-# LANGUAGE TemplateHaskell #-}
module Day10(
solve1',
solve2',
) where
import Relude
import Relude.Extra.Foldable1
import Data.Text (pack, unpack)
import Control.Lens
import qualified Data.Set as Set
import Linear.V2
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Show (Show(..))
import Utils.Parsing
data Point = Point {
_location :: V2 Int,
_velocity :: V2 Int
} deriving (Show)
makeLenses ''Point
vectorParser :: Parser (V2 Int)
vectorParser = do
_ <- char '<'
_ <- optional (char ' ')
x <- signedIntParser
_ <- char ','
_ <- char ' '
_ <- optional (char ' ')
y <- signedIntParser
_ <- char '>'
pure $ V2 x y
pointParser :: Parser Point
pointParser = do
_ <- string "position="
location <- vectorParser
_ <- string " velocity="
velocity <- vectorParser
pure $ Point location velocity
pointsParser :: Parser [Point]
pointsParser = sepBy pointParser newline
data BoundingBox = BoundingBox {
_topLeft :: V2 Int,
_bottomRight :: V2 Int
} deriving (Show)
makeLenses ''BoundingBox
height :: BoundingBox -> Int
height (BoundingBox (V2 minX minY) (V2 maxX maxY)) = maxY - minY
getBoundingBoxRows :: BoundingBox -> [[V2 Int]]
getBoundingBoxRows (BoundingBox (V2 minX minY) (V2 maxX maxY)) = [[V2 x y | x <- [minX..maxX]] | y <- [minY..maxY]]
data PossibleMessage = PossibleMessage {
_visiblePoints :: Set.Set (V2 Int),
_boundingBox :: BoundingBox
}
makeLenses ''PossibleMessage
instance Show PossibleMessage where
show message = "\n" <> (unpack $ unlines $ fmap (pack . fmap pointChar) rows)
where rows = getBoundingBoxRows (view boundingBox message)
pointChar p = if Set.member p (view visiblePoints message) then '#' else '.'
-- end to end solving functions
solve1' = solve1 <=< parseMaybe pointsParser
solve2' = solve2 <=< parseMaybe pointsParser
tick :: NonEmpty Point -> NonEmpty Point
tick ps = fmap (\p -> over location ((+) (view velocity p)) p) ps
makeBoundingBox :: NonEmpty Point -> BoundingBox
makeBoundingBox ps = BoundingBox (V2 minX minY) (V2 maxX maxY)
where
xs = fmap (view (location . _x)) ps
minX = minimum1 xs
maxX = maximum1 xs
ys = fmap (view (location . _y)) ps
minY = minimum1 ys
maxY = maximum1 ys
toSet :: (Foldable f, Ord a) => f a -> Set.Set a
toSet xs = Set.fromList (toList xs)
draw :: NonEmpty Point -> PossibleMessage
draw ps = PossibleMessage (toSet (fmap (view location) ps)) (makeBoundingBox ps)
-- solve1 :: [Point] -> Int
solve1 ps = do
nonEmptyPs <- nonEmpty ps
final <- viaNonEmpty head $ dropWhile ((\h -> h > 10) . height . makeBoundingBox) $ iterate tick nonEmptyPs
pure $ draw final
solve2 ps = do
nonEmptyPs <- nonEmpty ps
let final = length $ takeWhile ((\h -> h > 10) . height . makeBoundingBox) $ iterate tick nonEmptyPs
pure $ final
|
// DisableThrottlerOptions suppresses the presence of throttler-related flags,
// effectively disallowing external users to parametrize default throttling
// behavior. This is useful mostly when a program creates multiple GH clients
// with different behavior.
func DisableThrottlerOptions() FlagParameter {
return func(o *flagParams) {
o.disableThrottlerOptions = true
}
} |
// Write results to results_dir and return them as
// an ActionOutput struct
static ActionOutput write_download_results(const fs::path& results_dir,
const int exit_code,
const std::string& std_out,
const std::string& std_err)
{
lth_file::atomic_write_to_file(std::to_string(exit_code) + "\n",
(results_dir / "exitcode").string(),
NIX_FILE_PERMS,
std::ios::binary);
lth_file::atomic_write_to_file(std_out,
(results_dir / "stdout").string(),
NIX_FILE_PERMS,
std::ios::binary);
lth_file::atomic_write_to_file(std_err,
(results_dir / "stderr").string(),
NIX_FILE_PERMS,
std::ios::binary);
return ActionOutput { exit_code, std_out, std_err };
} |
// Unsubscribe is used to send an Unsubscribe request to the MQTT server.
// It is passed a pre-prepared Unsubscribe packet and blocks waiting for
// a response Unsuback, or for the timeout to fire. Any response Unsuback
// is returned from the function, along with any errors.
func (c *Client) Unsubscribe(ctx context.Context, u *Unsubscribe) (*Unsuback, error) {
debug.Printf("unsubscribing from %+v", u.Topics)
unsubCtx, cf := context.WithTimeout(ctx, c.PacketTimeout)
defer cf()
cpCtx := &CPContext{unsubCtx, make(chan packets.ControlPacket, 1)}
up := u.Packet()
up.PacketID = c.MIDs.Request(cpCtx)
debug.Println("sending UNSUBSCRIBE")
if _, err := up.WriteTo(c.Conn); err != nil {
return nil, err
}
debug.Println("waiting for UNSUBACK")
var uap packets.ControlPacket
select {
case <-unsubCtx.Done():
if e := unsubCtx.Err(); e == context.DeadlineExceeded {
debug.Println("timeout waiting for UNSUBACK")
return nil, e
}
case uap = <-cpCtx.Return:
}
if uap.Type != packets.UNSUBACK {
return nil, fmt.Errorf("received %d instead of Unsuback", uap.Type)
}
debug.Println("received SUBACK")
ua := UnsubackFromPacketUnsuback(uap.Content.(*packets.Unsuback))
switch {
case len(ua.Reasons) == 1:
if ua.Reasons[0] >= 0x80 {
var reason string
debug.Println("received an error code in Unsuback:", ua.Reasons[0])
if ua.Properties != nil {
reason = ua.Properties.ReasonString
}
return ua, fmt.Errorf("failed to unsubscribe from topic: %s", reason)
}
default:
for _, code := range ua.Reasons {
if code >= 0x80 {
debug.Println("received an error code in Suback:", code)
return ua, fmt.Errorf("at least one requested unsubscribe failed")
}
}
}
return ua, nil
} |
The First Battle of Gettysburg: April 22, 1861
The fears of invasion voiced by the residents of south-central Pennsylvania prior to the Gettysburg Campaign are often the subject of ridicule in books and articles written on the battle. But to appreciate the events that occurred during the summer of 1863, it is necessary to understand how the citizens were affected by the constant rumors of invasion during the first two years of the war. And although there were many such scares prior to the battle, nothing reached the level of anxiety that was felt during the first few days of the war. On Monday morning, April 15, 1861, following the surrender of Fort Sumter, Abraham Lincoln issued a proclamation calling for 75,000 volunteers from the loyal states to suppress the Rebellion so as to "maintain the honor, the integrity, and existence of our national Union." |
Links between the Orientation of Vascular Smooth Muscle and Microscopical Composition of Aortic Segments
We analyzed histological data statistically describing the distribution of orientations of vascular smooth muscle cells (VSMC) within porcine aorta. The data were correlated with the fractions of actin, desmin, vimentin, elastin and collagen within the same samples. In samples with more contractile VSMC and less elastin, the symmetrical helices of VSMC were arranged closely to each other and they were more concentrated than in samples with fewer actin-and desmin-positive VSMC and more elastin. The findings are suitable for microstructurally-motivated biomechanical modeling of porcine aorta under normal conditions. |
import numpy as np
import pytest
from neuraxle.steps.numpy import OneHotEncoder
@pytest.mark.parametrize("n_dims", [1, 2, 3])
@pytest.mark.parametrize("no_columns", [10])
def test_one_hot_encode_should_encode_data_inputs(n_dims, no_columns):
one_hot_encode = OneHotEncoder(nb_columns=no_columns, name='one_hot')
data_shape = list(range(100, 200))[:n_dims]
data_inputs = np.random.randint(low=no_columns, size=data_shape)
data_inputs[0] = 0
data_inputs[1] = no_columns - 1
data_inputs[-2] = -1 # or nan or inf.
outputs = one_hot_encode.transform(data_inputs)
assert outputs.shape[-1] == no_columns
assert ((outputs == 1) | (outputs == 0)).all()
if n_dims >= 2:
assert (outputs[0, ..., 0] == 1).all()
assert (outputs[1, ..., -1] == 1).all()
assert (outputs[-2, ...] == 0).all()
|
import io
import os
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
DEBUG = False
def solve(N, X, Y, B):
# Want X matching, and Y - X in derangement, and pad rest (pad possibly mixed with the derangements)
match = X
derange = Y - X
if DEBUG:
print()
print("derange", derange, "match", match)
print("B")
print(B)
padVal = next(iter(set(range(1, N + 2)) - set(B)))
A = [padVal for i in range(N)]
if DEBUG:
print("after pad")
print(A)
valToIndices = defaultdict(list)
for i, x in enumerate(B):
valToIndices[x].append(i)
heap = []
for val, indices in valToIndices.items():
heap.append((-len(indices), val))
heapify(heap)
def take(count):
ret = []
readd = []
for i in range(count):
if not heap:
break
negCount, val = heappop(heap)
i = valToIndices[val].pop()
ret.append(i)
if negCount != -1:
readd.append((negCount + 1, val))
for tup in readd:
heappush(heap, tup)
return ret
while heap and match:
(i,) = take(1)
A[i] = B[i]
match -= 1
assert match == 0
if DEBUG:
print("after match")
print(A)
while heap and derange > 1:
indices = take(2)
if len(indices) != 2:
return "NO"
i, j = indices
A[i], A[j] = B[j], B[i]
derange -= 2
if derange == 1:
j, = take(1)
for i, x in enumerate(A):
if A[i] != B[i] and A[i] != B[j] and B[i] != B[j]:
A[i], A[j] = B[j], A[i]
derange -= 1
break
else:
return "NO"
assert derange == 0
if DEBUG:
print("after derange")
print(A)
if DEBUG:
aFreq = Counter(A)
bFreq = Counter(B)
xCheck = sum(1 for a, b in zip(A, B) if a == b)
yCheck = sum(min(aFreq[k], bFreq[k]) for k in aFreq.keys() & bFreq.keys())
assert xCheck == X
assert yCheck == Y
return "YES\n" + " ".join(str(x) for x in A)
if DEBUG:
import random
random.seed(0)
for _ in range(100000):
N = random.randint(1, 10)
A = [random.randint(1, N + 1) for i in range(N)]
B = [random.randint(1, N + 1) for i in range(N)]
X = sum(1 for a, b in zip(A, B) if a == b)
aFreq = Counter(A)
bFreq = Counter(B)
Y = sum(min(aFreq[k], bFreq[k]) for k in aFreq.keys() & bFreq.keys())
if solve(N, X, Y, B) == "NO":
print("expected")
print(B)
print(A)
assert False
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for tc in range(1, T + 1):
N, X, Y = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
ans = solve(N, X, Y, B)
print(ans)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.