content
stringlengths 7
2.61M
|
---|
The Lakers and the Buss family released a statement shooting down a published report suggesting they might sell the franchise to an outside group.
“We unanimously agree that we have no intention of ever selling the Lakers, and intend to keep ownership of the team in our family for generations to come,” the statement read.
Jerry Buss, 78, has owned the Lakers since 1979, when he purchased the team along with the Forum, the NHL’s Kings and a 13,000-acre ranch in Kern County for $67million from Jack Kent Cooke. Since then, the Lakers have become one of the sport’s top franchises, winning 10 of their 16 NBA championships under Buss’ watch.
In recent years, Buss has experienced declining health and has gradually ceded more control of the Lakers.
Buss’ daughter, Jeanie, is the team’s executive vice president of business operations, while Buss’ son, Jim, is the team’s executive vice president of player personnel. The Lakers were recently listed by Forbes Magazine as the second-most-valuable NBA team at $1billion, trailing the New York Knicks.
With the Lakers showing little sign they’ll climb out of the Western Conference cellar, coach Mike D’Antoni conceded what many fans have thought about him in recent weeks.
Don’t expect the Lakers to fire D’Antoni, however. When the Lakers fired Mike Brown following a 1-4 start, he had $10million left on his contract through the 2013-14 season. D’Antoni signed with the Lakers on a $12million deal that lasts through the 2014-15 season, with a team option the following year. Meanwhile, the Lakers already have a $100million payroll and an additional $30million in luxury taxes.
It sounds ridiculous to ask, considering the Lakers boast four future Hall of Famers in Kobe Bryant, Steve Nash, Dwight Howard and Pau Gasol, but does D’Antoni believe he has the pieces needed to turn things around?
D’Antoni conceded he hasn’t convinced everyone to embrace their roles.
|
/**
* Calculator of the currency exposure for Forex derivatives in the Black (Garman-Kohlhagen) world. The volatilities are given by delta-smile descriptions.
* To compute the currency exposure, the Black volatility is kept constant; the volatility is not recomputed for spot and forward changes.
*/
public final class CurrencyExposureBlackSmileForexCalculator extends CurrencyExposureForexCalculator {
/**
* The unique instance of the calculator.
*/
private static final CurrencyExposureBlackSmileForexCalculator s_instance = new CurrencyExposureBlackSmileForexCalculator();
/**
* Gets the calculator instance.
* @return The calculator.
*/
public static CurrencyExposureBlackSmileForexCalculator getInstance() {
return s_instance;
}
/**
* Constructor.
*/
private CurrencyExposureBlackSmileForexCalculator() {
}
/**
* The methods used by the different instruments.
*/
private static final ForexOptionVanillaBlackSmileMethod METHOD_FXOPTION = ForexOptionVanillaBlackSmileMethod.getInstance();
private static final ForexOptionSingleBarrierBlackMethod METHOD_FXOPTIONBARRIER = ForexOptionSingleBarrierBlackMethod.getInstance();
private static final ForexNonDeliverableOptionBlackMethod METHOD_NDO = ForexNonDeliverableOptionBlackMethod.getInstance();
private static final ForexOptionDigitalBlackMethod METHOD_FXOPTIONDIGITAL = ForexOptionDigitalBlackMethod.getInstance();
@Override
public MultipleCurrencyAmount visitForexOptionVanilla(final ForexOptionVanilla derivative, final YieldCurveBundle data) {
return METHOD_FXOPTION.currencyExposure(derivative, data);
}
@Override
public MultipleCurrencyAmount visitForexOptionSingleBarrier(final ForexOptionSingleBarrier derivative, final YieldCurveBundle data) {
return METHOD_FXOPTIONBARRIER.currencyExposure(derivative, data);
}
@Override
public MultipleCurrencyAmount visitForexNonDeliverableOption(final ForexNonDeliverableOption derivative, final YieldCurveBundle data) {
return METHOD_NDO.currencyExposure(derivative, data);
}
@Override
public MultipleCurrencyAmount visitForexOptionDigital(final ForexOptionDigital derivative, final YieldCurveBundle data) {
return METHOD_FXOPTIONDIGITAL.currencyExposure(derivative, data);
}
}
|
Antivirulence effects of pomegranate peel extracts on most common urinary tract infection pathogens in pregnant women Objective This study includes the investigation of antibacterial and antivirulence activities of three types of pomegranate peel extracts and then determines the interaction between the extracts and antibiotic in vitro. Methods The ability of most common isolated bacteria from urinary tract infection (UTI) to produce different virulence factors were tested and the effect of plant extracts on virulence factors were determined; in addition the correlation between extracts and antibiotics were evaluated by using fractional inhibitory concentrations. Results The inhibition zones diameters of the pomegranate peel extracts against most common isolated bacteria (Staphylococcus aureus and Escherichia coli) increase significantly with increase in concentrations. There is no effect of the extracts on the ability of studied bacteria to produce hemolysin and protease enzymes, while both studied bacteria lost its ability to produce -lactamase enzyme after treating with MIC. In addition, extracts were affected largely on adherence activity and biofilm forming ability of tested bacteria. The results found that the pomegranate peel extracts effect alone against pathogenic bacteria was good than they interacted with antibiotics, in most of the results. Conclusion The alcohol extract was the best solvent in its effects on bacterial pathogen and its effect was largely on the ability of the studied bacteria to form biofilm and adhesion on the epithelial cell. The pomegranate peel extracts were high synergism with some antibiotics against pathogenic bacteria. Introduction Urinary tract infection (UTIs) is an injury resulting from the presence and the growth of microorganism in different parts of the urinary tract, so it could be defined as the colonization of and invasion of the structures in the urinary tract by micro-organisms. 1 In human, the urinary tract is one of the most common sites of bacterial infection and most case of UTI caused by bacteria which ascend from the perineum, and the reason of the ascent of bacteria raised by conditions like pregnancy. 2,3 UTIs are the most common problem during pregnancy as result of physiologic changes which are related to pregnancy that make healthy women more susceptible to acquired various injury. 4 UTIs are caused by different type of gram positive and negative bacteria like Escherichia coli, Klebsiella species, Proteus mirabilis, Pseudomonas aeruginosa, Enterococcus, Staphylococcus, and Streptococcus agalactiae. 5 The isolate bacteria produce deferent virulence factors which play essential roles in pathogenicity of these bacteria such as hemolysin (is an important virulence factor attached with especial receptors on the erythrocytes wall then making pours in the cell wall so the erythrocytes will lyse), -lactamase (enzyme that works to destroy the -lactam ring of antibiotic and causing the loss of effectiveness and contain serine amino acid in their hydroxyl group which represented the active site of this enzyme). 6 Pathogen adhesion to the host tissue is regarded as an important initiating step in many types of infection because it helps the bacteria to resist the defense mechanism in the body, 7 and biofilm formation (a slimy layer with embedded micro colonies) is most important and widespread mode for increase pathogenicity of the microorganism and helps bacteria to resist the surrounding environment condition and antibiotic concentration. 8 Some pathogens which are responsible for UTI are resistance to different types of antibiotic therefore relatively limited choice of antimicrobial agents can eliminate from the body so has become necessary to work to find a new techniques more effective for the treatment of infection caused by drug-resistant microorganism. Many types of medicinal plants contain various components some of which can operate in synergy with antibiotic but others are able to sensitize the pathogen to antibiotic. 9 Pomegranate is one of the medicinal plants used in medicine for treatment of several disease, which was one of the oldest fruits that have not changed much through the history of man and regarded as an important source of phenolic compounds, including hydrolysable tannins, which possess high antioxidant activity. 10 The screening of medicinal plant extracts for interactions with antibiotics is expected to provide chance to determine inhibitors that may benefit medicine. 11 The purpose of this study was to find a safety method to reduce pathogenicity of high virulence pathogenic bacteria responsible for UTI by using natural material and attempt to find a safety method to solve the problem of multi-drug resistance pathogen. Isolation and diagnosis of bacteria One hundred morning midstream urine samples were collected from pregnant women attending Maternity and Women's Hospital in Karbala Province during December 2011 to March 2012. The isolated bacteria were diagnosed biochemically according to methods described by Collee et al. 12 and Baron et al. 13 Then the diagnosed bacteria were confirmed by APi20E and Api Staph system accomplished according to manufacturer's instructions. The isolated bacteria used in the study were chosen according to their ability to give deep violet color on the wall and bottom of the test tubes, which was used to determine the biofilm forming as described by Mathur et al. 14 Interaction between the extracts of pomegranate peels and antibacterial and antivirulence activities Research Wafaa Sadeq Al-Wazni et al. Ability of isolated bacteria to produce virulence factors Blood agar plates and skim milk agar plates were used to determine the ability of isolated bacteria to produce hemolysin and protease enzyme, respectively, as described by Collee et al. 12 and Baron et al. 13 The -lactamase production was prepared according to WHO. 15 The adherence activity for studied bacteria was carried out according to Svanborg et al. 16 In addition we screwed isolates for their ability to form biofilm by tube and tissue culture plant methods as described by Mathur et al. 14 and Maldonado et al. 17 Plants extracts Plant extracts (aqueous, alcohol, and acetone) were prepared according to Ahmed et al. 18 and Al-jboriy et al. 19 Then stock solution was prepared for each extract by dissolving 1 g of dry extract with 10 ml of distilled water, so the final concentration of extract would be 0.1 g/ml, from this solution other concentrations were prepared (0.01-0.1) g/ml, which was used to determine the antibacterial activity of peel extracts against S. aureus and E. coli bacteria by agar well diffusion method as mentioned by Egharevba et al. 20 but agar dilution method was used to detect minimum inhibitory concentration (MIC) of the plant extracts according to NCCLS. 21 The extracts were subjected to phytochemical screening according to Ling et al. 22 Effect of pomegranate peel extracts on the bacterial vir- ulence factors MIC of each extract was added to the bacterial suspension, and all tests were made as mentioned in step 2. Combination studies The combined antimicrobial activity of the pomegranate peel extracts and antibiotics were done by evaluating the fractional inhibitory concentrations ( Then the interactions between the antibiotics and the peel extracts were evaluated by using the FIC indices as described by Pankey et al. 24 and Kamatou et al. 25 which were calculated by using the formula: The combinations were classified as synergistic (FIC indices were <1), additive (FIC indices were 1), indifferent (FIC indices were between 1 and 2), and antagonistic (FIC indices were >2 ). Statistical analysis Data analysis of variance was carried out by SAS. LSD was used to compare mean at 0.0001. 26 Frequency of urinary tract pathogens in pregnant women Fifty-two bacterial isolates were isolated in this study, gram-positive bacteria 43(83%) occurred more frequently than gram-negative bacteria 9(18%) where S. aureus 20(39%) and E. coli 6(11%) were the commonest offending isolated as shown in Fig. 1. First, this might be due to environment, the socioeconomic conditions of the pregnant and the reinfection, when infection happened in the first trimester (some time it is possible in the third trimester) of pregnancy which was ensured by the patients' information. One isolate of both S. aureus and E. coli had been chosen to continue and complete other steps of the study. These two isolates were subjected to standard tests for determination of their ability to produce different virulence factors such as hemolysin, protease, -lactamase, adherence, and biofilm formation ability. From the result, it appeared that these two isolates gave positive results for the previous tests. Many studies indicate the relationship between the bacterial virulence factors and their pathogenicity such as Muder et al. 27 who found that the bacteria which had the ability to produce hemolysin and protease enzymes in some way were showed to increase its invasion activity and ability to resist host immune system. While Al-Chalabi 28 reported that several virulence factors such as hemolysin, cytotoxic necrotizing factor, aerobactin, biofilm, and different types of adhesion have been responsible for E. coli pathogenesis, because of the relationship between the bacterial ability to produce virulence factors and their infectivity or pathogenicity. Plant extracts Pomegranate peel extracts screening alkaloid, saponins, flavonoids, tannins, phenolic, glycosides, and resins as a phytochemical. The flavonoids and saponins were absent in aqueous extract, but during ethanol extraction, only saponins were not extracted. While in the acetone extraction this solvent succeeded to extract nearly all the studied active material. The antibacterial activity of plant extracts depends on the extraction conditions such as type and concentration of the solvent, time and temperature for the extraction process, all these factors effect on the type and the amount of the active material that extracted and found large amount of phytochemical material increase antibacterial activity of extract against pathogenic bacteria. 29 The antibacterial activity of pomegranate peel extracts The results showed clearly that pomegranate peel extracts were active against S. aureus and E. coli bacteria in comparison to ciprofloxacin as a positive control and the distilled water as a negative control. The alcohol solvent could be considered as the best one among the three solvents which were used in this study. Acetone follow alcohol and distilled water might be the last good solvent with respect to their activity against the chosen isolates as shown in Tables 1 and 2. The result showed a relationship between the value of inhibition zone diameter for each one of the studied bacteria and type of solvents used in the extraction process. When the three solvents were used Fig. 1 Frequency of urinary tract pathogens in pregnant women. Research Interaction between the extracts of pomegranate peels and antibacterial and antivirulence activities Wafaa Sadeq Al-Wazni et al. at different concentrations against S. aureus bacteria, alcohol solvent gave the widest inhibition zone, when used at 0.01, 0.05, 0.075 and 0.1 g/ml and it was followed by the value of inhibition zone diameter for the acetone extract, the aqueous extract had the lowest effect when used at the concentrations above and when 0.025 g/ml concentration of these three types of extracts were used against S. aureus, the acetone extract was the best one as the highest effect then followed by the alcohol and the aqueous extracts. Among the solvent and according to their effects on E. coli isolate, acetone extract was considered as the best one when it used at 0.01 g/ml and 0.075 g/ml, while the alcohol extract had the highest effect on E. coli bacteria at 0.025 g/ml, 0.05 g/ml, and 0.1 g/ml concentration in contrast with the other extracts. When the pomegranate peel extracts were used as an antibacterial the best solvent chosen as extractor could be the polar solvents especially the ethanol solvent due to the best effect on both selected isolates. The results agree with Rathinamoorthy et al. 30 who attributed the antibacterial activity of pomegranate peel extracts to the presence of the broad spectrum antimicrobial compounds that act against both selected isolates. Antivirulence activity of pomegranate peel extracts The studied bacteria which had the ability to produce a number of virulence factors (hemolysin, protease, -lactamase) were treated with the MIC of each one of the plant extracts (which reached to 0.006 g/ml in aqueous extract, 0.004 in both alcohol and acetone extracts). The results explained that capacity of S. aureus and E. coli bacteria to produce hemolysin toxin and protease enzyme had not been affected and remained without any alteration after incubation period with these extracts compared to control. These bacteria completely lost their ability to produce -lactamase enzymes after their treatment with the MIC of each extract, although these bacteria were active producer for this enzyme before they have been treated with the extracts, as shown in Table 3. Forty cells of S. aureus bacteria adhered on the assayed epithelial cell, while only 20 cells of E. coli adhered to the epithelial cells. These data were regarded as control for detection the effects of the MIC of pomegranate peel extracts on adhesion ability of studied bacteria. As shown in Fig. 2, the number of adhered S. aureus bacterial cells on the epithelial cell was clearly declined when the bacteria was treated with MIC of extracts. The aqueous extract reduced the number of the adherence bacterial to only 10 bacteria/cell, but the number of the adherence cells reached to 3 and 1 bacteria/cell in the presence of the acetone and the alcohol extracts, respectively. The adherence of E. coli cell reached to one bacteria/cell when the acetone extract was added to bacterial suspension, but only three bacterial cells were seen to be attached to Interaction between the extracts of pomegranate peels and antibacterial and antivirulence activities Research Wafaa Sadeq Al-Wazni et al. epithelial cells after the bacterial suspension was incubated with alcohol extract, while only 5 bacteria/cell were attached after treatment with the aqueous extract, in contrast with control (E. coli without the extracts), as shown in Fig. 3. As a comparison, ethanol extract was the best anti-adhesive factor, followed by acetone, while the aqueous extract had the least effect. This may return to the weak ability of distilled water to extract the active materials from plants peel in affected amounts compared to acetone and alcohol solvents. The pomegranate peel extracts have been worked as anti-adhesive, because of the large amounts of the saponins, flavonoids, alkaloids, tannins, phenolic, glycosides, and resins, which were directly responsible for the anti-adhesive activity against the pathogen. 31 The effect of the plant extracts is return to its ability to inhibiting cell attachment; therefore pretreatment of the body surface with plant extracts produced an unfavorable film that prevent and reduce the surface adhesion of pathogenic bacteria. 32 Figure 4 illustrates that S. aureus was a high producer for biofilm formation; this was shown through its optical density that reaches to 1.7 when it was measured for bacterial suspension without any types of the extracts (regarded as control). But, the optical density came to be reduced largely when the MIC of each one of the extracts was added to S. aureus suspension before reading the optical density. The optical density (OD) of S. aureus suspension with the MIC of the aqueous and the acetone extracts almost the same, and this result was different from the results of the other studies which found that the acetone extract had more effect than the aqueous extract. Whereas the alcohol extracts, still the best solvent in its effects on studied bacteria E. coli, was regarded as high producer biofilm because the OD of its suspension without extracts reached to 1.5. But when the suspension of E. coli bacteria was treated with MIC of the aqueous and acetone extracts, the OD of it reduced, which means the biofilm formation activity were declined clearly compared to the control, as shown in Fig. 5. Fig. 2 Effects of extracts on adherence activity of S. aureus bacteria. Fig. 3 Effects of extracts on adherence activity of E. coli bacteria. Fig. 4 Effects of extracts on biofilm formation activity of S. aureus bacteria. Fig. 5 Effects of extracts on biofilm formation activity of E. coli bacteria. Research Interaction between the extracts of pomegranate peels and antibacterial and antivirulence activities Wafaa Sadeq Al-Wazni et al. The biofilm formation activity of bacteria were declined after treatment with extracts but this decline do not transfer bacteria from high producer (the control) to the poor producer (OD lower than 0.1) after treatment with extracts. S. aureus and E. coli bacteria were treated with the aqueous and the acetone extracts remained as a high producer (OD high than 0.5), but when bacteria was treated with alcohol extract it came to be transferred from high producer to producer only (OD between 0.5-0.1). This proved that alcohol solvent represented as the best solvent in extraction and preserves the activity of active compounds in pomegranate peel extracts compared with acetone and aqueous extracts. These results may be due to the formation of variety of biological properties and the activity of the extracts of chemical composition when different solvents were used in preparing these extracts. Many searchers were emphasizing by many trials to find some materials that inhibit the activity of virulence factors of pathogenic bacteria such as chemical material that was extracted from plants. 33 The pomegranate peel extracts contain compound such as tannins that can interact with macromolecules, including carbohydrates and proteins, which made these compounds as promising anti-adhesive and antibiofilm. 34 Interactions between the extracts and antibiotics in vitro The effect of the combination of the peel extracts and the antibiotics on the susceptibility of the S. aureus bacteria shown in Table 4 illustrated that the interaction of the ethanol extracts with the chloramphenicol and ciprofloxacin antibiotics were synergy. But with tetracycline it's been indifferent. While at the combination of the acetone extract with the three types of the antibiotics had been antagonism. The FIC value illustrated that the combination was indifference in the aqueous extracts with the chloramphenicol and ciprofloxacin antibiotics and came to be antagonism with the tetracycline antibiotic. While in the study of E. coli bacteria, susceptibility found that the synergy was present only in the interaction between the tetracycline and the acetone extract and the other results were divided between antagonism and indifference effect, but in the case of ethanol and the chloramphenicol it was additive (the effect which is less than synergistic but not antagonism), as shown in Table 5. The effect of chloramphenicol and ciprofloxacin antibiotics against S. aureus bacteria was marginally improved in the presence of the alcohol extract and the effect of the tetracycline antibiotic against E. coli was improved in the presence of the acetone extract, while any other combination between studied antibiotic and the extracts had not any beneficial effects against studied S. aureus and E. coli bacteria. So the results found that the effect of pomegranate peel extracts alone was well than they interact with antibiotics in most of the results. While other studies found that the efficacy of antimicrobial agents could be improved by combining antibiotics with crude plant extracts against different pathogens Interaction between the extracts of pomegranate peels and antibacterial and antivirulence activities Research Wafaa Sadeq Al-Wazni et al. in vitro and found that it may reduce MICs of antibiotics against resistant organisms. The combination of the plants extracts and the antibiotics could be useful in fight emergency drug resistance pathogens. 35 The antimicrobial compounds extracted from plants have been found to be synergistic enhancers in that though they may not explain any antimicrobial properties alone, but when used with antibiotic they enhance the activity of the drug. The synergistic effect of the association of antibiotic and plant extracts against resistant pathogens leads to new choices for the treatment of infectious diseases. Also synergy between plant product and drug will solve problems of toxicity and overdose since when they combine a little concentration of two agents is required. Therefore, there is an urgent need to find source of natural compound to solve the problem of multiple drug resistance. 36
|
<reponame>gscept/nebula-trifid<filename>code/addons/ui/rocket/rocketinterface.h
#pragma once
//------------------------------------------------------------------------------
/**
@class Rocket::RocketInterface
Implements a Rocket system interface
(C) 2013 <NAME>
*/
//------------------------------------------------------------------------------
#include <Rocket/Core.h>
namespace LibRocket
{
class RocketInterface : public Rocket::Core::SystemInterface
{
public:
/// constructor
RocketInterface();
/// destructor
virtual ~RocketInterface();
/// gets the time elapsed since the start of the application
virtual float GetElapsedTime();
/// activate keyboard
void ActivateKeyboard();
/// deactivate keyboard
void DeactivateKeyboard();
#ifdef NEBULA3_DEBUG
/// logs specific message
bool LogMessage(Rocket::Core::Log::Type type, const Rocket::Core::String& message);
#endif
};
} // namespace Rocket
//------------------------------------------------------------------------------
|
kol_vo=int(input())
was=int(input())
maximum=0
g=0
f=[]
for _ in range(kol_vo):
h=int(input())
if h>maximum:
maximum=h
g+=h
f+=[h]
h=[]
if (was+g)%kol_vo==0:
o=(was+g)//kol_vo
else:
o=(was+g)//kol_vo+1
if max(f)>o:
h.append(max(f))
else:
h.append(o)
h.append(maximum+was)
print(*h)
|
//function if the center 2 is on fire
void center_2_fire()
{
drive(200, r_reg_speed, r_reg_speed);
turn(1000, turn_power, m_port_r);
drive(900, r_reg_speed, r_reg_speed);
turn(400, turn_power, m_port_r);
drive(400, r_reg_speed, r_reg_speed);
servo_change(sweeper_down, sweeper_up, servo_port_sweeper, 30);
reverse_line_follower(5, black_tape);
servo_change(sweeper_up, sweeper_down, servo_port_sweeper, 30);
line_follower(13, black_tape);
servo_change(sweeper_down, sweeper_grab, servo_port_sweeper, 30);
reverse_line_follower(14, black_tape);
msleep(1000);
turn(turn_time-110, turn_power, m_port_l);
msleep(1000);
line_up(500);
msleep(1000);
drive(1500, reg_speed, reg_speed);
servo_change(sweeper_grab, 0, servo_port_sweeper, 30);
servo_change(scooper_up, scooper_down, servo_port_scooper, 30);
line_up(500);
drive(350, r_reg_speed, r_reg_speed);
turn(turn_time+200, turn_power, m_port_r);
line_follower(9, black_tape);
servo_change(0, sweeper_up, servo_port_sweeper, 30);
reverse_line_follower(12, black_tape);
servo_change(sweeper_up, sweeper_down, servo_port_sweeper, 30);
line_follower(10, black_tape);
servo_change(sweeper_down, sweeper_grab, servo_port_sweeper, 30);
reverse_line_follower(32, black_tape);
turn(turn_time, turn_power, m_port_l);
line_up(500);
servo_change(scooper_down, scooper_up, servo_port_scooper, 30);
drive(1500, reg_speed, reg_speed);
servo_change(sweeper_grab, 0, servo_port_sweeper, 30);
servo_change(scooper_up, scooper_down, servo_port_scooper, 30);
line_up(1000);
drive(350, r_reg_speed, r_reg_speed);
turn(turn_time, turn_power, m_port_r);
line_follower(29, black_tape);
servo_change(0, sweeper_up, servo_port_sweeper, 30);
reverse_line_follower(12, black_tape);
servo_change(sweeper_up, sweeper_down, servo_port_sweeper, 30);
line_follower(9, black_tape);
servo_change(sweeper_down, sweeper_up, servo_port_sweeper, 30);
reverse_line_follower(5, black_tape);
reverse_line_follower(43, black_tape);
turn(turn_time, turn_power, m_port_l);
set_servo_position(servo_port_sweeper, sweeper_up);
line_up(500);
set_servo_position(servo_port_sweeper, sweeper_grab-10);
drive(1500, reg_speed, reg_speed);
servo_change(sweeper_grab, sweeper_down, servo_port_sweeper, 30);
servo_change(scooper_up, scooper_down, servo_port_scooper, 30);
line_up(1000);
drive(600, r_reg_speed, r_reg_speed);
}
|
import { BaseObject } from '../_lib_code/objects/baseObject';
import { Exportable } from './exportable.interface';
export class TopFoodSource extends BaseObject implements Exportable {
public static readonly KEYS = {
CONSUMPTION_DATA_ID: 'consumptionDataId',
COMPOSITION_DATA_ID: 'compositionDataId',
MICRONUTRIENT_ID: 'micronutrientId',
DAILY_MN_CONTRIBUTION: 'dailyMnContribution',
FOOD_GROUP_ID: 'foodGroupId',
FOOD_GROUP_NAME: 'foodGroupName',
FOOD_GENUS_ID: 'foodGenusId',
FOOD_GENUS_NAME: 'foodGenusName',
RANKING: 'ranking',
};
public readonly dailyMnContribution: number;
public readonly ranking: number;
public readonly foodGroupName: string;
public readonly foodGenusName: string;
protected constructor(sourceObject?: Record<string, unknown>) {
super(sourceObject);
this.dailyMnContribution = this._getNumber(TopFoodSource.KEYS.DAILY_MN_CONTRIBUTION);
this.ranking = this._getNumber(TopFoodSource.KEYS.RANKING);
this.foodGroupName = this._getString(TopFoodSource.KEYS.FOOD_GROUP_NAME);
this.foodGenusName = this._getString(TopFoodSource.KEYS.FOOD_GENUS_NAME);
}
public getExportObject(): Record<string, unknown> {
const exportObject = JSON.parse(JSON.stringify(this)) as Record<string, unknown>;
// eslint-disable-next-line @typescript-eslint/dot-notation, @typescript-eslint/no-unsafe-member-access
delete exportObject['_sourceObject'];
return exportObject;
}
public getExportFileName(): string {
return 'Top20FoodItemsData';
}
}
|
<reponame>erlendvollset/Expression
# Attribution to original authors of this code
# --------------------------------------------
# This code has been originally been ported from the Fable project which
# was originally ported from the FSharp project.
#
# Fable:
# https://fable.io
# - Copyright (c) <NAME> and contributors.
# - MIT License
# - https://github.com/fable-compiler/Fable/blob/nagareyama/src/fable-library/Map.fs
#
# F#
# - https://github.com/dotnet/fsharp
# - Copyright (c) Microsoft Corporation. All Rights Reserved.
# - MIT License
# - https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/map.fs
from typing import Any, Callable, Iterable, Iterator, List, Mapping, Optional, Set, Tuple, TypeVar, cast, overload
from expression.core import Option, SupportsLessThan, pipe
from . import maptree, seq
from .frozenlist import FrozenList
from .maptree import MapTree
Key = TypeVar("Key", bound=SupportsLessThan)
Value = TypeVar("Value")
Result = TypeVar("Result")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")
T4 = TypeVar("T4")
T5 = TypeVar("T5")
T6 = TypeVar("T6")
class Map(Mapping[Key, Value]):
"""The immutable map class."""
def __init__(self, __tree: Optional[MapTree[Key, Value]] = None) -> None:
self._tree: MapTree[Key, Value] = __tree if __tree else maptree.empty
def add(self, key: Key, value: Value) -> "Map[Key, Value]":
return Map(maptree.add(key, value, self._tree))
@overload
def pipe(self, __fn1: Callable[["Map[Key, Value]"], Result]) -> Result:
...
@overload
def pipe(self, __fn1: Callable[["Map[Key, Value]"], T1], __fn2: Callable[[T1], T2]) -> T2:
...
@overload
def pipe(
self, __fn1: Callable[["Map[Key, Value]"], T1], __fn2: Callable[[T1], T2], __fn3: Callable[[T2], T3]
) -> T3:
...
@overload
def pipe(
self,
__fn1: Callable[["Map[Key, Value]"], T1],
__fn2: Callable[[T1], T2],
__fn3: Callable[[T2], T3],
__fn4: Callable[[T3], T4],
) -> T4:
...
@overload
def pipe(
self,
__fn1: Callable[["Map[Key, Value]"], T1],
__fn2: Callable[[T1], T2],
__fn3: Callable[[T2], T3],
__fn4: Callable[[T3], T4],
__fn5: Callable[[T4], T5],
) -> T5:
...
@overload
def pipe(
self,
__fn1: Callable[["Map[Key, Value]"], T1],
__fn2: Callable[[T1], T2],
__fn3: Callable[[T2], T3],
__fn4: Callable[[T3], T4],
__fn5: Callable[[T4], T5],
__fn6: Callable[[T5], T6],
) -> T6:
...
def pipe(self, *args: Any) -> Any:
"""Pipe map through the given functions."""
return pipe(self, *args)
@staticmethod
def create(ie: Iterable[Tuple[Key, Value]]) -> "Map[Key, Value]":
return create(ie)
def contains_key(self, key: Key) -> bool:
return maptree.mem(key, self._tree)
def change(self, key: Key, f: Callable[[Option[Value]], Option[Value]]) -> "Map[Key, Value]":
return Map(maptree.change(key, f, self._tree))
@staticmethod
def empty() -> "Map[Key, Value]":
return Map(maptree.empty)
def is_empty(self) -> bool:
return maptree.is_empty(self._tree)
def exists(self, predicate: Callable[[Key, Value], bool]) -> bool:
return maptree.exists(predicate, self._tree)
def filter(self, predicate: Callable[[Key, Value], bool]) -> "Map[Key, Value]":
return Map(maptree.filter(predicate, self._tree))
def for_all(self, predicate: Callable[[Key, Value], bool]) -> bool:
"""Returns true if the given predicate returns true for all of
the bindings in the map.
Args:
predicate: The function to test the input elements.
Returns:
True if the predicate evaluates to true for all of the
bindings in the map.
"""
return maptree.forall(predicate, self._tree)
def iterate(self, f: Callable[[Key, Value], None]) -> None:
return maptree.iter(f, self._tree)
# def MapRange (f:'Value->'Result) =
# return Map<'Key, 'Result>(comparer, maptree.map f tree)
def fold(self, folder: Callable[[Result, Tuple[Key, Value]], Result], state: Result) -> Result:
return maptree.fold(folder, state, self._tree)
def fold_back(self, folder: Callable[[Tuple[Key, Value], Result], Result], state: Result) -> Result:
return maptree.fold_back(folder, self._tree, state)
def map(self, mapping: Callable[[Key, Value], Result]) -> "Map[Key, Result]":
"""Builds a new collection whose elements are the results of
applying the given function to each of the elements of the
collection. The key passed to the function indicates the key of
element being transformed.
Args:
mapping: The function to transform the key/value pairs
Returns:
The resulting map of keys and transformed values.
"""
return Map(maptree.map(mapping, self._tree))
def partition(self, predicate: Callable[[Key, Value], bool]) -> "Tuple[Map[Key, Value], Map[Key, Value]]":
r1, r2 = maptree.partition(predicate, self._tree)
return Map(r1), Map(r2)
# @overload
# def get(self, key: Key) -> Optional[Value]:
# ...
# @overload
# def get(self, key: Key, default: Value) -> Value:
# ...
# def get(self, key: Key, default: Union[Value, _T]) -> Union[Value, _T]:
# for value in self.try_find(key):
# return value
# return default
def items(self) -> Set[Tuple[Key, Value]]:
return set(maptree.to_seq(self._tree))
def remove(self, key: Key) -> "Map[Key, Value]":
return Map(maptree.remove(key, self._tree))
def to_list(self) -> FrozenList[Tuple[Key, Value]]:
return maptree.to_list(self._tree)
def to_seq(self) -> Iterable[Tuple[Key, Value]]:
"""Convert to sequence.
Returns:
Sequence of key, value tuples.
"""
return maptree.to_seq(self._tree)
def try_get_value(self, key: Key, value: List[Value]):
for v in maptree.try_find(key, self._tree).to_list():
value.append(v)
return True
else:
return False
def try_find(self, key: Key) -> Option[Value]:
return maptree.try_find(key, self._tree)
def try_pick(self, chooser: Callable[[Key, Value], Option[Result]]) -> Option[Result]:
return maptree.try_pick(chooser, self._tree)
@staticmethod
def of(**args: Value) -> "Map[str, Value]":
return Map(maptree.of_seq(args.items()))
@staticmethod
def of_frozenlist(lst: FrozenList[Tuple[Key, Value]]) -> "Map[Key, Value]":
"""Generate map from list.
Returns:
The new map.
"""
return of_frozenlist((lst))
@staticmethod
def of_list(lst: List[Tuple[Key, Value]]) -> "Map[Key, Value]":
"""Generate map from list.
Returns:
The new map.
"""
return of_list((lst))
@staticmethod
def of_seq(sequence: Iterable[Tuple[Key, Value]]) -> "Map[Key, Value]":
"""Generate map from sequence.
Generates a new map from an iterable of key/value tuples. This
is an alias for `Map.create`.
Returns:
The new map.
"""
return of_seq(sequence)
def __hash__(self) -> int:
def combine_hash(x: int, y: int) -> int:
return (x << 1) + y + 631
res = 0
for x, y in maptree.mk_iterator(self._tree):
res = combine_hash(res, hash(x))
res = combine_hash(res, hash(y))
return res
def __getitem__(self, key: Key) -> Value:
return maptree.find(key, self._tree)
def __iter__(self) -> Iterator[Key]:
xs = maptree.mk_iterator(self._tree)
return (k for (k, _) in xs)
def __len__(self) -> int:
"""Return the number of bindings in the map."""
return maptree.size(self._tree)
def __contains__(self, key: Any) -> bool:
return self.contains_key(key)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Map):
return False
other = cast(Map[Any, Any], other)
iterator: Iterator[Tuple[Any, Any]] = iter(other.to_seq())
for kv in self.to_seq():
try:
kv_other = next(iterator)
except StopIteration:
return False
else:
if kv != kv_other:
return False
return True
def __bool__(self) -> bool:
return not maptree.is_empty(self._tree)
def __str__(self) -> str:
def to_str(item: Tuple[Key, Value]) -> str:
key, value = item
if isinstance(key, str):
return f'("{key}", {value})'
return f"({key}, {value})"
items = pipe(self.to_seq(), seq.map(to_str))
return f"map [{'; '.join(items)}]"
def __repr__(self) -> str:
return str(self)
def add(key: Key, value: Value) -> Callable[[Map[Key, Value]], Map[Key, Value]]:
"""Add key with value to map.
Returns a new map with the binding added to the given map. If a
binding with the given key already exists in the input map, the
existing binding is replaced by the new binding in the result
map.
Args:
key: The input key.
value: The input value.
Returns:
A partially applied add function that takes the input map and returns
the output map.
"""
def _add(table: Map[Key, Value]) -> Map[Key, Value]:
"""Add the partially applied key with value to map.
Returns a new map with the binding added to the given map. If a
binding with the given key already exists in the input map, the
existing binding is replaced by the new binding in the result
map.
Args:
table: The input table.
Returns:
The resulting map.
"""
return table.add(key, value)
return _add
def change(key: Key, fn: Callable[[Option[Value]], Option[Value]]) -> Callable[[Map[Key, Value]], Map[Key, Value]]:
"""Returns a new map with the value stored under key changed
according to f.
Args:
key: The input key.
fn: The change function.
table: The input table.
Returns:
The input key.
"""
def _change(table: Map[Key, Value]) -> Map[Key, Value]:
return table.change(key, fn)
return _change
def contains_key(key: Key) -> Callable[[Map[Key, Value]], bool]:
def _contains_key(table: Map[Key, Value]) -> bool:
return table.contains_key(key)
return _contains_key
def count(table: Map[Key, Value]) -> int:
"""Return the number of bindings in the map."""
return len(table)
def create(ie: Iterable[Tuple[Key, Value]]) -> "Map[Key, Value]":
return Map(maptree.of_seq(ie))
def find(key: Key) -> Callable[[Map[Key, Value]], Value]:
"""Lookup an element in the map, raising KeyNotFoundException if no
binding exists in the map
Args:
key: The key to find.
table: The map to find the key in.
"""
def _find(table: Map[Key, Value]) -> Value:
return table[key]
return _find
def is_empty(table: Map[Key, Value]) -> bool:
"""Is the map empty?
Args:
table: The input map.
Returns:
True if the map is empty.
"""
return table.is_empty()
def iterate(action: Callable[[Key, Value], None]) -> Callable[[Map[Key, Value]], None]:
def _iterate(table: Map[Key, Value]) -> None:
return table.iterate(action)
return _iterate
def try_pick(chooser: Callable[[Key, Value], Option[Result]]) -> Callable[[Map[Key, Value]], Option[Result]]:
"""Searches the map looking for the first element where the given
function returns a Some value.
Args:
chooser: The function to generate options from the key/value
pairs.
Returns:
Partially applied `try_pick` function that takes the input map
and returns the first result.
"""
def _try_pick(table: Map[Key, Value]) -> Option[Result]:
return table.try_pick(chooser)
return _try_pick
def pick(chooser: Callable[[Key, Value], Option[Result]]) -> Callable[[Map[Key, Value]], Result]:
def _try_pick(table: Map[Key, Value]) -> Result:
for res in table.try_pick(chooser):
return res
else:
raise KeyError()
return _try_pick
def exists(predicate: Callable[[Key, Value], bool]) -> Callable[[Map[Key, Value]], bool]:
"""Returns true if the given predicate returns true for one of the bindings in the map.
Args:
predicate: The function to test the input elements.
Returns:
Partially applied function that takes a map table and returns
true if the predicate returns true for one of the key/value
pairs.
"""
def _exists(table: Map[Key, Value]) -> bool:
return table.exists(predicate)
return _exists
def filter(predicate: Callable[[Key, Value], bool]) -> Callable[[Map[Key, Value]], Map[Key, Value]]:
def _filter(table: Map[Key, Value]) -> Map[Key, Value]:
return table.filter(predicate)
return _filter
def for_all(predicate: Callable[[Key, Value], bool]) -> Callable[[Map[Key, Value]], bool]:
def _for_all(table: Map[Key, Value]) -> bool:
return table.for_all(predicate)
return _for_all
def map(mapping: Callable[[Key, Value], Result]) -> Callable[[Map[Key, Value]], Map[Key, Result]]:
def _map(table: Map[Key, Value]) -> Map[Key, Result]:
return table.map(mapping)
return _map
def fold(folder: Callable[[Result, Tuple[Key, Value]], Result], state: Result) -> Callable[[Map[Key, Value]], Result]:
def _fold(table: Map[Key, Value]) -> Result:
return table.fold(folder, state)
return _fold
def fold_back(
folder: Callable[[Tuple[Key, Value], Result], Result], table: Map[Key, Value]
) -> Callable[[Result], Result]:
def _fold_back(state: Result) -> Result:
return table.fold_back(folder, state)
return _fold_back
def partition(
predicate: Callable[[Key, Value], bool]
) -> Callable[[Map[Key, Value]], Tuple[Map[Key, Value], Map[Key, Value]]]:
def _partition(table: Map[Key, Value]) -> Tuple[Map[Key, Value], Map[Key, Value]]:
return table.partition(predicate)
return _partition
def remove(key: Key) -> Callable[[Map[Key, Value]], Map[Key, Value]]:
"""Removes an element from the domain of the map. No exception is
raised if the element is not present.
Args:
key: The key to remove.
table: The table to remove the key from.
Returns:
The resulting map.
"""
def _remove(table: Map[Key, Value]) -> Map[Key, Value]:
return table.remove(key)
return _remove
# // [<CompiledName("FindKey")>]
# let findKey predicate (table : Map<_, _>) =
# table |> Seq.pick (fun kvp -> let k = kvp.Key in if predicate k kvp.Value then Some k else None)
# // [<CompiledName("TryFindKey")>]
# let tryFindKey predicate (table : Map<_, _>) =
# table |> Seq.tryPick (fun kvp -> let k = kvp.Key in if predicate k kvp.Value then Some k else None)
def of(**args: Value) -> Map[str, Value]:
"""Create map from arguments."""
return Map(maptree.of_seq(args.items()))
def of_frozenlist(elements: FrozenList[Tuple[Key, Value]]) -> Map[Key, Value]:
return Map(maptree.of_list(elements))
def of_list(elements: List[Tuple[Key, Value]]) -> Map[Key, Value]:
return Map(maptree.of_list(FrozenList(elements)))
def of_seq(elements: Iterable[Tuple[Key, Value]]) -> Map[Key, Value]:
return Map(maptree.of_seq(elements))
def to_list(table: Map[Key, Value]) -> FrozenList[Tuple[Key, Value]]:
return table.to_list()
def to_seq(table: Map[Key, Value]) -> Iterable[Tuple[Key, Value]]:
return table.to_seq()
def try_find(key: Key) -> Callable[[Map[Key, Value]], Option[Value]]:
"""Lookup an element in the map, returning a `Some` value if the
element is in the domain of the map and `Nothing` if not.
Args:
key: The input key.
Returns:
A partially applied `try_find` function that takes a map
instance and returns the result.
"""
def _try_find(table: Map[Key, Value]):
"""Lookup an element in the map, returning a `Some` value if the
element is in the domain of the map and `Nothing` if not.
Args:
key: The input key.
Returns:
The found `Some` value or `Nothing`.
"""
return table.try_find(key)
return _try_find
empty: Map[Any, Any] = Map.empty()
__all__ = [
"Map",
"add",
"change",
"create",
"contains_key",
"count",
"empty",
"exists",
"filter",
"find",
"fold",
"for_all",
"is_empty",
"iterate",
"map",
"of",
"of_frozenlist",
"of_list",
"of_seq",
"partition",
"pick",
"remove",
"to_list",
"to_seq",
"try_find",
"try_pick",
]
|
Knowledge of strategic value discipline and its importance for fresh graduate: A qualitative investigation. Strategy formulation is an old practice that cuts through business and politics. With the concept of strategy being around since advent of the human species, it has gradually evolved to become an important aspect in all aspects of life. This paper aims to evaluate strategy as a management discipline and its impact on job-seeking graduates in building a career. In doing so, a qualitative research approach will be employed to analyse a variety of concepts in strategic management. The historical perspective of strategy formulation, as well as the importance of strategy in the modern-day business context will be discussed. Moreover, the emergence of strategy, strategic management and planning in the business perspectives will be analysed. Ultimately, this paper aims to demonstrate the importance of strategic management as a skill that would guide job-seeking graduates to work in organizations best suited for them. Introduction to Strategic Management 1.1 Origins of Strategic Management The concept of strategic management is as old as human civilisation itself. The first occurrence of strategy can be traced back to our foraging forefathers who incorporated the concept in their daily affairs. Pederzini states that the homo sapiens acquisition of territories for settlement is attributed to calculated strategies in hunting and gathering. Our foraging forefather's ability to terminate rival human species is a result of the strategic management of hunting and gathering bands. In fact, strategy is not only regarded as a business or existential concept, but also a communicative practice. Consequently, the concept found its way into modern Greek societies where businessmen laid out ideas to accentuate business practices. In academia, strategic management is only a fledgling field, where it only fully materialised in the 1960s. It was first introduced as a field of study in Strategy and Structure: Chapters in the History of American Industrial Enterprise by A. Chandler in 1962. Just 3 years later in 1965, H.I. Ansoff released Corporate Strategy: An Analytic Approach to Business Policy for Growth and Expansion where he delved more specifically into the concept of business strategy. Also, in The Concept of Corporate Strategy in 1971, K. Andrews discussed companies' patterns of decisions and how these shaped the policies and plans for the companies' future. After the release of these works, the discipline of strategic management grew to become a more developed and nuanced field in management (Guerras-Martn et.al, 2014). With Michael Porter's publishing of Competitive Strategy: Techniques for Analyzing Industries and Competitors in 1980, the academic field of strategic management was further solidified with his revolutionary concepts of the five forces analysis and generic strategies which still prove relevant till today. His concepts will be delved on more specifically in later sections of the paper. Importance of Strategy in the Modern Business Context The application of strategy in the modern business context provides a plethora of ideas that promotes corporate sustainability and financial success. According to Genc, business managers develop strategic ideas for planning. This is so as the process of developing management ideas helps business gain financial success and improve human resource engagement. Furthermore, creating a strategy helps in forming ideas that create long term and short-term goals in a business. With strategic management, the holistic use of limited resources in propelling success within an organisation is emphasized on. Strategic management also calls for a strength-weakness evaluation. According to Wieland e al., business managers and entrepreneurs have a thorough knowledge of business practices. In that regard, an analysis of organisational strengths and weaknesses provide an avenue to manage competitive forces in the external and internal environments. In the case of young graduate professionals, understanding traditional strategic management values is important when entering the workforce. With the fast development of education systems all over the world, millions of graduates are churned out every year, making the competition extremely high for these job seekers. According to Nnaji & Ahmed, graduates acquainted with strategic concepts, such as planning, are better fitted to work in organisations that aim for profit development. These graduates are able to develop fiscal plans, set busines objectives, and creates both short term and long plans which are very valuable in business development. In fact, employers have expressed that these skills take precedence over industrial experience. Of course, it is understood that corporate organisations demand a certain level of job experience, which is why many young professionals begin their career through internship opportunities. However, with knowledge in strategic management, these graduates are able to bridge the gap between experience and industrial practice. Strategic management tenets, such as being forward thinking in goal setting, provides an avenue where individual skills are harnessed alongside the achievement of corporate success. Therefore, this demonstrates how strategic management as a field is not only important for businesses, but also for individuals looking to enter the workforce. Methodology In order to analyse the concept of strategic management, it is first important to establish the definition for which the methodology will aim at exploring. According to Jeffrey Bracker, strategic management is defined as 'the analysis of internal and external environments of a firm, to maximise the utilization of resources in relation to objectives'. Strategic management encompasses the aspects of creating objectives, evaluating the business environment, evaluating the internal environment of the company and the company's strategies. Based on this definition, the paper will analyse strategic management based on qualitative research methodologies. In the process of conducting qualitative research methodologies, existing literature will be heavily drawn upon, more specifically peer reviewed articles in reputable business and academic journals. In analysing the observations presented by scholars, inductive reasoning will be drawn upon to identify the patterns among the examples and create viable conclusions (Onwuegbuzie & Leech, 2005). The approach of inductive reasoning would allow a more flexible analysis of existing scholarship to derive a conclusion that adheres closely to supported and proven studies. This would allow for the paper to come up with more reliable conclusions that investigates the concept of strategic management and its benefits for job-seeking graduates. Literature Review 2.1 Strategic management theories According to Marshall & Richards, Harry Algor Ansoff, a Russian mathematician and businessman, was perhaps the first person in the modern business era to realise the market mixstriking a balance between markets, competition, and financial growth. Ansoff analysed the shifts in market structures and posited three comprehensive answers to this dynamic market shift. Firstly, Ansoff highlighted the change in market dynamics as being consistent with organisational change. Furthermore, he asserted that the incorporation of technology within management principles was important, and that business decisions should not only solve specific market problems but also anticipate unprecedented market shifts. These dynamic changes indeed demanded strategic decision-making processes which could propel organisations during difficult economic periods. Although Ansoff realised the necessary engagement of strategic management principles, he was not considered as the first scholar to write about strategic management as a discipline. Von Neuman and Morgenstern were posited as the first scholars who drew a relationship between business practices and strategic management. The scholars presented the theory of games which provides a locus on cooperation and non-cooperation between business partners. According to Boone & Piliouras, Von Neuman understood the matching desire of corporate organisations forming business coalitions which aimed at achieving market survival in hostile economic and market environments. In addition, Von Neuman introduced the aspect of symmetric versus asymmetric relationships in corporate management. This concept describes that without any compromise to management strategies, any change in player composition can be described as symmetric. On the other hand, when players espouse similar strategies, a business relationship can be described as asymmetric. Since these emergent theories in strategic management, many scholars have begun to build on the concepts and theories to create new frameworks expanding the discipline. For instance, in 1967, Muller provided an operationalisation framework which composed of a regression model to understand the allocation, of funds in an organisation. Subsequently, in 1968, the Boston Consulting group provided a new impetus developing on the earlier works of Muller by devising a cost to volume relationship based on the quantity of goods produced by a firm. They developed a strategic comparison among costs, volume, and profitability in firms. Furthermore, according to Vasilev et al., Kirchhoff analysed the changes in the business environment in 1975. The scholar understood that emerging market players reduced market shares for existing corporations. As such, issues such as profit margins and sustainable operations began to take centre stage in corporate conversations. Market players understood that a product's life span provided insight on shifting consumer demands. Schendel Paton and Rigs expounded on the level 2 regression model that was created by Muller into a three-tier regression model. Schendel and team understood that goal attainment was becoming a problem not only for big multinational corporations but also for new market entrants. Furthermore, the scope for strategic management has also changed over time. Oligarchic organisations enjoyed huge market shares because they dominated almost all of the factors of production, resulting in limited entry enthusiasm for new market players. In discussing strategic management theories, Michael E. Porter is a significant figure whose concepts have had far reaching impacts on businesses. As a distinguished thinker in business strategy, he introduced Porter's five competitive forces which has become integral in business strategic management today. Porter's five competitive forces outlines five causal factors which are responsible in determining the competitiveness of the industry. These five forces are: the bargaining power of consumers, the bargaining power of suppliers, barriers to entry, rivalry in the industry, as well as the threat of substitute products and services. Apart from his famous five forces analysis, Porter also introduced the generic strategies that highlight the strategies that allow companies to pursue competitive advantages in a market. With respect to Porter's generic strategies, he highlights the four major strategic value disciplinesdisruptive innovation, product leadership, customer intimacy and operational excellence. Disruptive innovation is defined as innovations that disrupt the existing market and value networks while product leadership entails the branding and innovation of products which are acceptable by consumers. Customer intimacy on the other hand refers to the connection between an organisation and its markets. Finally, operational excellence is defined as operations that create value both to stakeholders and the customers. Gamble et al. highlighted the success that corporate competencies experienced in adopting the four main strategies. Scholars have argued that successful firms often possess robust strategic decision-making principles which increase product value and customer intimacy even while operating in a competitive business environment. Furthermore, scholars have emphasised on the creation of policies and strategies which do not contradict the strategic value tenets. Hence, in achieving excellence, companies should continuously conduct product evaluations. This should be done through creating adjustments in advertising and branding to increase customer intimacy and operational excellence. Apart from the importance of the Porter's four generic strategies, achieving corporate sustainability has increasingly become an important goal. This is so as organization culture often serves as an impediment to the development of the business. Corporate sustainability can be described as the culmination of an organization's strategies, decision making, culture and operation structure as a result of economic, social, and environmental factors. Sullivan et al. for corporate businesses to define business values through the examination of the industrial ecology. This strategy not only helps promote the sustainable development of the organisation, but also improves key management practices. Furthermore, research conducted has demonstrated how an organization's culture was a primary reason for the failure of the implementation of organizational reform programs, in spite of the presence of adequate tools and techniques required. Furthermore, organizations with a strong singular culture has been proven to have higher chances of being dysfunctional (Linnenluecke & Griffiths, 2010). This concept that was further asserted by Intezari et al.. Referred to as Knowledge Management Culture, Interzari et al. asserted that organisational culture has a significant influence on the ability of the business in managing and utilising its knowledge sources for business strategies. Organisational culture in strategy formulation comprises of four valuescultivation, competence, cooperation and control. Cultivation refers to the emotional connection between employees and an organisation which is usually formed through the feelings of appreciation and care from either party. On the other hand, competence refers to the quality of input and productivity among employees. Cooperation is defined as the joint effort between employees in achieving the goals and objectives of an organisation. Finally, control refers to the efforts of the management in setting operational standards, values. and norms in a company. Therefore, it is clear that strategic management and the company's culture are closely intertwined. Culture, as part of organisational behaviour, influences business leaders in the formulation of strategy. Scholars have emphasized on the importance of the adoption of progressive cultures in an organisation to facilitate the development of viable strategies. Competency, as a value of culture, is described through cooperation between employees in achieving both the mission and vision of an organisation. Kumar et al. documented the importance of assessing stakeholder culture within an organisation. Stakeholder culture has been established to be different across various firms, even if they are massively intertwined with organisational culture. Furthermore, global cultural differences and institutions have an impact on the formulation of strategy and stakeholder culture. Therefore, it is clear that with the many aspects encapsulated by strategic management, several theories have been developed by scholars throughout the years. Even with the diverse theories on strategic management, all theories point to the importance of focusing on certain aspects in business strategy formulation, depending on the company's goals and mission. Real world examples of strategic management Companies have evolved over the years with different operating frameworks that challenged existing market theories. In fact, disruptive innovations in markets have been a significant contributing factor to the progress of strategic management. Disruptive innovation describes the process of small companies that successfully establish themselves in industries saturated by huge multinational corporations with seismic market shares. There have been a number of companies which have not only transformed the market composition in business enterprise, but also grown into multibillion dollar investments. The first example of such a company is Wikipedia. Before the Internet, academic research was primarily reliant on publishing houses and corporations which published encyclopaedias. At the time, encyclopaedias were the repository for all forms of knowledge. In addition, encyclopaedias were written by professionals and scholars who were contracted by publishers. However, disruptive innovation has since shifted the market composition. With the creation of Wikipedia in 2001, encyclopaedias became a thing of the past. Unlike Other reputable companies that have found success from disruptive innovation include Microsoft and Apple. Initially, computer manufacturing was dominated by Dell and IBM. However, Dell and IBM poured investments into mainframe computers without envisioning a threat from micro and personal computers. However, Microsoft and Apple introduced personal computers near the end of the 20 th century, gaining significant popularity which continues to grow till today. The popularity of personal computers or laptops has transformed Microsoft and Apple into multibillion dollar industries with further opportunities to diversify their product portfolio. In addition, the transport industry also experienced disruptive innovation. The Duryea Motor Wagon Company introduced automobiles which challenged railroads as the primary mode of transport. In fact, in the early 20 th century, trains were the fastest mode of transport, resulting in heavy investments by businesses in rail transport. However, the introduction of automobiles opened up new possibilities in transport that could not be realised with trains. Unlike rail transport, automobiles provided access even to the most remote areas in the industrialised nations thus quickly overtaking rail transport. Therefore, it is evident that disruptive innovation in various industries were key in igniting change in the way businesses operate. As such, businesses found that strategic management was extremely important to keep up with the fast-changing innovations that are introduced to the market often. Relationship between strategy and culture in the organizational context As briefly discussed in the previous section, Rahimi contended that strategy and organisational culture are closely related in management. Organisational culture has an influence on the strategy development process and the implementation of strategies. Consequently, implemented strategies also have the potential to change organisational culture and behaviour. In a research conducted by Janiijevi, it was postulated that organisational culture directly impacts the decisions made by business leaders whilst formulating strategies. In addition, culture affects the information gathering process and how management officials perceive both the internal and external business environments. This is evident from the layers of culture presented by Tenji & Foley in Figure 1, which demonstrates how patterns of behaviour encapsulated by culture can affect the decision-making process in strategic management. Therefore, culture provides the benchmark for the adoption of strategies by the management or business (Tenji & Foley, 2017). It is evident that culture has the ability to legitimize strategy. Hence, in cases where culture supports strategy, the process of strategy adoption can be smoothly facilitated. Since organisational culture has a strong influence on decision-making, in areas where culture does not support strategy, then adoption of strategy becomes a difficult process. Therefore, in addressing this obstacle, scholars have provided two methods to ensure that strategic management can proceed smoothly despite clashes with culture. Firstly, the management must understand company values and traditions before engaging in strategy formulation. In order to understand cultural values, Groysberg et al. states that management must conduct company profile audits to understand both stakeholder preference and organisation goals. Secondly, it is important for the management to exhibit good will and compliance to strategy. Therefore, some form of compromise must be made to ensure that strategies are formulated in unison with organisational culture. Furthermore, Scheepers & Reddy has introduced a new dimension in the concept of strategic management. The scholars analysed the dimensions between organisational culture and strategy. They posited that cultural dimensions within an organisation must be positive in order to increase the efficacy of developed strategies. Also, it was determined that achievement orientation is the most important in strategy formulation (). Achievement oriented strategies are formed with the overarching desire to gain results. Furthermore, when faced with business crises, strategies must be created in tandem with organisational cultures that reflect the desire for achievement and value creation to be successful. However, it appears that organisational culture has faced issues as a result of existing cultural gaps. Scholars argue that the cultural void can only be filled by adopting newer cultures, which will then incite organisational change. Furthermore, it is important that the organisational change is conducted seamlessly to avoid disruptions in organisational composition and business operations. Reddy determined that organisational culture is a management concept that is unlikely to change. However, strategies which respect organisational culture should be focused on instead. In addition, Reddy highlighted the growing relevance of strategy execution in businesses since the 1970s. In that regard, the execution of strategies is impactful to the existence of a business entity. Therefore, this proves how organisational culture should be a priority when developing strategies. In addition, the management should develop organisational culture frameworks that are responsive to strategies. Only when strategic management is consistent with organisational culture, will businesses be able to achieve its objectives and goals most effectively. Strategic Management and Graduate Job Seekers 3.1 Challenges faced by graduate job seekers In discussing strategic management, it is clear this field is important not only to business development, but also to job-seekers since having relevant knowledge in strategic management would serve to be a great competitive advantage. Unfortunately, when identifying the challenges faced by fresh graduates in job seeking, the lack of employment opportunities proves to be a common issue. Umezulike stated that the shrinking job market, as a result of tough economic times, has resulted in increased unemployment rates across the United States. Although governments are actively mitigating this problem by creating employment opportunities, the problem persists due to less conventional skills that graduates have. For instance, it has been found that more job seekers are seeking odd jobs rather than jobs requiring specialised skills. In addition, the lack of industrial experience is another problem which graduates grapple with. It is important to note that corporate organisations work in watertight situations and profit cost margins. Therefore, this further highlights the importance of fresh graduates acquiring essential knowledge in strategic management to improve their chances of attaining a job as they would be able to contribute to the company's development. This point is further emphasized by how interpersonal skills, especially organisational skills, among graduates have a great impact on job suitability and career gratification. Pang et al. highlighted the importance of ensuring that school curriculums are aligned with industrial expectations, through working with employer organisations. This comes after the realisation of the lack of technical competencies by job seekers. Baird & Parayitam have contended that the skill of solving organisational problems is extremely vital for graduates. Therefore, strategic partnerships between industries and students are a means for young graduates to equip themselves with technical experience and workplace understanding. Impact of Strategic Vision Development on Graduate Job Seekers Within the realm of strategic management, the concept of Strategic Vision Development proves to be crucial as an important aspect of organisational strategies. Strategic Vision Development refers to activities that evaluate opportunities for both market expansion and business success. With the world being in the midst of the fourth industrial revolution (4IR), also known as the digital era, technology has become an essential tool in strategic management. As a result, the demand for data by big firms both as marketing tools and business assets has grown. Saaid further emphasized on how this increased interest in big data by companies have led to compromises on data security on the internet. He argued that the nature of the internet as a free environment that is unregulated, makes it a target for computer hackers and other malicious individuals. Furthermore, this issue is compounded by how big corporations pay data mining companies to harvest user data on social media platforms and community blogs to market their client's products and services. As a result, digital documents such as images and videos are vulnerable to hacking activities and duplication. Penprase has also evaluated the 4IR and how higher education should be restructured to increase the job competitiveness of graduates. The 4IR has been identified to be an amalgamation of different practices in the development of technology to bring out new realities, such as artificial intelligence and different payment mechanisms like cryptocurrencies. In addition, Penprase highlighted the need to redefine science-based curriculums in institutions of higher learning to fit the rapid developments in the 4IR. Therefore, it is evident that technological and scientific courses in higher education are extremely important to ensure that graduates are able to keep up with the skills required in the current business climate. From a business perspective, sustainable practices are an integral aspect of strategic management in the 4IR. Operational sustainability and businesses' commitments towards climate change and green energy are integral in the 4IR (Oke & Fernandez, 2020). According to Madsen & Ulhoi, Strategic Vision Development is an inherent aspect within the frameworks of the 4IR. Businesses must be flexible in adopting disruptive changes. Through organisational learning, it is important that businesses managers develop strategic visions that will propel corporate organisations towards a new future. Businesses also need to conform to best industrial practices both in operations and human resource. It is no surprise that competition remains the most significant threat businesses face. Therefore, dealing with a competitive business environment requires the adoption of strategies that include the diversification of products and strategic marketing goals. Importance of job-seeking graduates entering suitable organizations Despite arguing for the importance of job-seeking graduates acquiring essential skills and knowledge in strategic management to attain jobs, one might question why graduates going through such training is necessary at all. It is unfortunate that millions of graduates in the labour market grapple with job satisfaction. In fact, the job-seeking decisions of many graduates are fuelled by pay instead of skill relevance. However, a well-paying job does not necessarily translate to better job satisfaction if the working environment is unsuitable. Targeting the right job firstly requires choosing the right career (). In the most ideal situation, students should choose a career that reflects their passion in order to attain personal fulfilment. When a student enters the right job, they are emotionally motivated and empowered. This is very important as it helps maintain the employee's psychological health, which has become an increasing issue. Statistics posits that 79% of employees battle employment stress because of job insecurities or hostile work environments. Additionally, 45% of employees have considered quitting their current jobs to venture into alternative careers due to work stress (Bell & Blanchflower, 2020). In the US, while 34% of employees have expressed satisfaction with their employment opportunities, close to 66% of employees are dissatisfied with their current jobs. In fact, employees who formed careers based on their passion have the ability to become some of the world's most paid professionals. For instance, Satya Nadella, Microsoft's current CEO, has been passionate about cloud computing and cyber networks. His passion translated into commitment and great work attitude which helped to propel him to become the CEO of Microsoft. Therefore, it is clear that choosing the right career for graduates would increase their ability progress further in their career. Part of the strategies to choosing the right career requires the alignment of skills with the organization's goals. This makes it important for graduates to be equipped with important knowledge in strategic management that will give them the competitive advantage that will allow them to choose a job most suitable for them. Conclusion and Recommendations The concept of strategic management, contrary to popular belief, is a relatively new concept and discipline, where it only fully materialised in the late 20 th century. However, with the rise of businesses and innovations, the concept became more of a subject of interest among scholars in recent years. In the contemporary society, major contributions to the development of strategic management can be attributed to disruptive innovations, which revolutionised much of the industries. Not only was the form of knowledge acquisition revolutionised, all aspects of our daily lives such as our mode of communication was also impacted significantly. From a business perspective, strategic management has been identified to be closely tied to organisational culture. Positive cultural dimensions in an organisation were crucial in increasing the efficacy of strategies. Furthermore, in strategic management, achievement orientation has the largest influence on the success of strategies. With the increasing significance of sustainability in the 21 st century, it is also important for strategic management to incorporate sustainable goals for the organization. Such operational sustainability can include goals in combating climate change through supporting green energy. Therefore, strategic management is extremely important for job-seeking graduates looking to build a successful career. Scholars have found that graduates well acquainted with strategic concepts, such as planning, are more successful in organizations which are profit oriented. Their knowledge of strategic concepts provides them with the skills to develop fiscal plans, set business objects, and form both short-term and long-term plans which are very valuable in business development. Due to the issue of rising levels of job dissatisfaction, it is recommended that job-seekers enter organizations well aligned with their skills. Therefore, business management teams and tertiary educations should work together to ensure that students are equipped with relevant knowledge in strategic discipline values to amplify their career success after graduation.
|
// checkKey checks the key to make sure it exists and is computed.
func (d *ResourceDiff) checkKey(key, caller string) error {
s, ok := d.schema[key]
if !ok {
return fmt.Errorf("%s: invalid key: %s", caller, key)
}
if !s.Computed {
return fmt.Errorf("%s only operates on computed keys - %s is not one", caller, key)
}
return nil
}
|
John Joseph Woods
Personal life
Woods was born in the then colony of Van Diemen's Land (now Tasmania) in 1849 into an Irish family with fourteen other children, seven boys and seven girls. His father was a soldier. After teaching in Tasmania for nine years, he migrated to New Zealand as a young man and worked for a time in Nelson, Christchurch, Dunedin and Invercargill. Eight years teaching in New Zealand led to a position as the head teacher of St Patrick's School in Lawrence, Otago, and he moved there from Invercargill in 1874. Woods was known as a good musician. He was choirmaster of the local Catholic church, and could play twelve different instruments, though he was best known for his skill on the violin. Singing a solo at his own wedding, Woods established that he was also a competent singer.
While in Lawrence, Woods taught alongside an Irish widow called Harriet Conway (née Plunket) who already had two sons. They were married in September 1874 and had four children together, three sons and a daughter named Mary.
In 1902, Woods built a house of brick and wood on the corner of Lismore and Lancaster Streets which was his residence until he died in 1934. It is now under the care of the Historic Places Trust, which mounted a plaque on the street-facing back wall commemorating his composition of the national anthem.
County clerk
In 1877, Woods stopped teaching and was appointed the county clerk for the Tuapeka County Council. He was known for working 13-hour days and keeping accounts of such standard that he was accepted as a fellow of the Registered Accountants of New Zealand. Serving in this role, he also gained a reputation as an authority on county law, sought out by the council and clerks of other regions. He also organised the decoration of council office buildings to mark Queen Victoria's Diamond Jubilee in 1897. He served as county clerk for 55 years until illness forced him to retire in 1932, aged 83.
Other honours
Woods was deeply involved in the affairs of the town. He was a member of many local clubs and societies. He was also known as an expert on cultivating daffodils, of which his collection was the largest in the area. In 1884, Woods was elected first president of the local choral society.
When Woods was made an Honorary Freeman of New Zealand, he was commended for his "efficiency, integrity and devotion to duty".
|
/**
* Read a binary string from the array.
* @return the byte array.
* @throws IOException
*/
public byte[] readBinaryString() throws IOException {
int len = (int) readInt();
byte[] buf = new byte[len];
readFully(buf);
return buf;
}
|
Synthesis of --fluoro-,,-unsaturated esters and ketones via vinylogous 18F-fluorination of -diazoacetates with AgF. This communication reports a method for the vinylogous radiofluorination of -diazoacetates to generate -fluoro-,-unsaturated esters and ketones in moderate to good radiochemical yields. The method uses no-carrier-added AgF and is compatible with aromatic and non-aromatic substrates and a number of different functional groups. The labeling method is showcased in the synthesis of a fluorinated 5-cholesten-3-one derivative as well as a difluorinated product pertinent to drug discovery.
|
Stakes too High for Women? Gendered Examination of an Education Reform in Kenya This paper examines the relationship between women's education and their empowerment, using six waves of the nationally representative Kenya Demographic Health Surveys (KDHS). We utilize the change in the educational system in 1985 as a source of positive exogenous shock. We particularly focus on women who were exposed to the new regime and how their exposure status affects their perceptions and practices in decision making. The Ordinary Least Squares regression (OLS) results indicate an increase in education for women exposed to this reform, followed by the delay in their age at first birth, a reduction in female genital mutilation practice on their eldest daughters, a decrease in sexual domestic violence, and enhancement in their household decision making. Media exposure, partners' characteristics, and wealth endowment are the possible pathways through which women's empowerment is achieved.
|
The Sda and Cad glycan antigens and their glycosyltransferase, 1,4GalNAcTII, in xenotransplantation Antibodymediated rejection is a barrier to the clinical application of xenotransplantation, and xenoantigens play an important role in this process. Early research suggested that NacetylDgalactosamine (GalNAc) could serve as a potential xenoantigen. GalNAc is the immunodominant glycan of the Sda antigen. Recently, knockout of 1,4Nacetylgalactosaminyltransferase 2 (1,4GalNAcTII) from the pig results in a decrease in binding of human serum antibodies to pig cells. It is believed that this is the result of the elimination of the GalNAc on the Sda antigen, which is catalyzed by the enzyme, 1,4GalNAcTII. However, research into human blood group antigens suggests that only a small percentage (1%2%) of people express antiSda antibodies directed to Sda antigen, and yet a majority appear to have antibodies directed to the products of pig B4GALNT2. Questions can therefore be asked as to (i) whether the comprehensive structure of the Sda antigen in humans, that is, the underlying sugar structure, is identical to the Sda antigen in pigs, (ii) whether the human antiSda antibody binds ubiquitously to pig cells, but not to human cells, and (iii) what role the Sda++ (also called Cad) antigen is playing in this discrepancy. We review what is known about these antigens and discuss the discrepancies that have been noted above.
|
. "This paper offers the results of the analysis of changes in biological and economic structure of the population in South Croatia (Dalmatia) from 1948 to 1991. Special attention has been paid to the development of the secondary and tertiary activity sectors and the influence of general economic progress on the population." Changes in age and sex distribution are analyzed. (EXCERPT)
|
Characterisation and functional properties of proteins of some Indian chickpea (Cicer arietinum) cultivars BACKGROUND: Chickpea (Cicer arietinum L.) proteins have received attention during recent years owing to their higher biological values and better functional ingredients than oilseed proteins. In this study the composition, fractionation, electrophoretic behaviour and functional properties of five chickpea protein concentrates were determined. RESULTS: The chickpea proteins contained 15.954.8 g kg−1 albumin, 48.9154.1 g kg−1 globulin, 39.276.5 g kg−1 glutelin and traces of prolamin. Electrophoresis of the various fractions revealed that albumin and globulin were made up of sub-units of different molecular weights ranging from 7 to 96 kDa. Water and oil absorption of the protein concentrates varied from 1.15 to 2.75 g g−1 and from 2.60 to 5.65 g g−1 respectively. Foaming capacity and foam stability of the protein concentrates were good and improved with the addition of salt (10 g L−1 NaCl) or sugar (100 g L−1 sucrose) at both isoelectric and neutral pH. Emulsifying capacity and emulsion stability of the protein concentrates were good and excellent respectively. CONCLUSION: Protein concentrates prepared from chickpeas have potential use in food formulations owing to their good emulsifying/foaming and water/oil-binding capacities. Copyright © 2008 Society of Chemical Industry
|
from flask import render_template, url_for, redirect, request, flash
from unolocum.amzn_form import UrlForm
from unolocum import app
from bs4 import BeautifulSoup
import requests
from unolocum.sql import cur, conn
from mysql.connector.errors import DataError
from datetime import datetime
# global variables
# amzn
amzn_redirects = 0
change_in_price = 'none'
amzn_table_data = []
amzn_table_headings = ('#', 'Product', 'Current Price')
cur.execute("SELECT id, name, price FROM URL")
print(amzn_table_data)
# nsinfo
hemis = "northern"
ns_table_data = []
ns_table_headings = ('#', 'Name', 'Direction', 'Image')
current_month = datetime.now().strftime("%B")
#------------------------------------------amazon functions-----------------------------------------------
def AmazonTableData(): # reformats the table data into list so that its
global amzn_table_data # more easily accessible
cur.execute("USE unolocum")
cur.execute("SELECT id, name, price FROM URL")
amzn_table_data = cur.fetchall()
for i in range(len(amzn_table_data)):
amzn_table_data[i] = list(amzn_table_data[i])
amzn_table_data[i][2] = str(amzn_table_data[i][2])
AmazonTableData()
def productinfo(url): # gets info of the product from the url
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' }
page = requests.get(url, headers = headers)
soup = BeautifulSoup(page.content, 'html.parser')
pname = soup.find(id="productTitle").get_text()
pname = pname.strip() #product name
print(url)
try:
p_price = soup.find(id="priceblock_ourprice").get_text() # price in string form
except AttributeError:
p_price = soup.find(id="priceblock_dealprice").get_text() # price in string form
c_p_price = float(p_price.replace(',', '')[2: ]) # price in float form
return [url, pname, c_p_price]
def update_prices(): # updates prices
global change_in_price
AmazonTableData()
cur.execute("USE unolocum")
cur.execute("SELECT url from URL ORDER BY id")
urls = cur.fetchall()
print(urls)
url_count = 0
for url in urls:
print(url_count)
url = url[0]
product_info = productinfo(url)
c_p_price = product_info[2] # current price
cur.execute(f"SELECT price FROM URL where url='{url}'")
old_price = cur.fetchone()[0]
print(old_price)
print(type(old_price), type(c_p_price))
if c_p_price != old_price:
print(c_p_price)
if c_p_price > old_price:
print("increasing")
amzn_table_data[url_count][2] = str(c_p_price) + ' ▲'
cur.execute(f"UPDATE URL SET price={c_p_price} WHERE url='{url}'")
elif c_p_price < old_price:
print("decreasing")
amzn_table_data[url_count][2] = str(c_p_price) + ' ▼'
cur.execute(f"UPDATE URL SET price={c_p_price} WHERE url='{url}'")
conn.commit()
url_count += 1
#---------------------------------------- nsinfo functions----------------------------------------------
def NSTableData(hemis):
global ns_table_data
ns_table_images = []
cur.execute('USE unolocum_space_objects')
cur.execute(f"SELECT Name, Direction from {hemis} WHERE Month='{current_month}'")
ns_table_data = cur.fetchall()
for i in range(len(ns_table_data)):
ns_table_data[i] = (i+1,) + ns_table_data[i]
ns_table_images.append(f"http://www.allthesky.com/constellations/big/{ns_table_data[i][1].lower()}28vm-b.jpg")
print(ns_table_data)
print(ns_table_images)
ns_table_data = zip(ns_table_data, ns_table_images)
NSTableData(hemis)
# -------------------------------------------routes----------------------------------------------------
@app.route('/')
@app.route('/home')
def home():
return render_template('home.htm')
@app.route('/about')
def about():
return render_template('about.htm', title = 'About')
@app.route('/services')
def services():
return render_template('services.htm', title = 'Services')
@app.route('/test')
def test():
return render_template('test.htm', title = 'test')
@app.route("/callback")
def callback():
global authorization_url
authorization_url = (request.url)
returnf()
return render_template('home.htm')
def returnf():
tempvar = authorization_url
@app.route('/amzn', methods=['GET', 'POST'])
def amzn():
global amzn_redirects
amzn_redirects += 1
if amzn_redirects <= 1:
update_prices()
form = UrlForm()
url = form.url.data
if form.validate_on_submit():
product_info = productinfo(url)
url = product_info[0]
pname = product_info[1]
c_p_price = product_info[2]
try:
cur.execute(f"INSERT INTO URL (url, name, price) VALUES('{url}', '{pname}', {c_p_price})")
except DataError:
pname = pname[ :97] + '...'
print(pname)
cur.execute(f"INSERT INTO URL (url, name, price) VALUES('{url}', '{pname}', {c_p_price})")
conn.commit()
flash(f'Added.', 'success')
update_prices()
return redirect('/amzn')
print(amzn_table_data)
return render_template('amzn.htm', title='Amazon Tracking', form=form, amzn_table_headings=amzn_table_headings, amzn_table_data=amzn_table_data, change_in_price=change_in_price)
@app.route('/nightsky', methods = ['GET', 'POST'])
def nightsky():
global hemis
if request.method == 'POST':
hemis = request.form['hemis']
print(hemis)
NSTableData(hemis)
return render_template('nightsky.htm', title='Night Sky Info', hemis=hemis, ns_table_data=ns_table_data, ns_table_headings=ns_table_headings)
|
/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package exchange.core2.rest.model.api;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import exchange.core2.core.common.OrderAction;
import exchange.core2.core.common.OrderType;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
import java.math.BigDecimal;
//@JsonDeserialize(builder = StompOrderUpdate.StompOrderUpdateBuilder.class)
@Getter
@ToString
public class StompOrderUpdate {
// TODO remove immutable field
private final long uid;
private final long orderId;
private final BigDecimal price;
private final long size; // immutable
private final long filled;
private final GatewayOrderState state;
private final int userCookie;
private final OrderAction action; // immutable
private final OrderType orderType; // immutable
private final String symbol; // immutable
@JsonCreator
@Builder
public StompOrderUpdate(
@JsonProperty("uid") long uid,
@JsonProperty("orderId") long orderId,
@JsonProperty("price") BigDecimal price,
@JsonProperty("size") long size,
@JsonProperty("filled") long filled,
@JsonProperty("state") GatewayOrderState state,
@JsonProperty("userCookie") int userCookie,
@JsonProperty("action") OrderAction action,
@JsonProperty("orderType") OrderType orderType,
@JsonProperty("symbol") String symbol) {
this.uid = uid;
this.orderId = orderId;
this.price = price;
this.size = size;
this.filled = filled;
this.state = state;
this.userCookie = userCookie;
this.action = action;
this.orderType = orderType;
this.symbol = symbol;
}
}
|
<reponame>qiuzichi/SingleMadBrain
package com.unipad.common;
import com.unipad.utils.LogUtil;
/**
* Created by liuxiang on 2016/6/22.
*/
public class AppGlobalManager {
private static final long VIEW_CLICKED_TIME_LIMIT = 600;
private static long lastClickTime;
private static int lastButtonId;
/**
* 判断两次点击的间隔,如果小于600毫秒,则认为是多次无效点击
*
* 这个方法不是万能的,如果用户点击一个按钮后,迅速点击其他按钮,
* 在再次点击该按钮,或者用户同时点击多个按钮,都可能导致该方法失效
*
* 暂时使用这个判断,这个方法在以后再进行优化2015/11/6 11:20
*
* @return
*/
public static boolean isFastDoubleClick(int buttonId) {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (lastButtonId == buttonId && lastClickTime > 0 && timeD < VIEW_CLICKED_TIME_LIMIT) {
LogUtil.v("isFastDoubleClick", "短时间内按钮多次触发");
return true;
}
lastClickTime = time;
lastButtonId = buttonId;
return false;
}
}
|
/**
* The methods associated to the pricing of Ibor fixing deposit by discounting.
* <p>
* This provides the ability to price {@link ResolvedIborFixingDeposit}. Those products are synthetic deposits
* which are used for curve calibration purposes; they should not be used as actual trades.
*/
public class DiscountingIborFixingDepositProductPricer {
/**
* Default implementation.
*/
public static final DiscountingIborFixingDepositProductPricer DEFAULT =
new DiscountingIborFixingDepositProductPricer();
/**
* Creates an instance.
*/
public DiscountingIborFixingDepositProductPricer() {
}
//-------------------------------------------------------------------------
/**
* Calculates the present value of the Ibor fixing deposit product.
* <p>
* The present value of the product is the value on the valuation date.
*
* @param deposit the product
* @param provider the rates provider
* @return the present value of the product
*/
public CurrencyAmount presentValue(ResolvedIborFixingDeposit deposit, RatesProvider provider) {
Currency currency = deposit.getCurrency();
if (provider.getValuationDate().isAfter(deposit.getEndDate())) {
return CurrencyAmount.of(currency, 0.0d);
}
double forwardRate = forwardRate(deposit, provider);
double discountFactor = provider.discountFactor(currency, deposit.getEndDate());
double fv = deposit.getNotional() * deposit.getYearFraction() * (deposit.getFixedRate() - forwardRate);
double pv = discountFactor * fv;
return CurrencyAmount.of(currency, pv);
}
/**
* Calculates the present value sensitivity of the Ibor fixing product.
* <p>
* The present value sensitivity of the product is the sensitivity of the present value to
* the underlying curves.
*
* @param deposit the product
* @param provider the rates provider
* @return the point sensitivity of the present value
*/
public PointSensitivities presentValueSensitivity(ResolvedIborFixingDeposit deposit, RatesProvider provider) {
double forwardRate = forwardRate(deposit, provider);
DiscountFactors discountFactors = provider.discountFactors(deposit.getCurrency());
double discountFactor = discountFactors.discountFactor(deposit.getEndDate());
// sensitivity
PointSensitivityBuilder sensiFwd = forwardRateSensitivity(deposit, provider)
.multipliedBy(-discountFactor * deposit.getNotional() * deposit.getYearFraction());
PointSensitivityBuilder sensiDsc = discountFactors.zeroRatePointSensitivity(deposit.getEndDate())
.multipliedBy(deposit.getNotional() * deposit.getYearFraction() * (deposit.getFixedRate() - forwardRate));
return sensiFwd.combinedWith(sensiDsc).build();
}
//-------------------------------------------------------------------------
/**
* Calculates the deposit fair rate given the start and end time and the accrual factor.
*
* @param deposit the product
* @param provider the rates provider
* @return the par rate
*/
public double parRate(ResolvedIborFixingDeposit deposit, RatesProvider provider) {
return forwardRate(deposit, provider);
}
/**
* Calculates the deposit fair rate sensitivity to the curves.
*
* @param deposit the product
* @param provider the rates provider
* @return the par rate curve sensitivity
*/
public PointSensitivities parRateSensitivity(ResolvedIborFixingDeposit deposit, RatesProvider provider) {
return forwardRateSensitivity(deposit, provider).build();
}
//-------------------------------------------------------------------------
/**
* Calculates the spread to be added to the deposit rate to have a zero present value.
*
* @param deposit the product
* @param provider the rates provider
* @return the par spread
*/
public double parSpread(ResolvedIborFixingDeposit deposit, RatesProvider provider) {
return forwardRate(deposit, provider) - deposit.getFixedRate();
}
/**
* Calculates the par spread curve sensitivity.
*
* @param deposit the product
* @param provider the rates provider
* @return the par spread curve sensitivity
*/
public PointSensitivities parSpreadSensitivity(ResolvedIborFixingDeposit deposit, RatesProvider provider) {
return forwardRateSensitivity(deposit, provider).build();
}
//-------------------------------------------------------------------------
// query the forward rate
private double forwardRate(ResolvedIborFixingDeposit product, RatesProvider provider) {
IborIndexRates rates = provider.iborIndexRates(product.getFloatingRate().getIndex());
// The IborFixingDeposit are fictitious instruments to anchor the beginning of the IborIndex forward curve.
// By using the 'rateIgnoringTimeSeries' method (instead of 'rate') we ensure that only the forward curve is involved.
return rates.rateIgnoringFixings(product.getFloatingRate().getObservation());
}
// query the forward rate sensitivity
private PointSensitivityBuilder forwardRateSensitivity(ResolvedIborFixingDeposit product, RatesProvider provider) {
IborIndexRates rates = provider.iborIndexRates(product.getFloatingRate().getIndex());
return rates.rateIgnoringFixingsPointSensitivity(product.getFloatingRate().getObservation());
}
}
|
import os
import numpy as np
import json
from PIL import Image
import preprocessing
import utilities
import postprocessing
import time
import matplotlib.pyplot as plt
import ip_algorithms as ipa
def compute_convolution(I, T, stride=(None, None), pixel_group=None, img_name=''):
'''
This function takes an image <I> and a template <T> (both numpy arrays)
and returns a heatmap where each grid represents the output produced by
convolution at each location. You can add optional parameters (e.g. stride,
window_size, padding) to create additional functionality.
'''
'''
BEGIN YOUR CODE
'''
if np.max(I) > 1:
I = I/255
I = I - np.mean(I, axis=(0, 1))
if len(I.shape) != 3:
I = np.expand_dims(I, axis=2)
(n_rows, n_cols, n_channels) = np.shape(I)
if len(T.shape) == 2 and n_channels != 1:
(Trows, Tcols) = np.shape(T)
T = np.expand_dims(T, axis=2)
repT = np.tile(T, reps=3)
elif len(T.shape) == 3 and n_channels == 1:
T = np.mean(T, axis=2)
(Trows, Tcols) = np.shape(T)
repT = T
else:
(Trows, Tcols, Tchannels) = np.shape(T)
repT = T
avg_repT = np.mean(repT, axis=(0, 1))
center_repT = repT - avg_repT
norm_repT = np.linalg.norm(center_repT, axis=(0, 1))
cnT = center_repT / norm_repT
x, y = np.where(repT[:, :, 0] == np.max(repT[:, :, 0]))
hot_x = round(np.mean(x).item())
hot_y = round(np.mean(y).item())
tr_Trows = hot_x
br_Trows = Trows - tr_Trows
lc_Tcols = hot_y
rc_Tcols = Tcols - lc_Tcols
heatmap = np.zeros(shape=(n_rows, n_cols))
if stride is (None, None):
stride = (1, 1)
xvals = range(0, n_rows, stride[0])
yvals = range(0, n_cols, stride[1])
targeted = False
yvals_master = None
if pixel_group is not None:
targeted = True
xvals, yvals_master = zip(*pixel_group)
xval_count = 0
for i in xvals:
if targeted:
yvals = [yvals_master[xval_count]]
xval_count += 1
for j in yvals:
padded_patch = np.zeros(shape=(T.shape[0], T.shape[1], n_channels))
tr = max(0, i - tr_Trows)
br = min(n_rows, i + br_Trows)
lc = max(0, j - lc_Tcols)
rc = min(n_cols, j + rc_Tcols)
offsetr = abs(i - tr_Trows - tr) + abs(i + br_Trows - br)
offsetc = abs(j - lc_Tcols - lc) + abs(j + rc_Tcols - rc)
patch = I[tr:br, lc:rc, :]
if patch.shape != T.shape:
padded_patch[offsetr:, offsetc:, :] = patch
patch = padded_patch
center_patch = patch - np.mean(patch, axis=(0, 1))
norm_patch = np.linalg.norm(center_patch, axis=(0, 1))
# print(norm_patch)
cnp = center_patch/norm_patch
for k in range(3):
heatmap[i, j] += (np.dot(cnT[:, :, k].flatten(), cnp[:, :, k].flatten()))/3
'''
END YOUR CODE
'''
return heatmap
def predict_boxes(cmc_list, heatmap):
'''
This function takes heatmap and returns the bounding boxes and associated
confidence scores.
'''
output = []
'''
BEGIN YOUR CODE
'''
'''
As an example, here's code that generates between 1 and 5 random boxes
of fixed size and returns the results in the proper format.
'''
groups, _, _ = postprocessing.group_pixels(heatmap)
_, _, output = postprocessing.groups_to_bounding_boxes(groups, cmc_list, heatmap)
'''
END YOUR CODE
'''
return output
def detect_red_light_mf(I, img=None, name=''):
'''
This function takes a numpy array <I> and returns a list <output>.
The length of <output> is the number of bounding boxes predicted for <I>.
Each entry of <output> is a list <[row_TL,col_TL,row_BR,col_BR,score]>.
The first four entries are four integers specifying a bounding box
(the row and column index of the top left corner and the row and column
index of the bottom right corner).
<score> is a confidence score ranging from 0 to 1.
Note that PIL loads images in RGB order, so:
I[:,:,0] is the red channel
I[:,:,1] is the green channel
I[:,:,2] is the blue channel
'''
'''
BEGIN YOUR CODE
'''
# You may use multiple stages and combine the results
st = time.time()
kernel_list = []
kernel_sizes = []
exclude = [0, 1, 3, 4, 5, 7, 8, 10, 13, 14, 15, 17, 6, 9, 11, 16]
n_kernels = 6 * 3
for i in range(n_kernels):
if i in exclude:
continue
kernel_list.append(utilities.load_kernel(str(i), '../data/kernels/'))
kernel_sizes.append(preprocessing.get_patch_hot_spot_size(kernel_list[-1]))
rgb_pixel_array = np.load('../data/red_light_pixels/rgb_pixel_array.npy')
print('preprocessing...')
map_mih = preprocessing.color_match_red_lights(I, rgb_pixel_array, stride=(1, 2))
thresholded_mih_map = postprocessing.threshold_convolved_image(map_mih, 0.94, mode='down')
smoothed_thresholded_mih_map = ipa.neighbor_max_smooth_heatmap(thresholded_mih_map, np.zeros(shape=(5, 5)))
groups1, group_centers1, pixels = postprocessing.group_pixels(smoothed_thresholded_mih_map)
# print(time.time() - st)
# plt.imshow(smoothed_thresholded_mih_map)
# plt.show()
heatmaps = []
group_kernel_scores = np.zeros(shape=(len(kernel_list), len(groups1)))
print('match filtering... #pixels : ', np.sum(smoothed_thresholded_mih_map > 0))
exclude_group = []
for k, kernel in enumerate(kernel_list):
kernel_heatmaps = []
for i, group in enumerate(groups1):
if i in exclude_group:
continue
group = postprocessing.group_center_to_pixel_group(group_centers1[i], group, kernel, img_size=I.shape)
hmap = compute_convolution(I, kernel, stride=(1, 1), pixel_group=group)
kernel_heatmaps.append(hmap)
group_kernel_scores[k, i] = np.max(hmap)
# vis = False
# if (282, 478) in group and vis:
# plt.subplot(131)
# plt.imshow(hmap)
# plt.subplot(132)
# mask = np.copy(hmap)
# mask[mask > 0] = 1
# mask[mask < np.mean(mask)] = 0.25
# plt.imshow(I/255 * mask[:, :, None])
# plt.subplot(133)
# plt.imshow(kernel)
# plt.show()
kernel_heatmap = np.max(kernel_heatmaps, axis=0)
heatmaps.append(kernel_heatmap)
print(time.time() - st)
heatmap = np.max(heatmaps, axis=0)
# print('postprocessing...')
output = []
if len(groups1) > 0:
thresh_heatmap = postprocessing.threshold_convolved_image(heatmap, 0.83, mode='down')
groups, group_centers, _ = postprocessing.group_pixels(thresh_heatmap)
matched_indices = postprocessing.match_group_centers_to_groups(group_centers, groups1)
bb_heatmap = np.zeros(shape=heatmap.shape)
cmc_list = []
for i, ind in enumerate(matched_indices):
if ind != -1:
gc = group_centers[i]
kind = int(np.argmax(group_kernel_scores[:, ind]))
kernel = kernel_list[kind]
cmc = postprocessing.color_match_score(gc, kernel, I)
if cmc > 0.88:
postprocessing.add_kernel_patch(gc, kernel, heatmap, bb_heatmap)
cmc_list.append(cmc)
output = predict_boxes(cmc_list, bb_heatmap)
print(time.time() - st)
'''
END YOUR CODE
'''
for i in range(len(output)):
assert len(output[i]) == 5
assert (output[i][4] >= 0.0) and (output[i][4] <= 1.0)
return output
# Note that you are not allowed to use test data for training.
# set the path to the downloaded data:
data_path = '../data/RedLights2011_Medium'
# load splits:
split_path = '../data/hw02_splits'
file_names_train = np.load(os.path.join(split_path,'file_names_train.npy'))
file_names_test = np.load(os.path.join(split_path,'file_names_test.npy'))
# set a path for saving predictions:
preds_path = '../data/hw02_weakened2_preds'
os.makedirs(preds_path, exist_ok=True) # create directory if needed
# Set this parameter to True when you're done with algorithm development:
done_tweaking = True
'''
Make predictions on the training set.
'''
preds_train = {}
# print(file_names_train)
st = time.time()
# with open(os.path.join(preds_path, 'preds_train.json'), 'r') as f:
# preds_train = json.load(f)
for i in range(len(file_names_train)):
# if i < 139:
# continue
if i % 10 == 0:
print('Time Elapsed : ', time.time() - st)
with open(os.path.join(preds_path, 'preds_train.json'), 'w') as f:
json.dump(preds_train, f)
print(str(i) + '/' + str(len(file_names_train)) + ' : ' + file_names_train[i])
# read image using PIL:
img = Image.open(os.path.join(data_path,file_names_train[i]))
# convert to numpy array:
I = np.asarray(img)
preds_train[file_names_train[i]] = detect_red_light_mf(I, img, file_names_train[i])
print('Finished train, ' + str(time.time() - st))
# save preds (overwrites any previous predictions!)
with open(os.path.join(preds_path,'preds_train.json'),'w') as f:
json.dump(preds_train,f)
if done_tweaking:
'''
Make predictions on the test set.
'''
preds_test = {}
for i in range(len(file_names_test)):
if i % 10 == 0:
print('Time Elapsed : ', time.time() - st)
with open(os.path.join(preds_path, 'preds_test.json'), 'w') as f:
json.dump(preds_train, f)
print(str(i) + '/' + str(len(file_names_test)) + ' : ' + file_names_test[i])
# read image using PIL:
I = Image.open(os.path.join(data_path,file_names_test[i]))
# convert to numpy array:
I = np.asarray(I)
preds_test[file_names_test[i]] = detect_red_light_mf(I)
# save preds (overwrites any previous predictions!)
with open(os.path.join(preds_path, 'preds_test.json'),'w') as f:
json.dump(preds_test,f)
print('Finished test, ' + str(time.time() - st))
|
package com.ctrip.xpipe.redis.keeper.ratelimit;
import com.ctrip.xpipe.redis.core.protocal.PsyncObserver;
/**
* @author chen.zhu
* <p>
* Mar 02, 2020
*/
public interface PsyncChecker extends PsyncObserver {
boolean canSendPsync();
}
|
/*
If there is a TX message in the queue, sends it
When resume_mob(mob name) is called, it:
1) resumes the MOB
2) triggers an interrupt (callback function) to get the data to transmit
3) sends the data
4) pauses the mob
*/
void send_next_tx_msg(void) {
if (queue_empty(&tx_msg_queue)) {
return;
}
if (print_can_msgs) {
uint8_t tx_msg[8] = { 0x00 };
peek_queue(&tx_msg_queue, tx_msg);
print("CAN TX: ");
print_bytes(tx_msg, 8);
}
resume_mob(&cmd_tx_mob);
}
|
<reponame>FPJack/ZLBridge-JS
interface ZLBridge {
call(method: string,arg: any,func?:(arg: any)=>void):void;
register(method:string,func:(arg:any)=>any):void;
registerWithCallback(method:string,func:(arg:any,callback:(arg:any,end?:boolean)=>void)=>void):void;
removeRegisted(method:string):void;
}
declare const zlbridge: ZLBridge;
export default zlbridge;
|
Propagation of ultrasonic Lamb waves in adhesively bonded lap joints This paper considers the bonded joint as a multilayer structure that is analysed using the Transfer Matrix method. In this particular case three layers (two adherents and the adhesive) are considered. The study of this propagation problem may be developed from matrix formulations which describe elastic waves in layered media. This technique combines the theory of the dynamics of the continuum within each layer with the conditions for the interaction at the interfaces between layers. The behaviour of the different modes which propagates in the overlap region is obtained, and is found that the relative amplitudes can be estimated based on the properties of the incident wave mode. It was verified that the excitation of these modes is ruled by the degree to which their mode shapes match the mode shapes of the incident wave. This allows us to explain the physical phenomena that are behind the mode conversion, which could be used to a correct selection of modes for non-destructive evaluation of the bond region. Another result which must be emphasized consists is the possibility to determine by this method the attenuation of both longitudinal and transversal waves in plates what usually is a difficult by using conventional pulse-echo technique, especially in thin plates. Using an immersion pitch and catch setup, the total attenuation, that is composed by the losses due to the leaking in the fluid and material damping, can easily be obtained doing two measurements at different distances. The leaking losses can be obtained by knowing the bulk properties of both fluid and plate. So, attenuation of longitudinal and transversal waves (material damping) can be evaluated. In the experimental work two sets of lap joints built from 1mm and 4 mm thickness aluminium plates are tested using the fundamental S0 mode as incident wave. Very good agreement is found when compared with the theoretical predictions.
|
<reponame>hpcloud/jclouds-labs
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unles 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 expres or implied. See the License for the
* specific language governing permisions and limitations
* under the License.
*/
package org.jclouds.joyent.cloudapi.v6_5.features;
import static org.testng.Assert.assertEquals;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.joyent.cloudapi.v6_5.JoyentCloudApi;
import org.jclouds.joyent.cloudapi.v6_5.internal.BaseJoyentCloudApiExpectTest;
import org.jclouds.joyent.cloudapi.v6_5.parse.ParseKeyListTest;
import org.jclouds.joyent.cloudapi.v6_5.parse.ParseKeyTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
/**
* @author <NAME>
*/
@Test(groups = "unit", testName = "KeyApiExpectTest")
public class KeyApiExpectTest extends BaseJoyentCloudApiExpectTest {
public HttpRequest list = HttpRequest.builder().method("GET")
.endpoint("https://api.joyentcloud.com/my/keys")
.addHeader("X-Api-Version", "~6.5")
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build();
public HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(
payloadFromResource("/key_list.json")).build();
public void testListKeysWhenResponseIs2xx() {
JoyentCloudApi apiWhenKeysExists = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(apiWhenKeysExists.getKeyApi().list(), new ParseKeyListTest().expected());
}
public void testListKeysWhenResponseIs404() {
HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();
JoyentCloudApi listWhenNone = requestsSendResponses(getDatacenters, getDatacentersResponse, list, listResponse);
assertEquals(listWhenNone.getKeyApi().list(), ImmutableSet.of());
}
public void testCreateKeyWhenResponseIs202() throws Exception {
HttpRequest create = HttpRequest.builder()
.method("POST")
.endpoint("https://api.joyentcloud.com/my/keys")
.addHeader("X-Api-Version", "~6.5")
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==")
.payload(
payloadFromStringWithContentType(
"{\"name\":\"rsa\",\"key\":\"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0A5Pf5Cq...\"}",
"application/json")).build();
HttpResponse createResponse = HttpResponse.builder().statusCode(202).message("HTTP/1.1 202 Accepted")
.payload(payloadFromResourceWithContentType("/key.json", "application/json; charset=UTF-8"))
.build();
JoyentCloudApi apiWithNewKey = requestsSendResponses(getDatacenters, getDatacentersResponse, create, createResponse);
assertEquals(apiWithNewKey.getKeyApi().create(new ParseKeyTest().expected())
.toString(), new ParseKeyTest().expected().toString());
}
}
|
<reponame>SebastianBoldt/Soundrocket<filename>Soundrocket/SRCreatePlaylistTableTableViewController.h
//
// CreatePlaylistTableTableViewController.h
// Soundrocket
//
// Created by <NAME> on 03.01.15.
// Copyright (c) 2015 sebastianboldt. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Playlist.h"
@class SRCreatePlaylistTableTableViewController;
@protocol SRCreatePlaylistControllerDelegateProtocol
-(void)controller:(SRCreatePlaylistTableTableViewController*)controller didCreatePlaylist:(Playlist*)playlist;
@end
@interface SRCreatePlaylistTableTableViewController : UITableViewController
@property (nonatomic,strong) Playlist * playlist;
@property(nonatomic,strong)id<SRCreatePlaylistControllerDelegateProtocol> delegate;
@property (weak, nonatomic) IBOutlet UIButton *createPlaylistButton;
@property (weak, nonatomic) IBOutlet UISwitch *sharingSwitch;
@property (weak, nonatomic) IBOutlet UITextField *nameOfPlaylistTextField;
@property (weak, nonatomic) IBOutlet UILabel *privatelabel;
@property (weak, nonatomic) IBOutlet UILabel *iconLabel;
@property (weak, nonatomic) IBOutlet UILabel *descriptionLabel;
- (IBAction)createPlaylistButtonPressed:(id)sender;
@end
|
/**
* Simple ASCII style visualizer for level layout.
*
*/
class Visualizer {
public static String visualize(Container container, int size, double horizontalScaling) {
StringBuilder b = new StringBuilder();
for(Level level : container.getLevels()) {
double factor = (double)size / container.getWidth();
IRender render = new Render();
IContextBuilder builder = render.newBuilder();
int w = (int)(size * horizontalScaling);
int d = ((size * container.getDepth()) / container.getWidth());
builder.width(w).height(d);
for(Placement placement : level) {
Space space = placement.getSpace();
Box box = placement.getBox();
builder.element(new Rectangle((int)Math.round(space.getX() * factor * horizontalScaling), (int)Math.round(space.getY() * factor), (int)(box.getWidth() * factor * horizontalScaling), (int)(box.getDepth() * factor)));
if(box.getWidth() > 1 && box.getDepth() > 1) {
builder.element(new Dot((int)Math.round(placement.getCenterX() * factor * horizontalScaling), (int)Math.round(placement.getCenterY() * factor)));
}
}
builder.element(new Rectangle(0, 0, (int)(container.getWidth() * factor * horizontalScaling), (int)(container.getDepth() * factor)));
ICanvas canvas = render.render(builder.build());
b.append(canvas.getText());
b.append("\n");
}
return b.toString();
}
public static String visualizeSpace(Container container, int size, double horizontalScaling) {
StringBuilder b = new StringBuilder();
for(Level level : container.getLevels()) {
double factor = (double)size / container.getWidth();
IRender render = new Render();
IContextBuilder builder = render.newBuilder();
int w = (int)(size * horizontalScaling);
int d = ((size * container.getDepth()) / container.getWidth());
builder.width(w).height(d);
for(Placement placement : level) {
Space space = placement.getSpace();
builder.element(new Rectangle((int)Math.round(space.getX() * factor * horizontalScaling), (int)Math.round(space.getY() * factor), (int)(space.getWidth() * factor * horizontalScaling), (int)(space.getDepth() * factor)));
}
builder.element(new Rectangle(0, 0, (int)(container.getWidth() * factor * horizontalScaling), (int)(container.getDepth() * factor)));
ICanvas canvas = render.render(builder.build());
b.append(canvas.getText());
b.append("\n");
}
return b.toString();
}
}
|
Home » Blog » Who Uses Internet Dating?
Ever wonder who uses Internet dating services like Match.com and eHarmony.com? The answer may surprise you. I think, “Well, gee, everybody uses them!” But that’s not the case. There’s a particular psychological profile that researchers have discovered of users of Internet dating services.
The researchers (Kim et al., 2009) surveyed 3,345 people in the U.S., of which 1,588 (47.5 %) were men and 1,757 (52.5 %) were women. Ages ranged from 19 to 89 with a mean of 48 years old. They gathered their data using a number of standardized questionnaires and psychological measures.
Indeed, that finding confirms the idea that Internet dating is firmly in the mainstream now. While that may have not been the case 10 years ago, times have changed and using the Internet as a means of finding a prospective partner is no longer thought of as unusual. The researchers finding in this regard is not unique — previous research has come to the same conclusion, so it’s considered a robust research finding. For people who are already sociable, using the Internet as a dating method is just one more tool at their disposal.
But not all sociable folks consider the use of Internet dating. If you have high self-esteem and consider romantic relationships to be an important part of your life, you’re more likely to use Internet dating. If you have low self-esteem and consider romantic relationships not to be an important part of your life, you’re also more likely to use Internet dating.
So the researchers found that if you have low self-esteem and put some value on to your romantic relationships, you’re actually less likely to use Internet dating.
If the success of romantic relationships is the domain of self worth, one may try to increase the prospect of success and avoid failure in romantic relationships. In the context of Internet dating, when sociable people consider romantic relationships to be an important domain for self-worth, those with high self-esteem will be more likely than those with low self esteem to use Internet dating services.
of anonymous people, whereas those with low self-esteem will be more likely to experience a higher level of stress just thinking about disclosing and promoting themselves on the Internet. Less confident individuals may not want their negative self-views publicized or viewed by others.
To reduce such negative feelings and protect their self-worth, those with low self-esteem will adopt avoidance strategies and distance themselves from Internet dating services.
The upshot is that Internet dating is no longer the domain of the desperate nor those with low self-esteem (if it ever was).
The New York Times has a related article about the science (or lack thereof) behind the sites that claim such science helps you make better choices about dating. I think the science of such sites is ultimately of limited value, since no amount of data is going to predict whether two people will experience that indefinable quality of a “spark” on a first date. Without that, there will be no relationship.
Technology Review also weighed in this past week about the overwhelming number of choices of online dating and the research that has shown the more choices we have, the harder it can be sometimes to make a decision (“cognitive overload”). That’s why the sites try their best to offer you a way to limit the results displayed, but ultimately can fail in paring things down enough to make a difference to your brain.
Kim, M., Kwon, K-N & Lee, M. (2009). Psychological Characteristics of Internet Dating Service Users: The Effect of Self-Esteem, Involvement, and Sociability on the Use of Internet Dating Services. CyberPsychology & Behavior, 12(4). DOI: 10.1089=cpb.2008.0296.
|
Single Pulse Laser Energy Deposition in Quiescent Air and Hypersonic Flows Single laser energy deposition was experimentally investigated in both quiescent air and hypersonic flow. The induced flow pattern and the resulted perturbation to the hypersonic flow are observed using high-speed schlieren photograpay. A laser induced plasma was obtained by focusing a Q-switched single pulse Nd:YAG laser (wavelength 532 nm) with maximum laser energy of 203 mJ per pulse using a combination of concave-convex lenses. Initially, single pulse laser energy deposition was conducted in quiescent air at 101 kPa. Then, the laser beam was focused upstream of a truncated cone model as well as in the boundary layer above a flat plate in Mach 5 flow. In the quiescent air, the speed of the induced shock wave decays rapidly with time and the strength of the shock wave is weakened as it propagates outward. In the presence of hypersonic flow, the induced shock wave propagates downstream and interacts with the bow shock wave in front of the truncated cone. The bow shock wave is significantly mitigated with an effecting time of 450 s after the laser pulse. Over the flat plate, the induced shock wave perturbs the boundary layer and causes separation in the adjacent upstream. A separation shock wave is formed due to the existence of a separation region. The entire structures are similar to that flow pattern induced by pulse micro-jet. The propagation of the induced shock wave changes the local pressure distribution and a stronger pressure disturbance is found in the downstream compared to than the upstream of the focal point.
|
// Float lazily returns the current float value.
func (v *Value) Float() (*encoding.Float, error) {
if v.vfloat != nil {
return v.vfloat, nil
}
vfloat := encoding.NewFloat()
err := vfloat.UnmarshalBinary(v.Raw)
if err != nil {
return nil, err
}
v.vfloat = vfloat
return vfloat, nil
}
|
Pictured here is a yurt at a glamping resort. Glamping allows you to enjoy nature but with more comfort -- much more!
For many people, camping is a popular outdoor activity. Camping is for people who like to feel one with nature. They like sleeping, playing, eating and washing (or not washing) in the open air. In fact, they often like camping a lot more than staying at home.
Camping is not always easy. But people who like camping like roughing it. In other words, they don't mind leaving their creature comforts at home. For example, they do not mind sleeping in a tent on the ground. They don’t mind cooking and eating outside -- or doing anything outside.
But not everyone likes sleeping on the ground or washing up in a cold lake. Even people who like being out in nature may still like to get a good night’s sleep on a soft, comfortable bed.
For these types of people, glamping may be more appealing.
"Glamping" combines two other words, "glamour" and "camping."
I have been camping. But I have never been glamping. My friend Lisa has. So, I invited her into the studio to describe her glamping experience. Here is part of our conversation.
ANNA: What is “glamping”? How would you describe “glamping”?
LISA: Well, “glamping” is actually “glamorous camping,” right? So, that’s where glamping came from. So, it’s camping without all of the downsides.
ANNA: Would you consider yourself a “glamper”? Have you glamped?
ANNA: We don’t really use the word that way, do we?
ANNA: It’s a new word.
LISA: It is a new word, I think. I have gone glamping. And we went to this fabulous resort with these yurts. It’s a big round circular tent with like a wooden frame. But this particular yurt has under-floor heating and like a beautiful spa bathroom and a wood stove and fuzzy bathrobes hanging in the corner. What else do you need? And baskets of muffins delivered to your doorstep in the morning.
ANNA: That does not sound like camping. But yet, you are outside sleeping in a fabric enclosure – a yurt.
ANNA: Yeah, it would be hard to go back to camping once you’ve been glamping, I have to say.
LISA: Yes, I think that’s very true. In fact, it may be possible that I have not been camping since I went glamping.
ANNA: So, Lisa if you’re free this summer how would you like to go camping with me?
LISA: I would much rather go glamping with you. How do you feel about glamping?
ANNA: The way that you've described it, I could do glamping for a longer period of time than I could camping. I do like camping. But glamping sounds really awesome.
LISA: Glamping is fabulous. And if you’re doing it right, there’s a restaurant nearby so you don’t even have to cook.
This is the wood-framed yurt where Lisa stayed on her glamping trip.
And this is my tent for when I go camping.
Now, there is no reason you have to choose between camping and glamping. Perhaps you like to do both. You have your feet in both camps, so to speak.
When you have your feet in both camps, you are supporting or are involved with competing sides -- or at least two very different sides.
Sometimes, we use this expression when supporting both sides is a good thing. For example, let’s say two friends of yours are having a big fight, and they stop talking to each other. You, however, want to stay out of the conflict. So, you talk with both of them. You keep your feet in both camps.
But sometimes the expression carries with it the feeling that there is something dishonest going on. In other words, maybe a person is supporting both parties but not saying so. I imagine that this happens in the world of politics quite a bit.
But let’s not end this Words and Their Stories in politics. Let’s go back to nature.
Which camp are your feet in: camping or glamping?
I’m Anna Matteo. Special thanks to my friend Lisa for joining me on the program.
spa – n. a place where people go to improve their health and appearance by exercising, relaxing, etc.
fuzzy – adj. pleasant or comforting : covered with short, soft hairs, fur, etc.
|
//--------------------------------------------------------------------------------------
// File: Model.cpp
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "Model.h"
#include "CommonStates.h"
#include "DirectXHelpers.h"
#include "Effects.h"
#include "PlatformHelpers.h"
using namespace DirectX;
#if !defined(_CPPRTTI) && !defined(__GXX_RTTI)
#error Model requires RTTI
#endif
//--------------------------------------------------------------------------------------
// ModelMeshPart
//--------------------------------------------------------------------------------------
ModelMeshPart::ModelMeshPart() noexcept :
indexCount(0),
startIndex(0),
vertexOffset(0),
vertexStride(0),
primitiveType(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST),
indexFormat(DXGI_FORMAT_R16_UINT),
isAlpha(false)
{
}
ModelMeshPart::~ModelMeshPart()
{
}
// Draws using a custom override effect.
_Use_decl_annotations_
void ModelMeshPart::Draw(
ID3D11DeviceContext* deviceContext,
IEffect* ieffect,
ID3D11InputLayout* iinputLayout,
std::function<void()> setCustomState) const
{
deviceContext->IASetInputLayout(iinputLayout);
auto vb = vertexBuffer.Get();
UINT vbStride = vertexStride;
UINT vbOffset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vb, &vbStride, &vbOffset);
// Note that if indexFormat is DXGI_FORMAT_R32_UINT, this model mesh part requires a Feature Level 9.2 or greater device
deviceContext->IASetIndexBuffer(indexBuffer.Get(), indexFormat, 0);
assert(ieffect != nullptr);
ieffect->Apply(deviceContext);
// Hook lets the caller replace our shaders or state settings with whatever else they see fit.
if (setCustomState)
{
setCustomState();
}
// Draw the primitive.
deviceContext->IASetPrimitiveTopology(primitiveType);
deviceContext->DrawIndexed(indexCount, startIndex, vertexOffset);
}
// Draws using a custom override effect w/ instancing.
_Use_decl_annotations_
void ModelMeshPart::DrawInstanced(
ID3D11DeviceContext* deviceContext,
IEffect* ieffect,
ID3D11InputLayout* iinputLayout,
uint32_t instanceCount, uint32_t startInstanceLocation,
std::function<void()> setCustomState) const
{
deviceContext->IASetInputLayout(iinputLayout);
auto vb = vertexBuffer.Get();
UINT vbStride = vertexStride;
UINT vbOffset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vb, &vbStride, &vbOffset);
// Note that if indexFormat is DXGI_FORMAT_R32_UINT, this model mesh part requires a Feature Level 9.2 or greater device
deviceContext->IASetIndexBuffer(indexBuffer.Get(), indexFormat, 0);
assert(ieffect != nullptr);
ieffect->Apply(deviceContext);
// Hook lets the caller replace our shaders or state settings with whatever else they see fit.
if (setCustomState)
{
setCustomState();
}
// Draw the primitive.
deviceContext->IASetPrimitiveTopology(primitiveType);
deviceContext->DrawIndexedInstanced(
indexCount, instanceCount, startIndex,
vertexOffset,
startInstanceLocation);
}
// Creates input layout for use with custom override effects.
_Use_decl_annotations_
void ModelMeshPart::CreateInputLayout(ID3D11Device* d3dDevice, IEffect* ieffect, ID3D11InputLayout** iinputLayout) const
{
if (iinputLayout)
{
*iinputLayout = nullptr;
}
if (!vbDecl || vbDecl->empty())
throw std::runtime_error("Model mesh part missing vertex buffer input elements data");
if (vbDecl->size() > D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT)
throw std::runtime_error("Model mesh part input layout size is too large for DirectX 11");
ThrowIfFailed(
CreateInputLayoutFromEffect(d3dDevice, ieffect, vbDecl->data(), vbDecl->size(), iinputLayout)
);
assert(iinputLayout != nullptr && *iinputLayout != nullptr);
_Analysis_assume_(iinputLayout != nullptr && *iinputLayout != nullptr);
}
// Assigns a new effect and re-generates input layout.
_Use_decl_annotations_
void ModelMeshPart::ModifyEffect(ID3D11Device* d3dDevice, std::shared_ptr<IEffect>& ieffect, bool isalpha)
{
if (!vbDecl || vbDecl->empty())
throw std::runtime_error("Model mesh part missing vertex buffer input elements data");
if (vbDecl->size() > D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT)
throw std::runtime_error("Model mesh part input layout size is too large for DirectX 11");
assert(ieffect != nullptr);
this->effect = ieffect;
this->isAlpha = isalpha;
assert(d3dDevice != nullptr);
ThrowIfFailed(
CreateInputLayoutFromEffect(d3dDevice, effect.get(), vbDecl->data(), vbDecl->size(), inputLayout.ReleaseAndGetAddressOf())
);
}
//--------------------------------------------------------------------------------------
// ModelMesh
//--------------------------------------------------------------------------------------
bool ModelMesh::s_reversez = false;
ModelMesh::ModelMesh() noexcept :
boneIndex(ModelBone::c_Invalid),
ccw(true),
pmalpha(true)
{
}
ModelMesh::~ModelMesh()
{
}
// Set render state for mesh part rendering.
_Use_decl_annotations_
void ModelMesh::PrepareForRendering(
ID3D11DeviceContext* deviceContext,
const CommonStates& states,
bool alpha,
bool wireframe) const
{
assert(deviceContext != nullptr);
// Set the blend and depth stencil state.
ID3D11BlendState* blendState;
ID3D11DepthStencilState* depthStencilState;
if (alpha)
{
depthStencilState = (s_reversez) ? states.DepthReadReverseZ() : states.DepthRead();
if (pmalpha)
{
blendState = states.AlphaBlend();
}
else
{
blendState = states.NonPremultiplied();
}
}
else
{
blendState = states.Opaque();
depthStencilState = (s_reversez) ? states.DepthReverseZ() : states.DepthDefault();
}
deviceContext->OMSetBlendState(blendState, nullptr, 0xFFFFFFFF);
deviceContext->OMSetDepthStencilState(depthStencilState, 0);
// Set the rasterizer state.
if (wireframe)
deviceContext->RSSetState(states.Wireframe());
else
deviceContext->RSSetState(ccw ? states.CullCounterClockwise() : states.CullClockwise());
// Set sampler state.
ID3D11SamplerState* samplers[] =
{
states.LinearWrap(),
states.LinearWrap(),
};
deviceContext->PSSetSamplers(0, 2, samplers);
}
// Draw mesh given worldViewProjection matrices.
_Use_decl_annotations_
void XM_CALLCONV ModelMesh::Draw(
ID3D11DeviceContext* deviceContext,
FXMMATRIX world,
CXMMATRIX view,
CXMMATRIX projection,
bool alpha,
std::function<void()> setCustomState) const
{
assert(deviceContext != nullptr);
for (const auto& it : meshParts)
{
auto part = it.get();
assert(part != nullptr);
if (part->isAlpha != alpha)
{
// Skip alpha parts when drawing opaque or skip opaque parts if drawing alpha
continue;
}
auto imatrices = dynamic_cast<IEffectMatrices*>(part->effect.get());
if (imatrices)
{
imatrices->SetMatrices(world, view, projection);
}
part->Draw(deviceContext, part->effect.get(), part->inputLayout.Get(), setCustomState);
}
}
// Draw the mesh using model bones.
_Use_decl_annotations_
void XM_CALLCONV ModelMesh::Draw(
ID3D11DeviceContext* deviceContext,
size_t nbones, const XMMATRIX* boneTransforms,
FXMMATRIX world,
CXMMATRIX view,
CXMMATRIX projection,
bool alpha,
std::function<void()> setCustomState) const
{
assert(deviceContext != nullptr);
if (!nbones || !boneTransforms)
{
throw std::invalid_argument("Bone transforms array required");
}
XMMATRIX local;
if (boneIndex != ModelBone::c_Invalid && boneIndex < nbones)
{
local = XMMatrixMultiply(boneTransforms[boneIndex], world);
}
else
{
local = world;
}
for (const auto& it : meshParts)
{
auto part = it.get();
assert(part != nullptr);
if (part->isAlpha != alpha)
{
// Skip alpha parts when drawing opaque or skip opaque parts if drawing alpha
continue;
}
auto imatrices = dynamic_cast<IEffectMatrices*>(part->effect.get());
if (imatrices)
{
imatrices->SetMatrices(local, view, projection);
}
part->Draw(deviceContext, part->effect.get(), part->inputLayout.Get(), setCustomState);
}
}
// Draw mesh using skinning given bone transform array.
_Use_decl_annotations_
void XM_CALLCONV ModelMesh::DrawSkinned(
ID3D11DeviceContext* deviceContext,
size_t nbones,
const XMMATRIX* boneTransforms,
FXMMATRIX world,
CXMMATRIX view,
CXMMATRIX projection,
bool alpha,
std::function<void()> setCustomState) const
{
assert(deviceContext != nullptr);
if (!nbones || !boneTransforms)
{
throw std::invalid_argument("Bone transforms array required");
}
ModelBone::TransformArray temp;
for (const auto& mit : meshParts)
{
auto part = mit.get();
assert(part != nullptr);
if (part->isAlpha != alpha)
{
// Skip alpha parts when drawing opaque or skip opaque parts if drawing alpha
continue;
}
auto imatrices = dynamic_cast<IEffectMatrices*>(part->effect.get());
if (imatrices)
{
imatrices->SetMatrices(world, view, projection);
}
auto iskinning = dynamic_cast<IEffectSkinning*>(part->effect.get());
if (iskinning)
{
if (boneInfluences.empty())
{
// Direct-mapping of vertex bone indices to our master bone array
iskinning->SetBoneTransforms(boneTransforms, nbones);
}
else
{
if (!temp)
{
// Create the influence mapped bones on-demand.
temp = ModelBone::MakeArray(IEffectSkinning::MaxBones);
size_t count = 0;
for (auto it : boneInfluences)
{
++count;
if (count > IEffectSkinning::MaxBones)
{
throw std::runtime_error("Too many bones for skinning");
}
if (it >= nbones)
{
throw std::runtime_error("Invalid bone influence index");
}
temp[count - 1] = boneTransforms[it];
}
assert(count == boneInfluences.size());
}
iskinning->SetBoneTransforms(temp.get(), boneInfluences.size());
}
}
else if (imatrices)
{
// Fallback for if we encounter a non-skinning effect in the model
XMMATRIX bm = (boneIndex != ModelBone::c_Invalid && boneIndex < nbones)
? boneTransforms[boneIndex] : XMMatrixIdentity();
imatrices->SetWorld(XMMatrixMultiply(bm, world));
}
part->Draw(deviceContext, part->effect.get(), part->inputLayout.Get(), setCustomState);
}
}
//--------------------------------------------------------------------------------------
// Model
//--------------------------------------------------------------------------------------
Model::~Model()
{
}
Model::Model(Model const& other) :
meshes(other.meshes),
bones(other.bones),
name(other.name),
mEffectCache(other.mEffectCache)
{
const size_t nbones = other.bones.size();
if (nbones > 0)
{
if (other.boneMatrices)
{
boneMatrices = ModelBone::MakeArray(nbones);
memcpy(boneMatrices.get(), other.boneMatrices.get(), sizeof(XMMATRIX) * nbones);
}
if (other.invBindPoseMatrices)
{
invBindPoseMatrices = ModelBone::MakeArray(nbones);
memcpy(invBindPoseMatrices.get(), other.invBindPoseMatrices.get(), sizeof(XMMATRIX) * nbones);
}
}
}
Model& Model::operator= (Model const& rhs)
{
if (this != &rhs)
{
Model tmp(rhs);
std::swap(meshes, tmp.meshes);
std::swap(bones, tmp.bones);
std::swap(boneMatrices, tmp.boneMatrices);
std::swap(invBindPoseMatrices, tmp.invBindPoseMatrices);
std::swap(name, tmp.name);
std::swap(mEffectCache, tmp.mEffectCache);
}
return *this;
}
// Draw all meshes in model given worldViewProjection matrices.
_Use_decl_annotations_
void XM_CALLCONV Model::Draw(
ID3D11DeviceContext* deviceContext,
const CommonStates& states,
FXMMATRIX world,
CXMMATRIX view,
CXMMATRIX projection,
bool wireframe,
std::function<void()> setCustomState) const
{
assert(deviceContext != nullptr);
// Draw opaque parts
for (const auto& it : meshes)
{
auto mesh = it.get();
assert(mesh != nullptr);
mesh->PrepareForRendering(deviceContext, states, false, wireframe);
mesh->Draw(deviceContext, world, view, projection, false, setCustomState);
}
// Draw alpha parts
for (const auto& it : meshes)
{
auto mesh = it.get();
assert(mesh != nullptr);
mesh->PrepareForRendering(deviceContext, states, true, wireframe);
mesh->Draw(deviceContext, world, view, projection, true, setCustomState);
}
}
// Draw all meshes in model using rigid-body animation given bone transform array.
_Use_decl_annotations_
void XM_CALLCONV Model::Draw(
ID3D11DeviceContext* deviceContext,
const CommonStates& states,
size_t nbones,
const XMMATRIX* boneTransforms,
FXMMATRIX world,
CXMMATRIX view,
CXMMATRIX projection,
bool wireframe,
std::function<void()> setCustomState) const
{
assert(deviceContext != nullptr);
// Draw opaque parts
for (const auto& it : meshes)
{
auto mesh = it.get();
assert(mesh != nullptr);
mesh->PrepareForRendering(deviceContext, states, false, wireframe);
mesh->Draw(deviceContext, nbones, boneTransforms, world, view, projection, false, setCustomState);
}
// Draw alpha parts
for (const auto& it : meshes)
{
auto mesh = it.get();
assert(mesh != nullptr);
mesh->PrepareForRendering(deviceContext, states, true, wireframe);
mesh->Draw(deviceContext, nbones, boneTransforms, world, view, projection, true, setCustomState);
}
}
// Draw all meshes in model using skinning given bone transform array.
_Use_decl_annotations_
void XM_CALLCONV Model::DrawSkinned(
ID3D11DeviceContext* deviceContext,
const CommonStates& states,
size_t nbones,
const XMMATRIX* boneTransforms,
FXMMATRIX world,
CXMMATRIX view,
CXMMATRIX projection,
bool wireframe,
std::function<void()> setCustomState) const
{
assert(deviceContext != nullptr);
// Draw opaque parts
for (const auto& it : meshes)
{
auto mesh = it.get();
assert(mesh != nullptr);
mesh->PrepareForRendering(deviceContext, states, false, wireframe);
mesh->DrawSkinned(deviceContext, nbones, boneTransforms, world, view, projection, false, setCustomState);
}
// Draw alpha parts
for (const auto& it : meshes)
{
auto mesh = it.get();
assert(mesh != nullptr);
mesh->PrepareForRendering(deviceContext, states, true, wireframe);
mesh->DrawSkinned(deviceContext, nbones, boneTransforms, world, view, projection, true, setCustomState);
}
}
// Compute using bone hierarchy from model bone matrices to an array.
_Use_decl_annotations_
void Model::CopyAbsoluteBoneTransformsTo(
size_t nbones,
XMMATRIX* boneTransforms) const
{
if (!nbones || !boneTransforms)
{
throw std::invalid_argument("Bone transforms array required");
}
if (nbones < bones.size())
{
throw std::invalid_argument("Bone transforms array is too small");
}
if (bones.empty() || !boneMatrices)
{
throw std::runtime_error("Model is missing bones");
}
memset(boneTransforms, 0, sizeof(XMMATRIX) * nbones);
XMMATRIX id = XMMatrixIdentity();
size_t visited = 0;
ComputeAbsolute(0, id, bones.size(), boneMatrices.get(), boneTransforms, visited);
}
// Compute using bone hierarchy from one array to another array.
_Use_decl_annotations_
void Model::CopyAbsoluteBoneTransforms(
size_t nbones,
const XMMATRIX* inBoneTransforms,
XMMATRIX* outBoneTransforms) const
{
if (!nbones || !inBoneTransforms || !outBoneTransforms)
{
throw std::invalid_argument("Bone transforms arrays required");
}
if (nbones < bones.size())
{
throw std::invalid_argument("Bone transforms arrays are too small");
}
if (bones.empty())
{
throw std::runtime_error("Model is missing bones");
}
memset(outBoneTransforms, 0, sizeof(XMMATRIX) * nbones);
XMMATRIX id = XMMatrixIdentity();
size_t visited = 0;
ComputeAbsolute(0, id, bones.size(), inBoneTransforms, outBoneTransforms, visited);
}
// Private helper for computing hierarchical transforms using bones via recursion.
_Use_decl_annotations_
void Model::ComputeAbsolute(
uint32_t index,
FXMMATRIX parent,
size_t nbones,
const XMMATRIX* inBoneTransforms,
XMMATRIX* outBoneTransforms,
size_t& visited) const
{
if (index == ModelBone::c_Invalid || index >= nbones)
return;
assert(inBoneTransforms != nullptr && outBoneTransforms != nullptr);
++visited; // Cycle detection safety!
if (visited > bones.size())
{
DebugTrace("ERROR: Model::CopyAbsoluteBoneTransformsTo encountered a cycle in the bones!\n");
throw std::runtime_error("Model bones form an invalid graph");
}
XMMATRIX local = inBoneTransforms[index];
local = XMMatrixMultiply(local, parent);
outBoneTransforms[index] = local;
if (bones[index].siblingIndex != ModelBone::c_Invalid)
{
ComputeAbsolute(bones[index].siblingIndex, parent, nbones,
inBoneTransforms, outBoneTransforms, visited);
}
if (bones[index].childIndex != ModelBone::c_Invalid)
{
ComputeAbsolute(bones[index].childIndex, local, nbones,
inBoneTransforms, outBoneTransforms, visited);
}
}
// Copy the model bone matrices from an array.
_Use_decl_annotations_
void Model::CopyBoneTransformsFrom(size_t nbones, const XMMATRIX* boneTransforms)
{
if (!nbones || !boneTransforms)
{
throw std::invalid_argument("Bone transforms array required");
}
if (nbones < bones.size())
{
throw std::invalid_argument("Bone transforms array is too small");
}
if (bones.empty())
{
throw std::runtime_error("Model is missing bones");
}
if (!boneMatrices)
{
boneMatrices = ModelBone::MakeArray(bones.size());
}
memcpy(boneMatrices.get(), boneTransforms, bones.size() * sizeof(XMMATRIX));
}
// Copy the model bone matrices to an array.
_Use_decl_annotations_
void Model::CopyBoneTransformsTo(size_t nbones, XMMATRIX* boneTransforms) const
{
if (!nbones || !boneTransforms)
{
throw std::invalid_argument("Bone transforms array required");
}
if (nbones < bones.size())
{
throw std::invalid_argument("Bone transforms array is too small");
}
if (bones.empty())
{
throw std::runtime_error("Model is missing bones");
}
memcpy(boneTransforms, boneMatrices.get(), bones.size() * sizeof(XMMATRIX));
}
// Iterate through unique effect instances.
void Model::UpdateEffects(_In_ std::function<void(IEffect*)> setEffect)
{
if (mEffectCache.empty())
{
// This cache ensures we only set each effect once (could be shared)
for (const auto& mit : meshes)
{
auto mesh = mit.get();
assert(mesh != nullptr);
for (const auto& it : mesh->meshParts)
{
if (it->effect)
mEffectCache.insert(it->effect.get());
}
}
}
assert(setEffect != nullptr);
for (const auto it : mEffectCache)
{
setEffect(it);
}
}
|
/*
* This has to be at the end after the pDispatch explicit specializations.
*/
cl_int ExecutionManager::dispatch(compute::DispatchPayload const& payload)
{
cl_int clResult = CL_SUCCESS;
size_t execNodeKEY = GET_EXECNODEKEY(payload.tag);
ExecutionNode* node = p_execNodes[execNodeKEY].get();
switch (node->getDevice()->getProfile())
{
case DeviceProfile::eGPGPU:
clResult = pDispatch<DeviceProfile::eGPGPU, WorkItemDistribution::eIncremental>(node, payload);
default:
assert(0);
}
return clResult;
}
|
An unexpected 2,3-dihydrofuran derivative ring opening initiated by electrophilic bromination: scope and mechanistic study. An unexpected 2,3-dihydrofuran ring opening process at the C-C bond has been developed. N-Bromosuccinimide and DABCO were used as the electrophilic halogen source and the catalyst, respectively. Mechanistic study indicates that moisture in the solvent might contribute to the reaction. The resulting brominated product could be further oxidized to yield a synthetically valuable 1,2-diketo building block.
|
AMBER-DYES: Characterization of Charge Fluctuations and Force Field Parameterization of Fluorescent Dyes for Molecular Dynamics Simulations. Recent advances in single molecule fluorescence experiments and theory allow a direct comparison and improved interpretation of experiment and simulation. To this end, force fields for a larger number of dyes are required which are compatible with and can be integrated into existing biomolecular force fields. Here, we developed, characterized, and implemented AMBER-DYES, a modular fluorescent label force field, for a set of 22 fluorescent dyes and their linkers from the Alexa, Atto, and Cy families, which are in common use for single molecule spectroscopy experiments. The force field is compatible with the AMBER protein force fields and the GROMACS molecular dynamics simulation program. The high electronic polarizability of the delocalized -electron orbitals, as found in many fluorescent dyes, poses a particular challenge to point charge based force fields such as AMBER. To quantify the charge fluctuations due to the electronic polarizability, we simulated the 22 dyes in explicit solvent and sampled the charge fluctuations using QM/MM simulations at the B3LYP/6-31G*//TIP3P level of theory. The analysis of the simulations enabled us to derive ensemble fitted RESP charges from the solvated charge distributions of multiple trajectories. We observed broad, single peaked charge distributions for the conjugated ring atoms with well-defined mean values. The charge fitting procedure was validated against published charges of the dyelike amino acid tryptophan, which showed good agreement with existing tryptophan parameters from the AMBER, CHARMM, and OPLS force field families. A principal component analysis of the charge fluctuations revealed that a small number of collective coordinates suffices to describe most of the in-plane dye polarizability. The AMBER-DYES force field allows the rapid preparation of all atom molecular dynamics simulations of fluorescent systems for state of the art multi microsecond trajectories.
|
On the outskirts of Kiev, men lay on the ground, rifles at the ready. For the moment, they're firing at cardboard, but soon the targets could include Russian soldiers or eastern Ukrainian separatists. The black-red banners of Ukrainian nationalists flap above them -- among the trees of the derelict troop training area where Soviets once learned how to shoot.
Ready, aim, "breathe deeply and think before you fire," yells Mykola Ishenko, 48. Two decades ago, he was a drill sergeant in the Ukrainian army. Now he's stuffed himself back into a uniform and wants to make the transition from civilian to fighter. They exercise, throw knives, engage in hand-to-hand combat. Due to a lack of sandbags, they kick and punch logs.
Their unit is called the group of "Three Hundreds," and it is comprised of dozens of civilian defense leagues that were formed during the insurgency on the Maidan, Kiev's Independence Square. Their ideal is that of the national partisan and they have organized in order to defend the Ukrainian state. They include cosmopolitan, Western-oriented students, but also hard-boiled right-wing extremists who view the toppling of President Viktor Yanukovych as only the first step of a "national revolution." Many Maidan activists have been showing up at the military training camp since Russia's annexation of Crimea, with around 50 men turning up at the site in Kiev each day.
More Ukrainian than Russian
Trainer Ishenko has been here for two weeks now, but he also served guard duty during the Maidan protests. He says he has nothing against the Russians -- on the contrary, he even earns money from them. He works as a tour guide, and many of his customers are Russian visitors. At the same time, Ishenko says he's a Ukrainian patriot and that he considers Russian President Vladimir Putin to be an aggressive dictator.
The fact that Ishenko is now training partisans is the source of conflict with his mother. She spent the majority of her life in the Soviet Union. If the Russians really do send soldiers into Ukraine, she says they should be given flowers. Her son would prefer to point a gun at them.
In terms of their numbers, right-wing groups were only a minority during the Maidan protests, but they formed the backbone of the revolt against the Yanukovych government. When initially peaceful protests turned violent, it was right-wing groups who defended the barricades, threw Molotov cocktails and carried firearms.
Russian propaganda tends to describe these groups, in blanket terms, as "fascists." But the right-wing camp is anything but homogenous. In the western part of the country, there are three different factions. There are the civilian patriots like Ishenko, who view it as their duty to fight for their country. There are revanchist anarchists who want to challenge corrupt state authorities. And there are right-wing radicals of the ideological and dangerous variety who want to take advantage of the current vacuum to rise to power themselves. They are supporters of a totalitarian ethno-nationalism with anti-Semitic overtones.
The Right Sector, one of the most important groups on the Maidan, is among the latter. At its core are followers who are clearly right-wing extremists, but it has also since become a rallying point for the discontented.
Newfound Allegiance
Alexander Kolokolov, 37, is another ethnic Russian who identifies as a Ukrainian national. He recently joined the Right Sector. Kolokolov lives in Kherson, a city that is a 12-hour train ride from Kiev and is located near Crimea. At first, many believed that Kherson would also be annexed by Russia. Most people here speak Russian in their daily lives. But the annexation of Crimea instead strengthened the position of Ukrainian nationalists here. They toppled the city's statue of Lenin and replaced it with a memorial to the "Heavenly Hundred," as the Ukrainians have named the more than 100 people killed during recent protests on the Maidan. After the Russians marched into Crimea, people here began wearing blue and yellow armbands as a token of their allegiance to Ukraine.
Kolokolov used to be a criminal investigator, but he says he got fed up at some point with the sleaze and corruption. He quit and is now hunting down criminals together with his fellow members of the Right Sector. The change they hoped would come through the coup failed to materialize and they feel there are too few fresh faces in the new government. Now they now want to take responsibility for public order into their own hands.
Their greatest opponent is Colonel Mikhail Fabrin, the head of the security forces in Kherson. He's only been in office for a few weeks now, but his nomination for the post was pushed through by the party of world champion boxer Vitali Klitschko. Kolokolov doesn't trust the colonel because Fabrin was previously stationed in Crimea and ran in the 2010 regional parliament election as a candidate for, of all things, the Russian Unity party of the new Crimean president, Sergey Aksyonov.
'Warriors of Good'
The local chapter of Right Sector has moved into a musty office in Kherson's city center between a copy shop and a beauty salon. It also serves as the precinct for Kolokolov's guards, who act as a police-like citizens' watch. They fan out at night to shut down gambling houses and patrol the streets. They've already closed down an illegal gas station where Kolokolov claims corrupt police had been selling gasoline they had seized.
The colonel wasn't happy about those developments. His officials raided the Right Sector office and searched for weapons, but they didn't find any. Kolokolov says they didn't find the pistol that had been hidden in the printer either. Other than that, he says, the vigilantes are unarmed.
The local boss has just found out about an imminent shipment of drugs in Kherson and his men want to catch the dealer. To prepare themselves mentally, they play music videos on a computer. In it, imaginary figures fight a giant eagle with Molotov cocktails, the heraldic animal of Ukraine's notorious Berkut special police force. The music featured in the video is a favorite of the right-wing scene, complete with the refrain: "Warriors of light, warriors of good." That's also how they view themselves.
Some of the militias from Maidan are now acting like criminal gangs; many of them are loose -- and violence-prone -- groups of nationalists, though not as ideological as the Right Sector. Just last week, masked militiamen attacked a cement factory after being paid to do so by businessmen interested in taking over the company that owns it. There have been other reports of similar incidents, such as an assault on a vodka distillery.
Lofty Ambitions
The man who the Kherson militia would like to see become president of Ukraine can be found in a former industrial quarter of Kiev -- he lives on Moscow Prospect, a somewhat ironic address for a nationalist. The 42-year-old Dmytro Yarosh founded a martial sports group in the 1990s which went on to spawn the Right Sector. In the past, he preferred to make public appearances in military uniform, but he receives us in jeans and a dark, turtleneck sweater. Yarosh, after all, has lofty ambitions. He has registered as a candidate for the May presidential elections and is lobbying for the Right Sector to be recognized as a party. He says that his movement has over 10,000 members and hopes that the current wave of nationalism will be enough to propel him to the presidency.
When Yarosh spoke on the Maidan, he was received with more cheers than his rival Yulia Tymoshenko, partly because his men impressed Ukrainians with their discipline and stamina during the uprising. Even a classified document from Russian security authorities notes, not without admiration, that the Right Sector is "the only organized power" and that it attracts "like a magnet" both extremists and the general populace.
For years, Yarosh has been fighting for the "de-Russification" of Ukraine and has produced manifestos calling for the "spread of the nationalist ideology across the entire territory of our state." Today, Yarosh denies that anti-Semitism is part of that ideology. But in a book, he has written: "I wonder how it came to pass that most of the billionaires in Ukraine are Jews?"
He believes that "anti-Christian" powers are afoot in the European Union and that Brussels forces people into lifestyles such as gay marriage. It is, he says, "a variety of totalitarianism." He doesn't see Europe or NATO as a potential partner and believes the US is also part of an "anti-Ukrainian front." Yarosh studied linguistics, and he is almost eloquent as he explains that a Kalashnikov can be a Ukrainian's only reliable ally.
The Right Sector is in favor of legalizing gun ownership in order to develop a "country of free, armed men." That, he adds, "is the only way we can defend ourselves from state capriciousness and against Russia." Yarosh's words are a threat, and not just against Moscow. More than anything, his target is the Kiev establishment. He closes with the statement: "Our revolution is not yet complete."
|
package at.aau.esop15.course11;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
/**
* Created by mlux on 15.12.2015.
*/
public class SimplePaint extends JPanel {
JFrame mainFrame;
ColorPicker colorPicker;
LinkedList<Point> points = new LinkedList<>();
public SimplePaint(JFrame mainFrame) {
this.mainFrame = mainFrame;
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
addPoint(e.getPoint());
}
});
Thread runner = new Thread(() -> {
while (true) repaint(120);
});
runner.start();
}
private void addPoint(Point point) {
points.add(point);
}
public static void main(String[] args) {
final JFrame main = new JFrame("Simple Java Paint");
main.setSize(640, 480);
SimplePaint simplePaint = new SimplePaint(main);
final JFXPanel fxPanel = new JFXPanel();
Platform.runLater(() -> {
ColorPicker cp1 = new ColorPicker();
Scene sc = new Scene(cp1);
fxPanel.setScene(sc);
simplePaint.setColorPicker(cp1);
});
main.getContentPane().add(fxPanel, BorderLayout.NORTH);
main.getContentPane().add(simplePaint, BorderLayout.CENTER);
main.setVisible(true);
}
public void setColorPicker(ColorPicker colorPicker) {
this.colorPicker = colorPicker;
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
while (!points.isEmpty()) {
if (colorPicker != null) {
javafx.scene.paint.Color val = colorPicker.getValue();
Color pc = new Color((float) val.getRed(), (float) val.getGreen(), (float) val.getBlue());
g2.setColor(pc);
}
Point p = points.removeFirst();
g2.fillOval(p.x, p.y, 5, 5);
}
}
}
|
Sen. Ted Cruz (R-Tex.) plans to introduce legislation that would block Syrian Muslim refugees being allowed into the country. Cruz is the son of Cuban immigrants. His father Rafael arrived in the United States shortly before Castro came to power, on a student visa.
In 1980, when Cruz was 9, it was Cuban refugees who were the ones that the American public wanted to curtail. A flood of refugees in the last months of the Carter administration prompted a good deal of hand-wringing. That May, ABC News asked Americans whether President Jimmy Carter was right or wrong in letting as many as 40,000 refugees from Cuba into the United States. Two-thirds said he was wrong. A month later, presented with the figure of 100,000, opinions of Carter were even worse.
Asked by CBS News and the New York Times whether Cuban refugees would be welcomed if they settled near where the respondents lived, more than half of those with an opinion said they wouldn't be. When Gallup asked people in December 1981 who they wouldn't want as neighbors, Cuban refugees were opposed by 25 percent of the respondents -- second only to "minority religious sects." (Fourteen percent of people wouldn't want to live near single people living together, which seems like a euphemism.) Fear of Cuban criminals sit at the center of the 1983 movie "Scarface," which tells the story of "political refugee"-turned-drug-lord Tony Montana, an arrival in the 1980 wave.
At about the time that Rafael Cruz left Cuba, though, there was a different group of refugees that was concerning Americans. He arrived in 1957, shortly after the Soviet Union occupied Hungary. That November, Gallup asked whether the law should be changed to make it easier for Hungarian and Polish refugees to enter the United States. Fifty-seven percent of respondents said no. The next month, a survey from Foreign Affairs magazine found that more than a third of Americans thought that too many Hungarian refugees were being admitted. By the following September, half of people who offered an opinion on the subject said that the country shouldn't change the law to prevent Hungarian refugees from being deported.
Cruz's opposition to Syrian refugees is echoed by a number of other elected officials, including New Jersey Gov. Chris Christie. Christie's heritage is mixed, but his mother, Sondra Grasso, was of Italian descent. (She died in 2004.) Her father, Christie's grandfather, was born on a ship traveling from Sicily to New York City in 1909. In that decade, between 1900 and 1910, more than 2 million immigrants from Italy arrived in the United States.
There wasn't robust polling at the time, but Italian immigrants faced significant public opposition. In 1905, the New York Times ran an article from "several statisticians" arguing that the perception of Italian immigrants was incorrect. "[T]he Italian settler is economically a good thing for the country," it argued, and, what's more, "in the particulars of disease and crime he does not supply more than his quota."
In 1911, a review of federal immigration policies conducted by the Dillingham Commission determined that immigration should be curtailed, in part because the influx of immigrants was driving down wages. Immigration from southeastern Europe, including Italy, was seen as especially problematic because of the percentage of the population that was male — and therefore would be looking for work.
(New York Tribune, 1911)
Southeastern Europe also includes countries like Croatia, which is the ethnic heritage of Ohio Gov. John Kasich (who also opposes Syrian refugees). His grandparents were immigrants and probably arrived in the same general time period.
Louisiana Gov. Bobby Jindal's parents emigrated from India in the early 1970s, well after laws restricting immigration from India were overturned. Had they tried to immigrate to the United States 50 years earlier, they would not have been able to do so, since India was included in the "Asiatic Barred Zone" passed by Congress in 1917 (over President Woodrow Wilson's veto). No Indian immigrants were allowed at all.
None of these efforts to limit or oppose immigrants and refugees is exactly like any of the others. There are things about the current influx of Syrian refugees that are unique. But it is not unique that the public should be concerned about new arrivals and that the officials they elect should try to enforce laws that would introduce new limits.
If the politicians involved in this current iteration don't believe that, they need only ask their grandparents.
Update: House Speaker Paul Ryan on Tuesday backed a pause on refugees from Syria. His family background includes immigrants from Ireland, who were one of the most-discriminated-against groups of immigrants in American history.
|
Late Show Conspiracy Theories with Damon Wayans Jr.
00:53 — Is the Earth round or flat? Or neither? Damon Wayans Jr., star of 'Happy Together' on CBS, helps us settle this debate once and for all.
|
Techniques in Computer-Aided Diagnosis and their application in clinical investigation of bronchial systems Respiratory diseases constitute a major preoccupation for the medical community, due to their worldwide extent, their high incidence in the industrialized countries and an important mortality rate. In this context, early diagnosis is the key issue for the patient healthcare policy. After its introduction in clinical routine during the last decade, helical computed tomography (CT) became rapidly the recomended imaging technique for assessing airway disease. With the advent of multidetector row CT (MDCT), high resolution images of the airways were possible to be acquired throughout the whole thorax, in a single breath hold. But the advantage to benefit of high-quality data for pulmonary investigation was counterbalanced by the large amount of data the clinician had to deal with. Computer-aided diagnosis (CAD) techniques are now proposed in routine investigation. This chapter aims at presenting an overview of the advances in the CAD techniques designed for bronchial systems analysis. According to their investigation ability, both basic and advanced methods are addressed throughout this presentation. From direct visualization, to complex segmentation, interaction, navigation, simulation and quantification issues, the challenges raised by the airway pathology investigation are discussed and various solutions are presented and illustrated.
|
Erratum: Heterologous expression of newly identified galectin-8 from sea urchin embryos produces recombinant protein with lactose binding specificity and anti-adhesive activity Galectin family members specifically bind beta-galactoside derivatives and are involved in different cellular events, including cell communication, signalling, apoptosis, and immune responses. Here, we report a tandem-repeat type galectin from the Paracentrotus lividus sea urchin embryo, referred to as Pl-GAL-8. The 933nt sequence encodes a protein of 34.73 kDa, containing the conserved HFNPRF and WGxExR motifs in the two highly similar carbohydrate-recognition domains (CRD). The three-dimensional protein structure model of the N-CRD confirms the high evolutionary conservation of carbohydrate binding sites. The temporal gene expression is regulated during development and transcripts localize at the tip of the archenteron at gastrula stage, in a subset of the secondary mesenchyme cells that differentiate into blastocoelar (immune) cells. Functional studies using a recombinant Pl-GAL-8 expressed in bacteria demonstrate its hemo-agglutinating activity on human red blood cells through the binding to lactose, as well as its ability in inhibiting the adhesion of human Hep-G2 cells to the substrate. The recent implications in autoimmune diseases and inflammatory disorders make Gal-8 an attractive candidate for therapeutic purposes. Our results offer a solid basis for addressing the use of the new Pl-GAL-8 in functional and applicative studies, respectively in the developmental and biomedical fields. Lectins are proteins that preferentially bind to carbohydrate complexes protruding from glycolipids and glycoproteins 1. They were shown to bind both to oligosaccharides on cells and to free-floating glycans, at the micromolar to the millimolar range 2. Due to their binding properties, lectins are involved in cell homeostasis, which is regulated by the controlled transcription of numerous genes. Thus, multiple signalling pathways and enzymatic cascades are influenced by lectins. Therefore, it is not surprising that certain lectins are expressed in a developmentally regulated fashion, both during early embryonic 3 and postnatal development 4. A subgroup of lectins is represented by the galectins 5. Galectins represent a large ancient family of structurally-related proteins identified in phylogenetically diverse species 6. Although they have been initially acknowledged as developmentally regulated lectins mainly in vertebrates also identified in sponges and in many protostome and deuterostome invertebrates 7, (see Supplementary Table S1 online). Generally physiological functions of invertebrate lectins are not completely understood. Increasing information confirm their involvement in processes like differentiation and development, as well as the elimination of foreign substances through binding to their carbohydrate structures. The Table (S1) lists examples of invertebrates protostome and deuterostome galectins described in the literature, indicating also their location in different cell types and tissues, as well as their putative and proved functions. Galectins exhibit a carbohydrate binding specificity towards disaccharides containing -galactosides found in cellular glycoconjugates or glycoproteins 8. The functional domain(s) of galectins involve one or two carbohydrate recognition domains (CRDs) within a single polypeptide chain. Based on their domain organization, galectin subfamilies are designated as proto-, chimera-and tandem repeat-types 9. In the tandem repeat type, each one of the two CRDs may have a diverse specificity. Tandem repeat type galectins do not involve diverse functional domains or interaction specificity with non CRDs. This is in contrast to the chimera galectins and the C-type lectins, which often occur together with other domain types in the same peptidic chain. Structurally, the galectin's CRD is a beta-sheet sandwich of about 135 aa, formed by 11 strands; carbohydrates are bound within the groove formed in the concave side by 6 strands 13. Galectins were initially discovered in tissue extracts and were analysed for their ability to agglutinate erythrocytes; based on the hypothesis that cell surface carbohydrates take part in cell adhesion 14. They were shown to exhibit inhibitory functions in cell adhesion and to induce apoptosis by binding to integrins 15. In fact, various functional roles of galectins have been evidenced in cancer 16, in innate and adaptive immunity 17 and in development 18,19. Furthermore, galectins appear to be implicated in diverse activities inside and outside the cell, both in invertebrates and vertebrates, where galectins participate in cell adhesion/proliferation, development/morphogenesis, tumor cell metastasis and immune regulation/innate immunity 20. Although several tandem repeat type members of the galectin superfamily have been described in adult and embryonic tissues of invertebrates 11 (see Supplementary Table S1 online), no characterization of galectin-8 has been reported for Echinoderms so far. The sea urchin has an extraordinary importance as a model for classical developmental and innovative systems biology studies, being in the lineage leading to the vertebrates and humans 21. Its genome includes many previously thought to be vertebrate innovations (or known only outside the deuterostomes), providing an evolutionary outgroup for the chordates and yielding insights into the evolution of deuterostomes 21. The access to the sea urchin genome of the species Strongylocentrotus purpuratus 21 and to ESTs sequences of the species Paracentrotus lividus, gave us the opportunity to look for galectin superfamily members. In this study, we report the identification and characterization of Pl-GAL-8, a new member of the galectin-8 family isolated from P. lividus sea urchin embryo. We describe its: i) cDNA sequence, ii) phylogenetic position, iii) protein domain 3D structure, iv) temporal and spatial mRNA expression profile, v) expression as recombinant fusion protein, vi) carbohydrate-binding specificity and vii) anti-adhesive activity. Results Identification, cloning and phylogenetic analysis. We isolated and cloned the complete galectin-8 cDNA from P. lividus sea urchin embryos (gastrula stage). The nucleotide sequence has a length of 1309 nt, including a 933 nt-long CDS and a 376 nt-long 3 UTR (Acc. Num. FR716469). The deduced amino acid sequence resulted of 311 residues with a predicted pI of 9.39 and a MW of 34.73 kDa. By in silico analysis, we identified two carbohydrate-recognition domains (CRD, Fig. 1A); the first spanning from V24 to Q158 (135 aa-long) and the second from Y178 to Q311 (134 aa-long). The two domains are joined by a linker region of 19 aa. In addition, we found ten predicted phosphorylation sites, including six serine residues (S33, S98, S154, S170, S243, S252), three threonine residues (T84, T143, T187) and one tyrosine (Y164) (Fig. 1A). The isolated cDNA showed a high identity (85%) with two sequences previously reported in S. purpuratus, namely: the predicted galectin-8-like sequence, of 2038 bp-long mRNA (Acc Num. XM_776778) identified at the NCBI; and the SPU_006306 sequence annotated as Sp-Gal/lec3, identified in the Sea Urchin Genome database (http://www.spbase.org/SpBase/search/) 22 Figure 1B shows the phylogenetic analysis acquired by ClustalW alignment obtained by comparing Pl-GAL-8 with homologous protein sequences of different deuterostomes, from hemichordates to humans. It is noted that with the exception of G. gallus, R. norvegicus and H. sapiens, all the sequences used in the alignment have only been identified as Galectin-8 homologues, but no characterization of the functional protein domains has been described. As expected, we found the Galectin-8 signature known to be responsible for the unique carbohydrate specificity 23, in the arginine located at position 64 of the N-terminal domain (R64), which corresponds to R59 of the human Galectin-8. An additional arginine (R204) is found at the same conserved position of the C-terminal domains of S. Purpuratus, B. Floridae and S. Kowalevski. Each of the two Pl-GAL-8 domains contains two evolutionarily conserved motifs, HFNPRF and WGxExR, which are present in all galectins described so far. We found six cysteine residues (potential SS intra-, inter-or extra-chain bridges) and one potential glycosylation site (NASY) at position 250-253. Based on the alignment, an NJ phylogenetic tree was generated (Fig. 1C) which demonstrates that among Chordates, Galectins-8 from echinoderms (P. lividus and S. purpuratus) are phylogenetically closer to Galectins-8 from cephalochordates (Amphioxus). Domain homology and modeling. To investigate the homology between the two tandem domains of Pl-GAL-8 we aligned their amino acidic sequences using the LALIGN program. As expected, we found a high sequence identity (62.8%) and similarity (83.7%) between domains, suggesting evolutionary-driven gene duplication, typical of most tandem repeated domains. To further characterize the Pl-GAL-8 domains, we blasted separately the sequence of each of the two domains at the NCBI and discovered the highest identity (49.6%) and similarity (75.6%) between the N-terminal domains of Pl-GAL-8 and human Galectin-8. The comparison of the C-terminal domains showed lower identity (46%) and similarity (63%). It was of interest to study the conservation of the overall 3D structure of the CRD of Pl-GAL-8 that is linked to its activity. Up to now, nineteen 3D crystal structures of N-and C-terminal domains of the human Galectin-8 have been deposited at the protein data bank, including structures containing bound carbohydrates or oligosaccharides. Therefore, based on the high primary sequence identity and structural similarity with the PDB structure of the N-terminal domain of human Galectin-8 (pdb: 2yv8), we obtained the 3D model structure of the Pl-GAL-8 N-terminal domain (Fig. 2). The model shows a bend-shaped structure, with two opposing sheets, each one containing antiparallel -strands forming a -sandwich arrangement. One of the two -sheets forms a concave region (cleft), containing the conserved carbohydrate-binding sites similarly to the N-terminal CRD domain of human Galectin-8 23. We found that the N-terminal domain model contains the canonical number of strands, with only differences being in the length of the S5 and S6 strands. In fact, the S5 strand of the Pl-GAL-8 model is divided in two smaller strands (S5a and S5b), by the conserved polar amino acid asparagine (N83, corresponding to N79 of the human template), while S5 of the template is undivided. On the contrary, the S6 strand of the Pl-GAL-8 model is smaller and identical to the first part (S6a) of the longer S6 strand of the human structure. The latter is subdivided into two smaller S6a and S6b strands by two amino acids, one of which is the conserved glutamic acid (E89) corresponding to E93 found in the Pl-Gal-8 model. By comparison with the human 3D structures (pdb: 2yv8 and 3AP5), we identified nine lactose-binding sites on the Pl-GAL-8 domain model. Apart from H52, which in the human Galectin-8 corresponds to Q47, all the rest lactose-binding sites identified in Pl-GAL8 are evolutionary conserved. Specifically, the sites: i) R50, H70, N72, R74, N83 and E93, are known to directly interact with lactose via hydrogen bonding 23, ii) W90, is known to form hydrogen bonds with lactose and participating in van der Waals interactions with the galactose ring 23 and iii) H52 and R64 are known to form a water-mediated hydrogen bond with lactose 23. Temporal and spatial gene expression profiling. The temporal expression profile of Pl-gal-8 during embryonic development was analyzed by comparative real-time qPCR ( CCt qPCR). We found that Pl-gal-8 mRNA was detectable at the cleavage stage and gradually increased at the blastula and gastrula stages, to reach a peak at the pluteus stage (Fig. 3A). It was particularly important from the developmental point of view to determine if the Pl-gal-8 transcripts were restricted to specific embryonic territories. To this aim, we analysed the spatial expression of Pl-gal-8 by WMISH using an antisense RNA probe (containing the complete ORF) on embryos fixed at different developmental stages, from early blastula to pluteus. Pl-gal-8 transcripts were not noticeable at the blastula stage ( Fig. 3B, a) as they were initially detected at the mesenchyme blastula stage, localized at the vegetal plate in a few of the secondary mesenchyme cells (SMCs) and at the presumptive endodermal cells (Fig. 3B, b). At gastrula, transcripts were localized at the tip of the archenteron, which invaginates from the vegetal plate and in some blastocoelar cells at the archenteron tip originated from the detachment of SMCs (Fig. 3B, c-d, see arrows). At the prism stage Pl-gal-8 mRNA was detected in the three differentiated parts of the gut (foregut, midgut and hindgut), with a higher signal at the level of the two sphincters, namely the constrictions separating the foregut from midgut, and the midgut from hindgut (Fig. 3B, e; see asterisks). No other territories appeared labelled at the pluteus stage, which was the latest stage investigated, where the Pl-gal-8 mRNA was highly restricted to the gut (Fig. 3B, f). Expression and purification of the recombinant protein. To produce Pl-GAL-8 recombinant protein we constructed a fusion protein by inserting the full-length CDS of Pl-gal-8 into the pCold vector containing the CDS of the chaperone trigger factor (TF), generally used for the production of soluble and functional/active proteins. It is also known that the TF assists in producing the appropriate folding of recombinant proteins 24, especially at the most proximal part of the inserted sequence 25. The construct also contained at the N-terminal an 11 aa-long 6 His-tag, which is needed for protein detection and purification (Fig. 4A). We analysed the bacterial extracts containing the fusion protein by SDS-PAGE, as shown in Fig. 4B. A prominent band was detected in the eluted fractions of the affinity chromatography, indicating an apparent protein size consistent with a theoretical molecular weight of 88.9 kDa, calculated for the fusion protein. The purified recombinant protein obtained from the pooled fractions was then purified by dialysis to reduce salt concentration and remove low molecular weight compounds such as imidazole, which could eventually interfere with the protein folding and activity (Fig. 4B, lane on the right). Carbohydrate binding activity and specificity. To identify the biological activity of Pl-GAL-8, we tested the ability of the recombinant protein to induce agglutination of RBCs in a conventional assay 26 (Fig. 5). Following 40 min incubation at room temperature, the agglutination activity was determined: wells that contain spread RBC exhibit agglutination activity, while wells that contain small red dots lack agglutination ability. Using serial dilutions, we found that the minimum concentration able to induce agglutination was 0.25 M (Fig. 5A,C). Loss of Pl-GAL-8 activity was evident after the inactivation of the recombinant protein at 100 °C for 15 min (Fig. 5A,C). BSA, also used as a negative control, did not induce RBC agglutination even at the highest dose tested (1 M, Fig. 5A,C). The purified trigger factor (TF) recombinant protein, obtained from the expression of the pCold vector alone, was also tested and shown to be inactive, thus demonstrating that it does not contribute to the activity of the Pl-GAL-8 recombinant protein (Fig. 5A,C). As tandem repeat galectins do not show the tendency to form dimers, trimers, etc. 27, we infer that the observed carbohydrate binding activity is due to the single recombinant Pl-GAL-8 polypeptide. The high similarity of Pl-GAL-8 with other members of the family suggests a sugar-binding specificity. To investigate the specificity, we studied the ability of increasing concentrations of different mono-and di-saccharide sugars to interfere with the hemoagglutinating activity of 0.25 M recombinant Pl-GAL-8 (Fig. 5B,D). The agglutination of RBC cells induced by Pl-GAL-8, was efficiently inhibited by lactose at all doses tested (from 1 to 20 mM) and, to a certain extent, by galactose at 20 mM. No inhibition of Pl-GAL-8 activity was observed with mannose or other sugars tested (glucose, sucrose, maltose; not shown). Anti-adhesive activity of the recombinant Pl-GAL-8. To further characterize the functional activity of Pl-GAL-8, we used the recombinant protein to test its ability to modulate cell adhesion, as described for other Galectins-8 15. Generally, when immobilized onto matrices (or on well surfaces), galectin-8 supports the adhesion of cells to the substrate, promoting their spreading and migration, triggering integrin-mediated signaling cascades which involve phosphorylation events of intracellular mediators 19,28. On the contrary, when it is present in excess as a soluble ligand, galectin-8 negatively regulates cell adhesion, inhibiting cell-substrate adhesion, by binding both cell surface integrins and other soluble ECM proteins, such as fibronectin 19,28. We tested this second biological activity of the recombinant protein using a human hepato-carcinoma cell line (HepG2) by measuring their adhesion on culture multiwell plates, in the presence of increasing concentrations of soluble recombinant Pl-GAL-8. As shown in Fig. 6, recombinant Pl-GAL-8 effectively inhibits the adhesion of cells in a dose-dependent manner, as assayed 3 h after plating. About 50% of inhibition was observed at the concentration of 0.2 M, while only 10% of cells adhered to the wells with the highest concentration used (1.6 M). As no interfering activity of the trigger factor was detected in the hemoagglutination assay, we decided not to include such a negative control. On the contrary, we used the human recombinant Galectin-8 as a positive control, and found a similar adhesion inhibitory effect (Fig. 6). Discussion In the present study, we report the identification of a new member of the galectin superfamily found in the sea urchin embryo. We describe the identification of the CDS, and the tempo-spatial mRNA expression during development. Additionally, we present the phylogenetic analysis of the protein, characterize its structure and study functional aspects using a recombinant protein we produced. Based on in silico analysis and sequence comparison with known homologs from distant phyla, the protein has been identified as a novel member of the galectin-8 family and named Paracentrotus lividus galectin-8 (Pl-GAL-8). Members of the galectin family are widely distributed in nature, in both embryonic and adult organisms, implying their importance in carrying out intra-and extracellular functions mediated by glycoconjugate recognition. The molecular characterization of new galectin-8 members was particularly awaited as they are recognized as important actors of many vital functions such as in innate and adaptive immunity and in physiological cell cycle homeostasis 17. The presence of galectin proteins in adults (coelomic fluid) of the sea urchin Strongylocentrotus purpuratus has been reported by proteomic analysis 29, although no further characterization was described. This is the first report describing the discovery of a galectin superfamily member in Echinoderms, which is added to the short list of invertebrate galectins, (see Supplementary Table S1 online). By identifying a new galectin-8 family member from the sea urchin embryo, a well established model for classical developmental studies, this work contributes information on the galectin-8 family phylogenesis. On the basis of in silico cDNA analysis, we hypothesize the presence of other Pl-GAL-8 isoforms, probably generated by alternative splicing, as it occurs in mouse and human 29. The occurrence of different-sized linker regions present in homologous sequences identified in the sea urchin EST database is in favor of this hypothesis. However, further studies will be necessary to demonstrate the existence of more than one sea urchin GAL-8 protein isoform. In this study we found that Pl-GAL-8 does not contain a typical signal peptide, in analogy with other previously identified members of the family known to be targeted not only to cytosolic and nuclear sites, but also to the extracellular environment 28 where they play key-roles as soluble mediators of various cell functions. Indeed, earlier studies demonstrated that Galectins might be secreted by a non-classical secretory pathway 6 and later reports on Galectin-1 and Galectin-5 demonstrated that the so-called alternative pathway of secretion implies the involvement in the exosomal sorting pathway 30. The lack of a signal peptide in all the Galectins analyzed so far is an additional demonstration of the strong conservation across vertebrate and invertebrate species. In general, the occurrence and the relative positions of cysteine residues are recognized as important factors in both protein structure and function. This is because of their ability to form intra and inter-molecular disulfide bridges influencing the protein folding, thus affecting protein's functionality. The Galectin-8 proteins from different species compared in this study (Fig. 1B), differ in the total number of cysteine residues. In an evolutionary context, it is worth mentioning that the C268 found in Pl-GAL-8 is the most conserved cysteine, as it is found in all the aligned sequences, (with the only exception of galectin from C. intestinalis). Generally, the activity of proteins can be modulated by post-translational modifications, such as glycosylation and phosphorylation. In the Pl-GAL-8 sequence we found one potential glycosylation motif (NASY) and 10 predicted phosphorylation sites (see Fig. 1B). However, other studies reported that native Galectin-8 is not heavily glycosylated, neither extensively phosphorylated 28. In agreement, our studies demonstrate that the protein's biological activity does not depend on post-translational modifications that are obviously not present in the recombinant protein made in bacteria. The two HFNPRF and WGxExR motifs present in the CRD domains are involved in sugar binding and intra-molecular linking mediated by hydrogen bonds or weak van der Waals forces 8,10. Interestingly, we found that the two Pl-GAL-8 CRDs (N-and C-terminal) contain identical HFNPRF and WGxExR motifs, unlike human Galectin-8, where CRDs contain sequence differences 28 that could determine differences in carbohydrate-binding specificity 31. As a result, our findings suggest that in sea urchins, the N-and C-terminal domains of Pl-GAL-8 have the same carbohydrate-binding specificity. This was confirmed experimentally by the heamoagglutination assay. The N-and C-terminal CRDs of Pl-GAL-8 show high values of identity (60%), in contrast to tandem repeat type galectins from other organisms, including human (38%), generally ranging from 20% to 40%, 28,32. Thus, the high CRDs identity suggests that Pl-GAL-8 is an ancestral form of the Galectin-8 protein. This is in agreement with the hypothesis proposing that all CRDs of tandem repeat galectins found in chordates evolved by a gene tandem duplication event of an ancestral mono-CRD galectin followed by divergent evolution 33. In accord, we found that the entire Pl-GAL-8 protein showed very high identity values only with S. purpuratus (88%) and low-medium identity values (30%-54%) with other organisms. This evidence, together with the high similarity between the two CRDs supports the hypothesis that Pl-gal-8 is the nearest gene to the postulated duplication event. As for other proteins, the 3D structure of Galectins provided with information on the highly evolutionarily conserved interaction sites. Many crystal structures have been reported for N-terminal and C-terminal domains of the human Galectin-8, alone or in association with sugars or other binding molecules 31. In general, Galectins are characterized by 11 beta-strands forming two antiparallel sheets. In particular, the sheet forming the concave side of the structure contains six (S1-S6) antiparallel -strands while the other sheet forming the convex side contains five (F1-F5) antiparallel -strands 23,34. The finding that the S5 strand of the Pl-GAL-8 model is divided into two smaller S5a and S5b strands implies that this feature is irrelevant with respect to the biological function of the molecule, as confirmed experimentally by the hemoagglutination assay (see Fig. 5). Despite the above mentioned differences, the generated Pl-GAL-8 model is highly similar to the structure of the template (human), showing that in both proteins, the conserved sugar-binding cleft exposes the same nine functional residues, with the exception of the histidine (H52) found on the S3 strand, corresponding to the glutamine (Q47) of the human template. A similar difference is found when comparing the sequences of the C-terminal domains, where histidine (H206) in Pl-GAL-8 is replaced by asparagine (N215) in human Galectin-8 23. However, the presence of the conserved histidines (H52 and H206) in P. lividus, is indicative of the great homology between the N-terminal and C-terminal domains, confirming their high conservation and calling for their identical carbohydrate-binding specificity. This suggestion is strengthened by the presence of the arginines (R64 and R204) in conserved positions in both N-and C-domains. In this study, we established a protocol for the expression of a fusion recombinant protein using the cDNA from a marine invertebrate species to address the biological function(s) of Pl-GAL-8. The recombinant fusion protein, tested in vitro by a hemagglutination assay on human red blood cells and an adhesion assay on human hepatoma cells (HepG2), demonstrated a sugar-binding specificity and its involvement in mediating cell adhesion. This is in agreement with the functional characterization of the Galectin-8 family members described so far, known to act as physiological modulators of cell adhesion 15,19. As expected for a Galectin-8 family member 15, only lactose (low concentrations) and galactose (higher concentrations), bind to Pl-GAL-8 and favor RBC hemagglutination, therefore preventing the inhibitory activity of Pl-GAL-8. The low effective inhibitory concentration of lactose (1 mM) suggests a high specificity of the Pl-GAL-8-lactose interaction, probably reflecting the bivalency of the protein. Galectin-8 has a dual effect on the adhesive performance of cells, i.e. depending on the extracellular context it can either promote or inhibit adhesion 15,19. We demonstrated that the recombinant Pl-GAL-8 is involved in cell-matrix interactions as it inhibited the binding of HepG2 cells to the substrate in a dose-dependent manner. This finding is in agreement with reports on the mammalian galectin-8 15,19,28,32. The inhibition was more effective than the one obtained by the highest concentration of human recombinant Galectin-8 used as a control. This result suggests a potential use of the recombinant Pl-GAL-8 protein in industrial applications. As for the function of the protein in the sea urchin embryo, the availability of the recombinant Pl-GAL-8 encourages future studies, involving for example the production and use of specific antibodies for embryonic perturbation and cell adhesion assays. Although at present we have no direct evidence for Pl-GAL-8 adhesion activity in the embryo, a recent study on the proteome of P. lividus tube feet (the adhesive organs of the adults) has proposed a role of Galectin-8 in mediating temporary cell-substrate adhesion 35. The temporal and spatial expression patterns of Pl-GAL-8 during sea urchin development have been described here for the first time. By qPCR, we found that Pl-gal-8 transcripts showed a developmental upregulation at gastrula and pluteus stages. This finding is in accordance with the important role attributed to galectins in controlling morphogenetic events during embryogenesis 36 and particularly with the role assigned to carbohydrates and carbohydrate-bearing molecules in supporting cell-cell interactions during sea urchin gastrulation 37. For example, the binding of secondary mesenchyme cells to the blastocoel roof is prevented by D-mannose like residues, resulting in the inhibition of gastrulation 37. This finding matches with the spatial localization of Pl-gal-8 transcripts at the tip of the archenteron found by WMISH in this study. The staining observed at the tip of the invaginating archenteron is associated to two major presumptive cells types, i.e. blastocoelar cells and gut cells, originating at the vegetal plate of the embryo from mesoderm and endoderm germ layers 38. Blastocoelar cells leave the tip of the archenteron and remain localized within the blastocoel cavity where they spread and form a network of cells connected by cytoplasmic filopodia. Subsequently, they surround the gut and also localize along the skeletal rods within the arms of the pluteus larva 39. We have no evidence of Pl-gal-8 transcripts along the skeleton of the embryo, at any stage of the development. To date, very few studies have explored the role of blastocoelar cells. Their involvement in phagocytosis and the expression of innate immunity genes has been established, suggesting a function in embryonic immunity 21,40-42. In analogy with what was recently reported in the adult sea urchin, where immune response genes and proteins have been found in cells dispersed within all major organs, including the gut 43, we suggest that Pl-gal-8-expressing cells of mesodermal origin (blastocoelar cells) are probably interspersed in the larval gut, later in development (in pluteus). Galectin-8 has also pro-apoptotic activity, often involving the activation of the caspase-3 and ERK pathways 44. The expression of Pl-Gal-8 in the gut at the pluteus stage matches with the physiological high apoptotic activity observed in previous studies in gut cells 45. The finding that Pl-GAL-8 transcripts are found more concentrated around the two sphincters of the gut, probably associated to myoblasts forming the intestinal musculature, is reminiscent of a similar pattern observed by scanning electron microscopy and anti-actin immunofluorescence in S. purpuratus embryos 46. The discovery of Pl-GAL-8 in the gut might serve in future work to unravel the complex morphogenesis occurring in the sea urchin embryo developing gut, well-illustrated in a recent article reviewing ultrastructural patterns and dynamics of gene expression 47. Despite that the sea urchin genome is sequenced, the many studies at the gene level, and the complex gene regulatory networks investigated so far with great accuracy in the embryo 21, the function of many proteins expressed during development is not very well known and understood. The success in the production of biologically active recombinant proteins will allow addressing key questions related to Pl-GAL-8 involvement in cellular communication and signaling. The finding that the recombinant fusion protein is more effective than the commercially available one of human origin is also interesting for potential pharmacological and therapeutic applications. The production and exploitation of galectins in analogy to proteins currently isolated from marine animals 11, is a fast growing field in life sciences, due to the potential physiological, biological and pharmacological uses. In conclusion, this work is a contribution to the evolutionary knowledge of the galectins expressed in marine invertebrate embryos and a hint to use the recombinant Pl-GAL-8 for industrial purposes in the biomedical field. Methods Embryo culture, total RNA extraction and RT-PCR. Adult sea urchins (P. lividus) were collected from the North-Western coast of Sicily (Mediterranean Sea) and kept in aquaria with circulating seawater obtained from the collection site. Spawning was induced by intra-coelomic injection of 0.5 M KCl. After fertilization, embryos (4000/ml) were cultured in glass beakers in Millipore-filtered sea water containing antibiotics (50 mg/L streptomycin sulfate and 30 mg/L penicillin) with gentle stirring at 18 °C. Unfertilized eggs or embryos at different developmental stages were collected by low-speed centrifugation, instantly frozen in liquid nitrogen and stored at − 80 °C for subsequent RT-PCR experiments or fixed in 4% paraformaldehyde in seawater and stored at − 20 °C for whole mount in situ hybridization (WMISH) experiments as previously reported 48,49. Total RNA from approximately 4000 embryos was isolated using the Gene Elute Mammalian total RNA kit (Sigma). Residual DNA was digested by DNase I (Ambion) according to the manufacturer's instructions. Target cDNA was directly amplified from the total RNA in a one-step reaction using the SuperScript One-Step RT-PCR kit (Invitrogen), following the manufacturer's instructions. Cloning of Pl-galectin-8. We used a sequence predicted to code for a Galectin protein in the sea urchin Strongylocentrotus purpuratus database (accession number XP_781871.1) for BLAST screening against P. lividus EST databases available at NCBI and MPIMG (http://goblet.molgen.mpg.de/cgi-bin/webapps/ paracentrotus.cgi). Three overlapping P. lividus EST clones were identified and used to design specific primers (MWG, Heidelberg, Germany). Purified total RNA extracted from the gastrula stage was used to amplify by One Step RT-PCR (Invitrogen), a partial sequence of the 5 CDS region. We used a 3 RACE kit (Invitrogen) to identify the 3 -terminal end of the sequence. The amplification products were cloned in the pGEM-T-Easy Vector (Promega) and sequenced (MWG, Heidelberg, Germany). The full-length 1309nt sequence was deposited to the EMBL databank, Acc Num: FR716469. New primers were designed to obtain by RT-PCR the amplification of the complete CDS (5 -ATGGCATACCCATACCCACAAGC-3 as forward and 5 -GCACCCGAAAAATCATCCCTAC-3 as reverse), which was cloned in the pGEM-T-Easy vector (Promega) and re-sequenced for validation. The obtained recombinant plasmid was referred to as pGEM-T-Easy-Pl-galectin-8. In silico characterisation, phylogenetic analysis and structural modelling. The deduced amino acidic sequence was analysed in silico using different tools found at the servers http://web.expasy.org, http://www.cbs.dtu.dk/services/, as described previously 50. Phylogenetic analysis of the amino acidic sequence was performed by ClustalW alignment and by the Neighbor-Joining phylogenetic tree as described by 50. To spot the best local alignment among sequences we used BLAST analysis and the LALIGN program (http://www.ch.embnet.org/software/LALIGN_form.html). The Modeller software (http://salilab.org/modeller/) was used to obtain the 3D structure model of the N-terminal domain of Pl-GAL-8, based on the 2yv8 crystallographic structure of the human Galectin-8 N-terminal domain, retrieved from the protein data bank (PDB) (http://www.rcsb.org/pdb). The model is presented using the PDB Viewer program, as previously described 50. Comparative Real Time qPCR. Gene expression was measured by q-PCR with the Comparative Threshold Cycle Method and SYBR Green chemistry using the Applied Biosystems Step One Plus real time PCR cycler, following the manufacturer's instructions. cDNAs were synthesised using as templates total RNAs extracted from different stages (cleavage, blastula, gastrula, pluteus) and random hexamers, as described in the MultiScribe Reverse Transcriptase protocol (Applied Biosystems). Pl-gal-8 primers were designed using the Primer Express software (v2.0.0; Applied Biosystems, Foster City, CA, USA) to amplify a fragment of 82 bp. The primers were: 5 -AAACATGGAGCTGGCAGCAT-3 as forward and 5 -TGAGTCTCCCTGGAGTCATTCC-3 as reverse. The Ct method was used: the mean and standard deviation was calculated for each sample and the values were normalized with their respective endogenous control results to obtain the Ct values. Then, the normalized Ct values were compared to the reference sample (cleavage stage) set to 1 in arbitrary units, to obtain the relative quantity values (RQ or Ct value y-axis). The Pl-z12-1 mRNA was used as an internal endogenous reference gene 49. Whole-mount in situ hybridization. The pGEM-T-Easy-Pl-galectin-8 plasmid was used as template for the synthesis of Digoxygenin (DIG) labelled antisense and sense RNA probes. Whole-mount in situ hybridization was performed in a 96-well plate (Greiner Labortechnik, Longwood, FL, USA), using 30-40 embryos per well as previously described 49. The hybridization reactions were carried out at 62 °C, for at least 20 h. After hybridization, specimens were extensively washed and incubated with an
|
// EncryptToKeystore encrypts a secret with the given passphrase,
// using the default parameters, new random 32-byte salts, PBKDF2 as KDF, AES-128-CTR as cipher, SHA-256 as checksum.
//
// The keystore Description, Pubkey and Path fields are not initialized, and can be set by the caller.
func EncryptToKeystore(secret []byte, passphrase []byte) (*Keystore, error) {
kdfParams, err := NewPBKDF2Params()
if err != nil {
return nil, fmt.Errorf("failed to create PBKDF2 params: %w", err)
}
cipherParams, err := NewAES128CTRParams()
if err != nil {
return nil, fmt.Errorf("failed to create AES128CTR params: %w", err)
}
crypto, err := Encrypt(secret, passphrase, kdfParams, Sha256ChecksumParams, cipherParams)
if err != nil {
return nil, fmt.Errorf("failed to encrypt secret: %w", err)
}
id, err := uuid.NewUUID()
if err != nil {
return nil, fmt.Errorf("failed to generate UUID: %w", err)
}
return &Keystore{
Crypto: *crypto,
Description: "",
Pubkey: nil,
Path: "",
UUID: id,
Version: 4,
}, nil
}
|
Egypt’s change of heart on the need for dialogue between rival Fatah and Hamas during a summit it originally hosted to boost President Mahmoud Abbas of Fatah left observers scratching their heads.
"It was Israel’s refusal to make clear pledges on reviving negotiations with the Palestinians that changed every thing," well-placed sources told IslamOnline.net on Tuesday, June 26, requesting anonymity for the sensitivity of the information.
President Hosni Mubarak and Jordanian King Abdullah wanted Israeli Premier Ehud Olmert to include in his summit speech a clear framework for direct negotiations with the Palestinians.
"Olmert dug his heels promoting host Mubarak to call in his speech for dialogue between Fatah and Hamas," added the sources.
"The resumption of dialogue between all Palestinians and the achievement of a common position that speaks for them and their cause are an immediate need that can not be delayed," said the veteran Egyptian leader.
"President Abbas was caught off guard because he was hoping to ensure full isolation of rival Hamas," said the sources.
The high-profile summit in the Egyptian Red Sea resort of Sharm el-Sheikh was originally seen as an attempt to consolidate support for Abbas.
Mubarak’s call was swiftly picked up by sacked Palestinian Premier Ismail Haniyeh who said Hamas was ready to "immediately" engage in any Palestinian dialogue.
Haniyeh, who refuses to recognize Abbas’s dismissal of his unity government and the appointment of an emergency cabinet, has issued several calls for unconditional reconciliation talks with Fatah.
Abbas and his top aide have repeatedly ruled out any such possibility, describing Hamas’s takeover of Gaza Strip earlier this month as a coup against legitimacy.
Analysts attributed the sudden change of heart for Egypt, which has clearly sided with Fatah in this muscle-flexing conflict, to dissatisfaction with Israel’s hollow peace promises.
"The Egyptians discovered that Israel wanted to exploit the situation to isolate Hamas without offering any thing in return," Raed Noairat, a Palestinian analyst, told IOL.
"The Arab leaders were ready to play the game in return for a serious Israeli commitment to resuming peace negotiations, which Olmert refused to make."
The only thing Olmert pledged during the four-way summit was to "seek" his government’s approval for the release 250 Fatah detainees, out of the nearly 11,000 Palestinians currently held in Israeli prisons.
Arab leaders have recently re-launched an initiative offering Israel normal relations in exchange for its withdrawal from all land seized in the 1967 war and the creation of a Palestinian state with Al-Quds as its capital.
Israel spurned the overture as it did when it was first adopted in 2002.
Noairat said that Cairo, which earlier accused Hamas of staging a coup against Palestinian legitimacy, came to the conclusion that excluding the group serves no but Israel.
"Egypt now sees a Hamas-Fatah dialogue as the best way out of the current stalemate, at least in terms of ending months of Palestinian infighting."
|
import { Injectable } from "@angular/core";
import {
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot,
} from "@angular/router";
import { AccountService } from "./account.service";
@Injectable({
providedIn: "root",
})
export class AuthGuard implements CanActivate {
constructor(private router: Router, private accountService: AccountService) {}
// console.log(
// "this.userService.isUserLoggedIn():",
// this.accountService.isUserLoggedIn()
// );
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
const token = window.localStorage.getItem("token");
if (this.accountService.isUserLoggedIn()) {
return true;
} else {
this.router.navigate(["login"]);
return false;
}
}
}
|
The present invention relates generally to a toilet tank flapper which has a short flush and a long flush capability. More particularly, the adjustable flapper uses a moveable weight which, if activated, will temporarily reduce the turning moment arm of the flapper for ensuring a long flush.
It is a well known fact that a large use of water in most households, and in many office buildings, is for flushing toilets. Because the flushing is typically carried out with the full capacity of the water in the water tank, the water usage is often wasteful and not required; such as when flushing liquid wastes. For water conservation reasons considerable interest has been centered on designing flushing systems and mechanisms that uses a short duration flush for liquids and a longer duration flush for solids (i.e. a dual-flush toilet).
Examples of prior art dual-flush mechanisms, which afford a degree of user control over the amount of water used per flush, are U.S. Pat. Nos. 3,935,598, 4,225,987, 4,433,445, 5,129,110, 5,205,000 and 5,524,297. All of the above references, however, lack one or more necessary elements for successful wide utilization in the industry. That is, these prior art references may be prohibitively expensive, too complicated to install, maintain or operate, require the user to hold down the handle for several seconds during the flushing cycle, or may be difficult to retro-fit into existing toilets.
What is needed is a flushing mechanism or system which will provide a dual-flush capability and which does not have the above-mentioned disadvantages.
In one embodiment, a pivoting flapper valve assembly, set for a normally short flush, is provided for use in a flush tank. The flapper assembly comprises a weight, which shifts back and forth relative to the assembly""s pivot point. The assembly further comprises an actuator to trap and release the weight, resulting in either a short flush (when the weight is remote from the pivot) or a long flush (when the weight is close to the pivot). The flapper assembly is engageable through a resistance force, for selectively triggering the actuator, shifting the weight and resulting in a long flush.
More specifically, the assembly includes flush sustaining means preset to maintain the flapper assembly in the open position for a short time (i.e. a short flush). The assembly""s shifting weight, or turning moment arm shifting means, reduces the turning moment arm of the assembly when it shifts closer to the pivot, thereby causing the flush sustaining means to hold the assembly open for a longer time (i.e. long flush).
In a preferred embodiment, the moment arm shifting means comprises a longitudinal guide mounted for displacement with the assembly, a weight slidably constrained within the guide and retaining means (releasable by the resistance force) to retain the weight at the end of the guide furthest from the assembly""s pivot point. In one embodiment of the invention, the retaining means comprises a magnetic coupling device. In another embodiment, the retaining means comprises a pivoting lever mechanism.
|
Checklist of Seedplant holdings of the UBD Herbarium (UBDH), with 234 new plant records for Brunei Darussalam Here we provide a checklist of all seed plant collections (Angiosperms and Gymnosperms) present in the UBD Herbarium (UBDH). The plants are arranged in alphabetical order by family, genus and species, using the latest taxonomic classifications. UBDH contained a total of 5271 databased seed plant collections (1060 fertile, and 4211 sterile), consisting of 1386 species from 130 families. The collections covered only a limited part of Brunei Darussalam, being concentrated near the easily accessible coastal zones of Muara, Tutong and Belait, as well as near the Kuala Belalong Field Study Centre in Temburong. Because the majority of collections in UBDH came from permanent forest plots, the collections are dominated by tree families, with Dipterocarpaceae both the most collected and species rich family. We found 234 species in UBDH that were not listed in the Brunei checklist and are potentially new records for Brunei Darussalam. This would increase the known number of seed plants in Brunei by ca. 5%. The high number of new species records suggests that the Brunei seed plant flora is still incompletely known.
|
Prime Minister Narendra Modi's early morning tweet about a meeting with his mother got the attention of many trolls today. One was unexpected.
Prime Minister Narendra Modi’s early morning tweet about a meeting with his mother got the attention of many trolls today. One was unexpected. Delhi Chief Minister Arvind Kejriwal took the opportunity to hit out at the Prime Minister for allegedly using his mother for politics.
In another tweet, Kejriwal raked up the issue of Modi living separately from his wife. The Delhi CM even said it was against Hindu religion and culture to keep old mother and wife away. “Hindu religion and culture say that one should keep old mother and wife with him. PM residence is very big, make your heart a bit big,” he tweeted.
Skipped Yoga & went to meet mother. Before dawn had breakfast with her. Was great spending time together.
Prime Minister Narendra Modi has not lived with his wife for over 45 years. He is also known for maintaining a distance between his family members and his public office. However, PM Modi regularly visits his mother Heeraben to take blessings. Following the demonetisation of old Rs 1000 and Rs 500 currency notes, Modi’s 97-year-old mother Heeraben’s visit to a bank for exchanging old currency had made news and divided opinions. While many appreciated the fact the even Prime Minister’s old mother had to stand in a queue for exchanging currency notes, others like Kejriwal attacked the PM for using his mother for politics.
Incidentally, on Tuesday, Kejriwal was not the only troll as both leaders had to face the wrath of their respective trolls. Users asked as to who goes to meet his mother with cameras and boast about it on social media. PM Modi, however, didn’t share any photo of meeting with his mother today on Twitter.
|
<reponame>littlerobots/beanlib
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Little Robots
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package nl.littlerobots.bean.internal;
public interface Protocol {
int APP_MSG_RESPONSE_BIT = 0x80;
int MSG_ID_SERIAL_DATA = 0x0000;
int MSG_ID_BT_SET_ADV = 0x0500;
int MSG_ID_BT_SET_CONN = 0x0502;
int MSG_ID_BT_SET_LOCAL_NAME = 0x0504;
int MSG_ID_BT_SET_PIN = 0x0506;
int MSG_ID_BT_SET_TX_PWR = 0x0508;
int MSG_ID_BT_GET_CONFIG = 0x0510;
int MSG_ID_BT_SET_CONFIG = 0x0511;
int MSG_ID_BT_SET_CONFIG_NOSAVE = 0x0540;
int MSG_ID_BT_END_GATE = 0x0550;
int MSG_ID_BT_ADV_ONOFF = 0x0512;
int MSG_ID_BT_SET_SCRATCH = 0x0514;
int MSG_ID_BT_GET_SCRATCH = 0x0515;
int MSG_ID_BT_RESTART = 0x0520;
int MSG_ID_BL_CMD_START = 0x1000;
int MSG_ID_BL_FW_BLOCK = 0x1001;
int MSG_ID_BL_STATUS = 0x1002;
int MSG_ID_BL_GET_META = 0x1003;
int MSG_ID_CC_LED_WRITE = 0x2000;
int MSG_ID_CC_LED_WRITE_ALL = 0x2001;
int MSG_ID_CC_LED_READ_ALL = 0x2002;
int MSG_ID_CC_ACCEL_READ = 0x2010;
int MSG_ID_CC_TEMP_READ = 0x2011;
int MSG_ID_CC_BATT_READ = 0x2015;
int MSG_ID_CC_POWER_ARDUINO = 0x2020;
int MSG_ID_CC_GET_AR_POWER = 0x2021;
int MSG_ID_CC_ACCEL_GET_RANGE = 0x2030;
int MSG_ID_CC_ACCEL_SET_RANGE = 0x2035;
int MSG_ID_AR_SLEEP = 0x3000;
int MSG_ID_ERROR_CC = 0x4000;
int MSG_ID_DB_LOOPBACK = 0xFE00;
int MSG_ID_DB_COUNTER = 0xFE01;
int MSG_ID_DB_E2E_LOOPBACK = 0xFE02;
int MSG_ID_DB_PTM = 0xFE03;
}
|
Police are appealing for help to catch a hapless crook who tried to rob a fish and chip shop with what appeared to be a banana.
The masked raider burst into the takeaway and pointed the 'gun' at staff while he screamed 'open that f***ing till now'.
But the makeshift weapon actually seemed to be nothing more than a piece of curved fruit concealed in a plastic bag.
CCTV then shows him fumbling in his pocket to try and pull out another weapon - but he failed and then fled the takeaway empty-handed.
A video clip released by Greater Manchester Police shows an offender trying to rob a fish and chip shop with a camouflaged weapon - believed to be a banana
He is seen screaming at the staff to 'open the f***ing till' but the workers stand firm
Police have released footage of the raid in Atherton, Greater Manchester - prompting online debate about what weapon was used.
One person said: 'He just robbed that shop with a banana wrapped in a plastic bag.'
Another added: 'The fool is waving a aubergine in a plastic bag about?'
One even wrote: 'He looks like he's holding a d**** wrapped in a plastic bag.'
The incident happened at the shop in Leigh Road, Atherton, at around 8.45pm on Saturday, February 11.
Detective sergeant David Johnston, of Greater Manchester Police's Wigan borough division, said: 'I am appealing for information about this terrifying incident, which put these people's safety in danger, all for petty cash from a till.'
He can be seen attempting to draw another weapon from his pocket before fleeing the premises in Atherton, Wigan
Police were called to reports at around 8.45pm on Saturday 11 February that a man had entered the shop on Leigh Road, Howe Bridge, and threatened staff with a concealed weapon
The offender is described as white, around 6ft tall and of a slim build.
He was wearing a blue jumper with a black hooded jacket underneath and had black material covering most of his face.
DS Johnson added: 'If anyone recognises the man in the CCTV footage, or has any other information that may help us, then I urge you to get in touch.'
Anyone with information should contact police on 0161 856 7292 or the independent charity Crimestoppers, anonymously, on 0800 555 111.
|
CAPE CORAL, Fla. (AP) — A southwest Florida man has been sentenced to life in prison for killing his father and then dismembering the body.
The News-Press reports that 34-year-old Matthew Marshall was sentenced Monday. He was convicted last month of second-degree murder, abuse of a body and tampering with evidence.
James Marshall went missing in February, and his torso was discovered in woods near his Cape Coral home several days later. Several weeks later, a suitcase containing his limbs was discovered in a nearby canal. Matthew Marshall was arrested in May.
Police found Marshall had tried to use his father’s credit card to pay for a bar tab after he had been reported missing.
|
<reponame>SahaginOrg/sahagin-java
package org.sahagin.share;
// Thrown when test scripts written by user have problems.
// (Maybe users should correct the test script mistakes)
public class IllegalTestScriptException extends Exception {
private static final long serialVersionUID = 1L;
public IllegalTestScriptException(String message) {
super(message);
}
public IllegalTestScriptException(String message, Throwable cause) {
super(message, cause);
}
public IllegalTestScriptException(Throwable cause) {
super(cause);
}
}
|
import { ElementRef, Renderer2, OnInit } from '@angular/core';
export declare class MdbTableScrollDirective implements OnInit {
private renderer;
private el;
scrollY: boolean;
maxHeight: any;
scrollX: boolean;
maxWidth: any;
constructor(renderer: Renderer2, el: ElementRef);
wrapTableWithVerticalScrollingWrapper(tableWrapper: ElementRef): void;
wrapTableWithHorizontalScrollingWrapper(tableWrapper: ElementRef): void;
wrapTableWithHorizontalAndVerticalScrollingWrapper(tableWrapper: ElementRef): void;
ngOnInit(): void;
}
|
Alternatives and Incommensurables: The Case of Darwin and Kelvin If, as it is usually understood, incommensurable theories must be compatible then one need never choose between two such theories. But if theories were incompatible and incommensurable one would have to choose between them. What if they are incompatible only outside the domain of observation? The fact that Darwin's biology can clash with Kelvin's physics (each with their respective auxiliary assumptions) regarding the age of the earth shows how commensurable theories may yet be incompatible. But it also shows that they need not be alternatives--i.e. that one may not be able to simply and satisfactorily replace the other in our world view. But standard examples of scientific revolutions consist of the replacement of one theory by another in one's world view. These alternative theories must therefore be more than merely incompatible--what do they share if not content? (I.e. they must be commensurable.)
|
<reponame>yuwentao/seckill
/*
* Copyright 2017 Huawei Technologies 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.
*/
package io.servicecomb.poc.demo.seckill;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import io.servicecomb.poc.demo.CommandServiceApplication;
import io.servicecomb.poc.demo.seckill.dto.CouponDto;
import io.servicecomb.poc.demo.seckill.entities.PromotionEntity;
import io.servicecomb.poc.demo.seckill.json.JacksonGeneralFormat;
import io.servicecomb.poc.demo.seckill.repositories.spring.SpringPromotionRepository;
import io.servicecomb.poc.demo.seckill.web.SecKillCommandRestController;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CommandServiceApplication.class)
@WebAppConfiguration
public class SecKillPromotionBootstrapTest {
private final Format format = new JacksonGeneralFormat();
private MockMvc mockMvc;
@Autowired
private SecKillCommandRestController controller;
@Autowired
private SpringPromotionRepository promotionRepository;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(controller).setHandlerExceptionResolvers(withExceptionControllerAdvice())
.build();
promotionRepository.deleteAll();
}
@Test
public void testPromotionStartedWhenPublishTimeReach() throws Exception {
int waitTime = 1000;
PromotionEntity delayPromotion = new PromotionEntity(new Date(System.currentTimeMillis() + waitTime), 5, 0.8f);
promotionRepository.save(delayPromotion);
mockMvc.perform(post("/command/coupons/").contentType(APPLICATION_JSON)
.content(format.serialize(new CouponDto(delayPromotion.getPromotionId(), "zyy"))))
.andExpect(status().isBadRequest()).andExpect(content().string(containsString("Invalid promotion")));
Thread.sleep(waitTime + 1000);
mockMvc.perform(post("/command/coupons/").contentType(APPLICATION_JSON)
.content(format.serialize(new CouponDto(delayPromotion.getPromotionId(), "zyy"))))
.andExpect(status().isOk()).andExpect(content().string("Request accepted"));
}
private ExceptionHandlerExceptionResolver withExceptionControllerAdvice() {
final ExceptionHandlerExceptionResolver exceptionResolver = new InvocationExceptionHandlerExceptionResolver();
exceptionResolver.afterPropertiesSet();
return exceptionResolver;
}
}
|
import sqlite3
conn = sqlite3.connect('main.db')
cursour = conn.cursor()
cursour.execute("CREATE TABLE IF NOT EXISTS login(username VARCHAR, password VARCHAR)")
cursour.execute("INSERT INTO login VALUES('malli', 'Malli2010')")
cursour.execute("INSERT INTO login VALUES('nesh', '12')")
conn.commit()
|
Rapidly growing mycobacterial infections after pedicures. BACKGROUND Rapidly growing mycobacteria (RGM) can cause a variety of cutaneous and systemic diseases. The causative organisms are typically Mycobacterium fortuitum or Mycobacterium chelonae (also known as Mycobacterium abscessus). Primary cutaneous lesions may develop after a variable latent period, from weeks to several months, and usually result from direct inoculation after trauma, from injections, or during surgery via contaminated medical instruments. Recently, investigators from the Centers for Disease Control and Prevention, Atlanta, Ga, and the California Department of Health Services, Berkeley, documented a large, unprecedented outbreak of community-acquired RGM infection, during which more than 100 patrons of a northern California nail salon contracted furunculosis in their legs as a result of exposure to whirlpool footbaths that were contaminated with M fortuitum. OBSERVATIONS We report the clinical and epidemiological findings in 3 cases of lower extremity RGM infections that occurred after similar whirlpool footbath exposure at several different nail salons in southern California. These infections typically presented as recurrent furunculosis, causing considerable morbidity as a result of scarring, delayed diagnosis, and the need for long-term polymicrobial therapy. CONCLUSIONS Rapidly growing mycobacterial infections related to pedicures may continue to occur in a sporadic fashion. Clinicians should consider the possibility of RGM infection and inquire about recent pedicures in a patient with recurrent lower extremity furunculosis and abscesses that are unresponsive to conventional antibiotic therapy.
|
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
left = 0
right = 0
# window = {}
window = collections.defaultdict(int)
ans = 0
while right < len(s):
c = s[right]
# window[c] = window.get(c, 0) + 1
window[c] += 1
right += 1
while len(window) > k:
d = s[left]
window[d] -= 1
if window[d] == 0:
del window[d]
left += 1
ans = max(ans, right-left)
return ans
|
14-Year Oil Spill In The Gulf Of Mexico Could Go On For Decades The U.S. Coast Guard is trying to clean up an oil spill in the Gulf of Mexico that's been going on since 2004 when a hurricane toppled a rig owned by Taylor Energy, a New Orleans-based firm.
The U.S. Coast Guard is trying to clean up an oil spill in the Gulf of Mexico that's been going on since 2004 when a hurricane toppled a rig owned by Taylor Energy, a New Orleans-based firm.
How long does it take to stop an oil spill? In the Gulf of Mexico, the nation's longest offshore oil spill has been leaking for more than 14 years. There is still no solution in sight. Now the Coast Guard is stepping in to try to clean it up. Tegan Wendland of member station WWNO and NPR's Energy and Environment team, reports.
TEGAN WENDLAND, BYLINE: On a windy spring day, I set out on a tiny fishing boat with the captain and a scientist. Giant waves toss us around.
MACDONALD: ...To the challenging ocean conditions.
WENDLAND: I'm trying not to throw up, but Ian MacDonald is unfazed by the 6-foot waves. He's a scientist at Florida State University, where he studies oil spills.
The fumes hit us first. The smell is overwhelming. And then we see it. It's not a black, sticky slick but a glossy layer that stretches for miles.
MACDONALD: Here is some coming up. See how it's all rainbow sheen there? So that's oil.
WENDLAND: Way back in 2004, powerful Hurricane Ivan toppled an oil rig into the Gulf. It was owned by Taylor Energy, a New Orleans-based company, which managed to plug some of the 25 broken pipes. But the leak didn't stop.
Jonathan Henderson runs an environmental nonprofit called Vanishing Earth and worries about the impact on marine life.
JONATHAN HENDERSON: Everything that lives and breathes in the Gulf of Mexico travels back and forth through that zone - fish and the sea birds and the sea turtles and the dolphins.
WENDLAND: The government is studying this, but it's hard. They can't even figure out exactly how much is leaking. Neither can the company. Henderson's been trying to monitor it himself, doing regular flyovers and reporting what he sees.
HENDERSON: I don't see why, if it's going to continue to leak, that they can't recover some of this oil. I mean, if we can put a man on the moon, we can figure out how to, like, grab oil that's coming up from the seafloor and 400 feet of water.
WENDLAND: The Department of the Interior and the Coast Guard have been working with the company to try to stop the leak for years, but it's a major engineering challenge. The wells were buried under hundreds of feet of mud in an underwater mudslide, which are common in this area where the murky Mississippi dumps into the Gulf. Ed Richards is a law professor at Louisiana State University.
ED RICHARDS: This is a well-known high-risk area. You have a whole huge amount of unconsolidated sediment coming out of the river basically piling up.
WENDLAND: He says the situation raises questions.
RICHARDS: Should they have been there? Should they have built the rig the way they built it? Should it have been permitted that way?
WENDLAND: And Taylor Energy's not the only company that built there. There are many rigs in the area. The company has spent about $500 million to try and stop the spill, and it's paying for pilots to fly over and monitor it. The companies reported less than a barrel of oil a day on the surface. But scientist MacDonald calculates that more than a hundred barrels a day are spilling into the Gulf. He says the whole situation should serve as a warning to regulators as they attempt to expand oil and gas drilling in the Atlantic, where underwater canyons pose a threat.
MACDONALD: So the idea that we would be building in deep water and making pipelines going back to land in an area that's susceptible to those kinds of accidents is something that we should take into account as we do our planning.
WENDLAND: And do you think we are?
WENDLAND: The Trump administration has rolled back offshore safety rules even as it works to open up more areas to drilling.
Back out in the Gulf, a giant ship looms in the distance - contractors hired by the Coast Guard to drop a giant metal dome over the wells and collect the oil. Taylor Energy says this could just make it worse, so it's suing the Coast Guard. Neither the government nor the company agreed to go on record, saying litigation is ongoing. MacDonald remains hopeful.
MACDONALD: I'm really glad to be out here and being able to see this operation because it's been a long time coming, and there's a lot riding on it.
WENDLAND: But in the end, he says, it might be that no one is able to stop the oil from bubbling up into the Gulf. If that's the case, according to government estimates, the leak could go on for a hundred more years.
For NPR News, I'm Tegan Wendland, in Port Eads, La.
|
/* normalises using "loga" two fixed-point promotion technique. */
double impact_normalise(double impact, double norm_B, double slope,
double max_impact, double min_impact) {
double norm_impact;
norm_impact = min_impact + (min_impact * (log10(impact / min_impact)
/ log10(norm_B)));
norm_impact = (1.0 - slope) * norm_impact + (slope * impact);
if (norm_impact < min_impact)
norm_impact = min_impact;
else if (norm_impact > max_impact)
norm_impact = max_impact;
return norm_impact;
}
|
. OBJECTIVE To investigate the influence and significance of gastric bypass surgery on hepatic gluconeogenesis in type 2 diabetic Goto Kakizaki(GK) rats. METHODS Forty GK rats were randomly divided into Roux-en-Y gastric bypass group(group A) and sham operation group(group B). Differences in glucose tolerance experiment(OGTT) at preoperative and postoperative 1, 2 and 4 weeks were compared and weight was recorded. Glycated hemoglobin levels were measured preoperatively and 4 weeks postoperatively. The animals were sacrificed 4 weeks after surgery and liver tissues were harvested to detect the relative expression of mRNA and protein of glucose 6 phosphatase(G-6-P) and phosphoenol pyruvate kinase(PEPCK) with RT-PCR and Western blot. RESULTS Fasting blood glucose levels were 6.5, 4.9, and 4.7 mmol/L in group A, and were 10.3, 10.4, and 12.5 mmol/L in group B, and the differences between two groups were statistically significant(P<0.05). The blood glucose level at 2 h after stomach lavage were 8.3, 6.4 and 5.5 mmol/L in group A, and were 21.4, 23.8 and 24.7 mmol/L in group B at postoperative 1, 2, 4 weeks, and the differences between two groups were statistically significant(P<0.05). The glycosylated hemoglobin at postoperative 4 weeks was(6.8±1.0)%, significantly lower than that in group B. Hepatic G-6-P and PEPCK mRNA relative expression at postoperative 4 weeks was reduced by 21.0% and 25.9% respectively as compared to group B, and the protein expression reduced as well. Immunohistochemistry showed that hepatic glycogen sedimentary in group A increased significantly. CONCLUSION The relative mRNA and protein level of key enzymes of hepatic gluconeogenesis are significantly decreased after Roux-en-Y gastric bypass surgery and hepatic gluconeogenesis is reduced, which may be a potential mechanism of the decrease of blood glucose.
|
<filename>src/main/java/com/jason/zero/utils/OSInfo.java
package com.jason.zero.utils;
import com.jason.zero.enums.EPlatform;
/**
* All rights Reserved, Designed By www.maihaoche.com
* 操作系统类:获取System.getProperty("os.name")对应的操作系统
*
* @author 文远
* @version 0.0.1
* @since 0.0.1
*/
public class OSInfo {
private static String OS = System.getProperty("os.name").toLowerCase();
private static OSInfo instance = new OSInfo();
private EPlatform platform;
private OSInfo() {}
/**
* Is linux boolean.
*
* @return the boolean
*/
public static boolean isLinux() {
return OS.contains("linux");
}
/**
* Is mac os boolean.
*
* @return the boolean
*/
public static boolean isMacOS() {
return OS.contains("mac") && OS.contains("os") && !OS.contains("x");
}
/**
* Is mac osx boolean.
*
* @return the boolean
*/
public static boolean isMacOSX() {
return OS.contains("mac") && OS.contains("os") && OS.contains("x");
}
/**
* Is windows boolean.
*
* @return the boolean
*/
public static boolean isWindows() {
return OS.contains("windows");
}
private static boolean isOS2() {
return OS.contains("os/2");
}
private static boolean isSolaris() {
return OS.contains("solaris");
}
private static boolean isSunOS() {
return OS.contains("sunos");
}
private static boolean isMPEiX() {
return OS.contains("mpe/ix");
}
private static boolean isHPUX() {
return OS.contains("hp-ux");
}
private static boolean isAix() {
return OS.contains("aix");
}
private static boolean isOS390() {
return OS.contains("os/390");
}
private static boolean isFreeBSD() {
return OS.contains("freebsd");
}
private static boolean isIrix() {
return OS.contains("irix");
}
private static boolean isDigitalUnix() {
return OS.contains("digital") && OS.contains("unix");
}
private static boolean isNetWare() {
return OS.contains("netware");
}
private static boolean isOSF1() {
return OS.contains("osf1");
}
private static boolean isOpenVMS() {
return OS.contains("openvms");
}
/**
* 获取操作系统名字
* @return 操作系统名
*/
private static EPlatform getOSname() {
if (isAix()) {
instance.platform = EPlatform.AIX;
} else if (isDigitalUnix()) {
instance.platform = EPlatform.Digital_Unix;
} else if (isFreeBSD()) {
instance.platform = EPlatform.FreeBSD;
} else if (isHPUX()) {
instance.platform = EPlatform.HP_UX;
} else if (isIrix()) {
instance.platform = EPlatform.Irix;
} else if (isLinux()) {
instance.platform = EPlatform.Linux;
} else if (isMacOS()) {
instance.platform = EPlatform.Mac_OS;
} else if (isMacOSX()) {
instance.platform = EPlatform.Mac_OS_X;
} else if (isMPEiX()) {
instance.platform = EPlatform.MPEiX;
} else if (isNetWare()) {
instance.platform = EPlatform.NetWare_411;
} else if (isOpenVMS()) {
instance.platform = EPlatform.OpenVMS;
} else if (isOS2()) {
instance.platform = EPlatform.OS2;
} else if (isOS390()) {
instance.platform = EPlatform.OS390;
} else if (isOSF1()) {
instance.platform = EPlatform.OSF1;
} else if (isSolaris()) {
instance.platform = EPlatform.Solaris;
} else if (isSunOS()) {
instance.platform = EPlatform.SunOS;
} else if (isWindows()) {
instance.platform = EPlatform.Windows;
} else {
instance.platform = EPlatform.Others;
}
return instance.platform;
}
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
System.out.println(OSInfo.getOSname());
}
}
|
Herpesvirus infection of the respiratory tract in patients with alcoholic hepatitis. Respiratory herpesvirus infections have rarely been described in alcoholics. We report four cases of severe respiratory herpesvirus infections in patients with alcoholic liver disease. Two were related to Herpes Simplex Virus and two to Cytomegalovirus. Both chronic alcoholism and severe liver disease induce immunosuppression, which might account for these unusual herpesvirus infections of the respiratory tract. These cases suggest that infections with herpesviruses should be considered in patients with alcoholic liver disease and pulmonary or tracheobronchial disease unresponsive to standard antibiotic therapy. Bronchoscopy, viral culture, and serological tests appear warranted, particularly given the existence of specific therapy.
|
Varun Dhawan and Alia Bhatt made their debut in Karan Johar directorial Student Of The Year. Since their debut, they have starred in three films together including Humpty Sharma Ki Dulhania and Badrinath Ki Dulhania. They are all set for their fourth collaboration which is Abhishek Varman’s upcoming period drama, Kalank. The first teaser of the highly awaited film was unveiled earlier this month in which the two stars create magic in their never-before-seen avatars.
Today, Varun Dhawan and Alia Bhatt launched their second song ‘First Class’ which stars Varun and Kiara Advani in a guest appearance. The launch took place at Gaeity Galaxy in Mumbai amid massive fanfare. The actors took over the balcony section where they entertained the awaiting fans. At the launch, Alia Bhatt enthralled the audience with her graceful performance on ‘Ghar More Pardesiya’ whereas Varun set the stage on fire with ‘First Class’ performance. In the end, he lifted Alia in his arms recreating Badrinath Ki Dulhania pose again.
Kalank cast includes Aditya Roy Kapur, Sonakshi Sinha, Sanjay Dutt, Madhuri Dixit. Set in the 1940s, presented by Fox Star Studios, Kalank, produced by Dharma Productions and Nadiadwala Grandson Entertainment, will release on April 17.
Adam Sandler Is Suddenly Dressing Age Appropriate!
|
// Hash generates a SHA256 HMAC hash from a byte array
func (h *HmacSha256) Hash(d []byte) []byte {
hash := hmac.New(sha256.New, []byte(h.secret))
hash.Write(d)
return hash.Sum(nil)
}
|
def expand_include(include, current_file, is_quote):
if is_quote:
search_path = [os.path.dirname(current_file)] + include_dirs
else:
search_path = include_dirs
for include_dir in search_path:
candidate = os.path.join(include_dir, include)
if os.path.exists(candidate):
with open(candidate, "r") as inf:
candidate_text = inf.read()
if not candidate_text.endswith("\n"):
candidate_text += "\n"
def expand_include_match(match):
char, body = match.groups()
return expand_include(
body,
candidate,
char == '"',
)
return include_pat.sub(expand_include_match, candidate_text)
raise PreprocessException(
"%s : fatal error: Cannot open include file: '%s'"
% (current_file, include)
)
|
Need to catch up fast on everything that has happened on Game of Thrones, seasons one through four? No problem.
DirectTV has launched “The Kingsroadmap,” which summarizes every major event throughout the Game of Thrones series. Scroll over a section, say Winterfell for the Starks, or King’s Landing for everything Lannister. Using the navigation at the bottom, users can select the episode they want a Cliff’s Notes-like update on, then hit the arrows to the right to read each family’s storyline for that episode.
As season five launches this Sunday on HBO, the map will be updated with those new episode recaps as well. Have fun with it!
|
Electric and so-called “hybrid-electric” vehicles store electrical power in an electric power storage, such as a battery. The electric power is used by the vehicle to be converted into useful work, such as by powering electric motors that are connected to the vehicle's wheels. In these hybrid-electric vehicles, a combustion engine, such as a petrol or diesel engine rotates an electric generator that produces electric power, is stored in a battery for powering one or more electric motor(s). The electric power in electric and hybrid-electric vehicles may also be generated using other means such as regenerative braking, which converts the energy dissipated during the braking and slowing down of the vehicle into electric energy for example.
The electric vehicle (EV), which lacks an independently fueled engine, relies on an external power source to provide the energy stored in the battery. The electric vehicle therefore includes a charging plug receptacle that allows a vehicle operator to couple the vehicle to a utility-grid connected electric circuit. Electrical power is transferred from the utility-grid connected electric circuit to the vehicle for charging or charging the batteries. A third type of vehicle, a so-called plug-in hybrid electric (“PHEV”) includes an engine for generating power during operation, but also incorporates a charging plug receptacle to allow charging the battery when the vehicle is not in use.
|
Oracle To Report Near-Flat YoY Earnings?
Oracle Corporation (NYSE: ORCL) will report its fourth quarter financial results on Wednesday afternoon, after the market closes.
While the company guided slight earnings growth to $0.93 per share (up from $0.92 per share reported a year ago), the crowd and Wall Street analysts are expecting to see a small decline in earnings.
According to Estimize, the crowd is projecting consensus earnings of $0.91 per share on revenue of $11.165 billion, versus $11.326 billion reported a year ago.
The Street is the most bearish, and models consensus earnings of $0.87 per share on revenue of $10.943 billion.
It is also interesting to see how sentiment has evolved over time; both the Street and the crowd have become increasingly bearish as the reporting date has come closer.
In a report published Monday, Wunderlich analyst Robert Breza previewed Oracle’s results, reiterating a Hold rating and price target of $47.00 on the stock.
The firm expects the tech company to deliver earnings and revenue at the high-end of the guidance, above consensus estimates.
|
What began as a seemingly routine government intervention into a small number of failing banks has grown into a corruption scandal in Venezuela which has claimed the political career of one of President Hugo Chavez's most trusted aides.
When Jesse Chacon, the Science and Technology Minister, handed in his resignation to Mr Chavez on Sunday after his brother, Arne Chacon, was arrested over the banking scandal, it must have sent shockwaves through the upper echelons of the Venezuelan government.
After all, Jesse Chacon had been a close ally to Hugo Chavez for almost 20 years, even going to prison with him for taking part in a failed coup in 1992.
Many Venezuelans were left wondering if a man like Mr Chacon was to leave government over the affair, who else could be involved?
First it is worth rewinding a little to explain how this situation arose.
On 20 November, the government took over four banks, including Banco Canarias and ProVivienda, which were accused of providing loans to companies in which the banks' directors were major shareholders.
As the questions began to mount up, one man emerged as key: a hitherto unknown businessman called Ricardo Fernandez Barrueco.
Mr Fernandez had amassed a fortune through supplying food to the government's subsidized supermarkets.
He led a group of investors in buying Banco Canarias allegedly using depositors' funds and public money.
Mr Fernandez is currently under arrest and awaiting trial, as is his lawyer and his lawyer's daughter, who are accused of facilitating the illegal transactions.
As Banco Canarias customers began to queue outside the branches to withdrawal their savings, the investigation then widened.
Three more banks passed into state hands for similar irregularities.
One of them was the development bank, Banco Real. Its president was Arne Chacon, brother of the Science and Technology minister, Jesse.
The opposition parties say the whole tangled web of associations, family relationships and apparent white collar crime reveals something they have claimed for some time: that a culture of cronyism, known as the "Boli-burgesia", exists in the heart of the Chavez government.
"The 'Boli-burgesia' is a summary of two words: bourgeoisie and Bolivarian," says Teodoro Petkoff, newspaper editor and vocal critic of President Chavez.
"It refers to a rich elite created through corruption, through illegal links with the Bolivarian government of Hugo Chavez.
"It's a word we Venezuelans have invented to mean a corrupt businessman linked to this government."
For Mr Petkoff, Ricardo Fernandez and the ex-minister's brother, Arne Chachon, are prime examples of "boli-burgeses".
"Ten years ago, Ricardo Fernandez was a modest businessman," says Mr Petkoff.
"But through his government contacts, he has obtained a series of contracts with the state which have allowed him to make a great deal of money.
"He now owns a transport company, a company producing maize flour for the government-run supermarkets, a flotilla of fishing boats, and four banks.
"He's a man who has been transformed into a magnate by his relationship with a supposedly socialist government."
Several opposition figures, including Mr Petkoff, have publically said that one of Ricardo Fernandez's main government contacts was President Chavez's own brother, Adan Chavez, who is governor of their home state of Barinas.
Adan Chavez denies knowing Mr Fernandez and is not under investigation over the scandal.
Either way, most analysts agree that the banking scandal in Venezuela isn't over yet.
There are still more than 25 arrest warrants out, on top of the eight bankers already detained.
The process of returning the depositors their savings has begun using the recently nationalised Bank of Venezuela as well as a number of private institutions.
But what has the episode done to the banking sector in Venezuela in the long term?
"The biggest damage has been to confidence," says economist, Jose Guerra.
"At first you say you're going to take over four banks, and that the process is going to be open and transparent.
"Then a few days later you announce you're taking over three more, but that now it will take place behind closed doors.
"What do you expect will happen when you then tell customers to have confidence in the security of their deposits?"
People are demanding a great deal of cash as they seek to recoup their savings, Mr Guerra says, something which could hurt the liquidity of the system as a whole.
But the real damage of the crisis is probably more political than economic.
With elections for the national assembly due next year, it still isn't clear how the scandal could affect President Chavez and his United Socialist Party candidates.
The government says they have acted swiftly. The main culprits have been arrested, President Chavez said on national television, and the worst of the crisis is over.
But for former Central Bank economist, Jose Guerra, there are still serious questions to be answered about the way in which the purchase and sale of these banks was carried out using public funds.
"How is it possible that three billion dollars of public money was deposited in these banks in just two days?" he asks.
"Who are the state officials who allowed such transactions to happen? There must be a group of state officials who knew what was happening."
|
package com.rakovpublic.jneuropallium.worker.net.study;
import com.rakovpublic.jneuropallium.worker.net.signals.ISignal;
import java.io.Serializable;
import java.util.List;
public interface IObjectStudyingAlgo extends IStudyingAlgo, Serializable {
/**
* this method return signals for study
*/
List<ISignal> getStudyingSignals();
}
|
Some articles on Diary of the Evans-Crittens, www.evans-crittens.com may contain affiliate links. Click here to read my disclosure policy.
Quentin Blake: Inside Stories celebrates the work of one of the world’s most important and best-loved illustrators. Best known for his illustrations in the books of Roald Dahl, Quentin Blake’s work is recognised worldwide. The kids and I are huge fans so just had to visit this special exhibition at the National Museum Cardiff.
There is parking situated behind the museum, off Museum Avenue (CF10 3NP). It costs £6.50 and you can purchase an exit token from the Museum Shop. As we were also visiting other places in Cardiff I parked in the on street parking in St Andrew’s Crescent (CF10 3DD). During the short walk to the museum, we looked for Pokemon and also ladybirds and caterpillars (yes, kids really can be into both the natural and the digital World). I find Pokemon Go useful for the the kids learning names of important landmarks in the new places we visit.
Entry into the National Museum is free. The museum is open Tuesday–Sunday, 10am–5pm (Galleries close at 4.45pm).
We made our way straight to the Inside Stories exhibition.
Four year old Isabelle asked if this was a statue of Quentin Blake. (sorry Mr Blake). It is actually a bust of William Adams, a mining engineer and one of the first members of Cardiff’s Naturalist’s Society by Edward Onslow Ford (1852 – 1901).
I also had to take a photo of the girls by this vase just to show the sheer size of it.
Illustration © Quentin Blake
Then it was time to enter Quentin Blake: Inside stories. Due to copyright issues there is no photography allowed in the exhibition but this understandable and it’s really one of
those exhibitions that is best seen in person anyway.
Illustration © Quentin Blake
As we walked into the gallery it felt like stepping into a book illustrated by Quentin Blake. There are huge illustrations and quotes painted directly onto the walls as well as the original first roughs, storyboards and finished artwork framed around the room.
Illustration © Quentin Blake
As we walked around, Izzy took in the art work while I read her the blurbs about each piece. This exhibition gives a unique insight into the origins of some of Blake’s most iconic and popular creations, ranging from his illustrations in Roald Dahl’s The Twits and Danny the Champion of the World, to his own Clown, The Boy in The Dress by David Walliams and illustrations in books by John Yeoman, Russell Hoban and Michael Rosen.
My favourite parts were seeing the illustrations from my most read books, such as Matilda, but it was interesting to be introduced to new (to me) work too. Despite being a fan of Michael Rosen’s writing I have somehow missed reading Sad Book. I was in tears reading this text which chronicles Rosen’s grief at the death of his son Eddie. A moving combination of sincerity and simplicity, it acknowledges that sadness is not always avoidable or reasonable and perfects the art of making complicated feelings plain. It wasn’t made like any other book either; Michael Rosen said of the text, ” I wrote it at a moment of extreme feeling and it went straight down onto the page … Quentin didn’t illustrate it, he ‘realised’ it. He turned the text into a book and as a result showed me back to myself. No writer could ask and get more than that.” And Quentin Blake says that the picture of Michael “being sad but trying to look happy” is the most difficult drawing he’s ever done… “a moving experience.” I have since ordered a copy of this book.
There is also a video installation that the girls enjoyed watching while sitting opposite each other wearing headphones (I really wanted to take a photo of them but didn’t want to get in trouble!). It was great seeing Quentin Blake at work drawing these iconic illustrations.
As well as being a nostalgic exhibition seeing these illustrations from our favourite childhood books it was also educational and inspirational for any aspiring story writers and illustrators.
My kids couldn’t wait for their turn on the drawing table to create their own piece of art to take pride of place in the exhibition.
I double checked and I was allowed to take photos of my kids and their own illustrations (I would have felt sad leaving their pictures there otherwise).
Rebecca drew Matilda, here it is hung up by Blake’s birds.
Isabelle drew some flowers. I admired their work before it was possibly covered with someone else’s new artwork.
We had a great time at this free exhibition and I would highly recommend it for children and adults alike.
Quentin Blake: Inside Stories is a touring exhibition, which was co-curated by Quentin Blake and Claudia Zeff for the opening of House of Illustration, the UK’s centre for the art of illustration.
The exhibition at National Museum Cardiff is supported by the Welsh Government and forms part the Roald Dahl 100 Wales celebrations taking place throughout 2016.
In addition to this exhibition, there are Family Workshops taking place between 2-4 August and an Art Lunchtime Talk taking place on 9 September.
Quentin Blake: Inside Stories is at National Museum Cardiff until Sunday 9th November.
Find more special events in honour of Roald Dahl’s birthday on the RoaldDahl100 site- we’re looking forward to The Wondercrump World of Roald Dahl tour at Wales Millennium Centre which opens this August.
We combined our visit to the National Museum Cardiff with a show at the nearby Sherman Theatre.
Quentin Blake “Inside Stories” will be at Laing Art Gallery from 11th March to 8th July 2017.
|
Relatively recently, mobile telephones have been configured to support voice communications as well as applications that require receipt and transmittal of data by way of a network connection. For example, currently mobile telephones are equipped with applications that support text messaging, e-mailing, instant messaging, web browsing, and the like. Furthermore, cellular networks are continuously being updated to support applications executing on mobile computing devices that request relatively large amounts of data at a relatively high throughput rate. For example, mobile telephones are being configured to execute applications for streaming high definition video for presentation to a user on a display of the mobile computing device. Similarly, mobile computing devices can be configured to execute gaming applications, wherein a user of a first mobile computing device is participating in a game with a user of a second mobile computing device in real-time, thereby requiring a relatively large amount of data to be transmitted by way of a cellular network to each of the mobile computing devices.
While processing capabilities, display resolution, chipsets, and other hardware of mobile computing devices has evolved to support applications that consume a relatively large amount of data, such applications also tend to consume a relatedly large amount of energy from batteries that charge the mobile computing devices. For example, if a user is watching a high-definition video on a mobile computing device, a battery that powers such mobile computing device may discharge all of its energy within a few hours. An exemplary protocol that has been employed by manufacturers of mobile computing devices to reduce an amount of energy consumed thereby when communicating with a base station in a cellular network is referred to as fast dormancy. Generally, this protocol allows a wireless radio to be relatively quickly (e.g., 1-3 seconds) placed into an idle state when there is no data being transferred between the mobile computing device and the base station. In current mobile computing devices, however, fast dormancy fails to extend the battery life when a user is uploading or downloading relatively large amounts of data, such as watching high definition video by way of the mobile computing device.
|
The bad news for RIM: it lost nearly $200 million (adjusted) last quarter. The worse news: it's now letting 5,000 employees go, on top of the 2,000 cuts that had been previously announced. The very worst news: its BB10 operating system—and last hope for relevance—has been pushed back until next year.
This is an unmitigated disaster.
Look, companies lose money all the time. It's rough economy, a competitive space. It happens. But what's crucial during times like that is to have a clear way out. The only chance RIM had at surviving as a standalone company was for BB10—which remains promising, if not revolutionary—to lead a BlackBerry renaissance. Waiting until this fall, as had been previously indicated, was pushing it. Waiting until 2013 is suicidal.
Then combine that with the revelation that RIM's cutting 5,000 jobs, making 7,000 total in the last two months. Add in net income losses in the hundreds of millions, revenue down by 33%. BlackBerry PlayBook shipments of 260,000. An app store with just 89,000 offerings—less, even than Windows Phone 7, which isn't even two years old.
The only number from RIM's latest earnings report that even sounds big is the number of handsets sold: 7.8 million. And then you remember that Apple sold 35 million iPhones in the first three months of the year, and that at this point many of the BlackBerrys sold are low-end phones in developing countries, and you just get all sad again.
There are two ways to survive as a troubled business: either be incredibly strong but with no prospects, or be weak but have a clear path to success. RIM's last great hope, BB10, is gone. Its current offerings are totally ignorable. All that's left is BBM, a service that's only as good as the number of people using it. A number that's decreasing by the day.
So what happens now? We'll hopefully here a plan of action during the company's conference call to discuss earnings at 5 pm EST. But know this much: Either RIM goes quiet into that good night, or it goes on sale. The company's already hired "strategic advisers," who one imagines hastily advising its execs to sell BBM, sell the hypersecure server network. To salvage what it can instead of suffering this death by a thousand hatchet gashes.
|
<reponame>khelsabeck/felony_records_nc
from src.habitual_machine import State, StartState, StrikeOne, StrikeTwo, StrikeThree, FinishedState, HabitualMachine
from src.dumbwaiter import Dumbwaiter
from src.charge import Charge
from src.defendant import Defendant
import pytest
from datetime import date, datetime, timedelta
import typing
@pytest.fixture
def hab_eligibles():
'''This is a test list of the values of all crime classes eligible for habitual felony status'''
hab_eligibles = [ "Class I Felony", "Class H Felony", "Class G Felony", "Class F Felony", "Class E Felony", "Class D Felony", "Class C Felony",
"Class B1 Felony", "Class B2 Felony", "Class A Felony" ]
return hab_eligibles
@pytest.fixture
def defendant1():
'''This is a test defendant.'''
defendant1 = Defendant("John", "Doe", date(1999, 1, 1))
return defendant1
@pytest.fixture
def dumbwaiter():
'''This is a test dumbwaiter.'''
dumbwaiter = Dumbwaiter(date(1999, 1, 1))
return dumbwaiter
@pytest.fixture
def conviction1():
'''This is a basic conviction for testing the i_eligible method in the fsm itself.'''
conviction1 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2015,2, 2), "Randolph County", "14-72")
return conviction1
@pytest.fixture
def one_strike():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a single strike for habitual status. It is not eligible for habitual status'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1), date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2015,2, 2), "Randolph County", "14-72") # -- StrikeOne
one_strike = [ con1, con2 ]
return one_strike
@pytest.fixture
def two_strikes():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a record with 2 strikes. It is not eligible for habitual status'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2015,2, 2), "Randolph County", "14-72") # -- StrikeOne
con3 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,3, 3), "Randolph County", "14-72") #
con4 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,4, 4), "Randolph County", "14-72") #
con5 = Charge("Second Degree Kidnapping", "Class E Felony", date(2018,1, 1),date(2019,5, 5), "Randolph County", "14-39") # -- StrikeTwo
con6 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1), date(2015,6, 6), "Randolph County", "14-72") # 1 pt
two_strikes = [ con1, con2, con3, con4, con5, con6 ]
return two_strikes
@pytest.fixture
def one_strike_because18():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a record with 1 strike because the second happened with the defendant under 18. It is not eligible for habitual status'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2015,2, 2), "Randolph County", "14-72") # -- StrikeOne
con3 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2014,3, 3), "Randolph County", "14-72") #
con4 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,4, 4), "Randolph County", "14-72") #
con5 = Charge("Second Degree Kidnapping", "Class E Felony", date(2014,1, 1),date(2016,5, 5), "Randolph County", "14-39") # -- Still under 18
con6 = Charge("PSG", "Class 1 Misdemeanor", date(2016,1, 1),date(2016,6, 6), "Randolph County", "14-72") # 1 pt
one_strike_because18 = [ con1, con2, con3, con4, con5, con6 ]
return one_strike_because18
@pytest.fixture
def screen_pedantic_exceptions():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a record with 1 strike because the second happened with the defendant under 18. It is not eligible for habitual status'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("Habitual B&E", "Class E Felony", date(2014,1, 1),date(2015,2, 2), "Randolph County", "14-7.31") # -- No Strike (pedantic)
con3 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,3, 3), "Randolph County", "14-72") #
con4 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,4, 4), "Randolph County", "14-72") #
con5 = Charge("Habitual Misdemeanor Assault", "Class H Felony", date(2014,1, 1),date(2019,5, 5), "Randolph County", "14-33.2") # -- No Strike (pedantic)
con6 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,6, 6), "Randolph County", "14-72") #
screen_pedantic_exceptions = [ con1, con2, con3, con4, con5, con6 ]
return screen_pedantic_exceptions
@pytest.fixture
def three_striker():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a record with 3 strikes. It is eligible for habitual status'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2015,2, 2), "Randolph County", "14-72") # -- StrikeOne
con3 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,3, 3), "Randolph County", "14-72") #
con4 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,4, 4), "Randolph County", "14-72") #
con5 = Charge("Second Degree Kidnapping", "Class E Felony", date(2017,12, 31),date(2018,1, 1), "Randolph County", "14-39") # -- Strike2
con6 = Charge("Second Degree Kidnapping", "Class E Felony", date(2018,1, 2),date(2018,1, 3), "Randolph County", "14-39") # -- Strike3
three_striker = [ con1, con2, con3, con4, con5, con6 ]
return three_striker
@pytest.fixture
def one_strike_overlapper():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a record with three overlapping-timeline felonies. Only one should count.'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2018,1, 1), "Randolph County", "14-72") # -- StrikeOne
con3 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,3, 3), "Randolph County", "14-72") #
con4 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,4, 4), "Randolph County", "14-72") #
con5 = Charge("Second Degree Kidnapping", "Class E Felony", date(2014,12, 31),date(2017,12, 31), "Randolph County", "14-39") # -- Overlap Strike2
con6 = Charge("Second Degree Kidnapping", "Class E Felony", date(2018,1, 1),date(2018,1, 3), "Randolph County", "14-39") # -- Overlap Strike3
one_strike_overlapper = [ con1, con2, con3, con4, con5, con6 ]
return one_strike_overlapper
@pytest.fixture
def two_strike_overlapper():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a record with two non-overlapping-timeline felonies. Two should count out of three.'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2016,1, 1), "Randolph County", "14-72") # -- StrikeOne
con3 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,3, 3), "Randolph County", "14-72") #
con4 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,4, 4), "Randolph County", "14-72") #
con5 = Charge("Second Degree Kidnapping", "Class E Felony", date(2016,1, 1),date(2017,12, 31), "Randolph County", "14-39") # -- Overlap Strike2
con6 = Charge("Second Degree Kidnapping", "Class E Felony", date(2018,1, 1),date(2018,1, 3), "Randolph County", "14-39") # -- Overlap Strike3
two_strike_overlapper = [ con1, con2, con3, con4, con5, con6 ]
return two_strike_overlapper
@pytest.fixture
def two_strike_overlapper2():
'''FOR USE WITH defendant1, born 1/1/99.
This represents a record with two non-overlapping-timeline felonies. Two should count out of three.'''
con1 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") #
con2 = Charge("PSG", "Class H Felony", date(2014,1, 1),date(2015,1, 1), "Randolph County", "14-72") # -- StrikeOne
con3 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,3, 3), "Randolph County", "14-72") #
con4 = Charge("PSG", "Class 1 Misdemeanor", date(2014,1, 1),date(2015,4, 4), "Randolph County", "14-72") #
con5 = Charge("Second Degree Kidnapping", "Class E Felony", date(2016,1, 1),date(2017,12, 31), "Randolph County", "14-39") # -- Strike2
con6 = Charge("Second Degree Kidnapping", "Class E Felony", date(2017,12, 31),date(2018,1, 3), "Randolph County", "14-39") # -- Overlaps Strike2
con7 = Charge("Second Degree Kidnapping", "Class E Felony", date(2017,12, 31),date(2018,1, 3), "Randolph County", "14-39") # -- Overlaps Strike2
two_strike_overlapper2 = [ con1, con2, con3, con4, con5, con6, con7 ]
return two_strike_overlapper2
def test_state():
'''This is a basic initialization test of the base state.'''
st = State()
assert State == type(st)
assert "State" == str(st)
assert "State" == repr(st)
def test_startstate(dumbwaiter):
'''This is a test of the start state with a mock dumbwaiter and an empty list of convictions. It should go straight to the FinishedState.'''
st = StartState()
dumbwaiter = Dumbwaiter(date(1999,1,1))
expect_finished = st.on_event([],dumbwaiter)
assert FinishedState == type(expect_finished)
assert True == dumbwaiter.ran
def test_pedantics(screen_pedantic_exceptions):
'''This tests the screening out of two pedantic exceptions which would otherwise count. These only count if they were committed before 12/1/2004'''
st = StartState()
dumbwaiter = Dumbwaiter(date(1999,1,1))
expect_finished = st.on_event([],dumbwaiter)
assert FinishedState == type(expect_finished)
assert True == expect_finished.dumbwaiter.ran
assert [] == expect_finished.convictions
def test_one_strike(one_strike):
'''This is a test of a one-strike record.'''
st = StartState()
dumbwaiter = Dumbwaiter(date(1999,1,1))
expect_finished = st.on_event(one_strike, dumbwaiter)
assert FinishedState == type(expect_finished)
assert True == expect_finished.dumbwaiter.ran
assert [ one_strike[1] ] == expect_finished.dumbwaiter.habitual_convictions
assert False == expect_finished.dumbwaiter.hab_eligible
assert None == expect_finished.dumbwaiter.date_eligible
def test_2strikes(two_strikes):
'''This is a test of the expected returns from a 2-strike record'''
st = StartState()
dumbwaiter = Dumbwaiter(date(1999,1,1))
expect_finished = st.on_event(two_strikes, dumbwaiter)
assert FinishedState == type(expect_finished)
assert True == expect_finished.dumbwaiter.ran
assert [ two_strikes[1], two_strikes[4] ] == expect_finished.dumbwaiter.habitual_convictions
assert False == expect_finished.dumbwaiter.hab_eligible
assert None == expect_finished.dumbwaiter.date_eligible
def test_1strike_bc18(one_strike_because18):
'''This is a test of the expected returns from a 1-strike record because what would have qualified as the second strike was pre-18.'''
st = StartState()
dumbwaiter = Dumbwaiter(date(1999,1,1))
expect_finished = st.on_event(one_strike_because18, dumbwaiter)
assert FinishedState == type(expect_finished)
assert True == expect_finished.dumbwaiter.ran
assert [ one_strike_because18[1] ] == expect_finished.dumbwaiter.habitual_convictions
assert False == expect_finished.dumbwaiter.hab_eligible
assert None == expect_finished.dumbwaiter.date_eligible
def test_pedantic_exceptions(screen_pedantic_exceptions):
'''This tests these two particular and pedantic exceptions. These appear to be qualified felonies, but should be screened out'''
st = StartState()
dumbwaiter = Dumbwaiter(date(1999,1,1))
expect_finished = st.on_event(screen_pedantic_exceptions, dumbwaiter)
assert FinishedState == type(expect_finished)
assert True == expect_finished.dumbwaiter.ran
assert [ ] == expect_finished.dumbwaiter.habitual_convictions
assert False == expect_finished.dumbwaiter.hab_eligible
assert None == expect_finished.dumbwaiter.date_eligible
def test_3strikes(three_striker):
'''This is a test with a record for someone who has three strikes, two after turning 18'''
st = StartState()
dumbwaiter = Dumbwaiter(date(1999,1,1))
expect_finished = st.on_event(three_striker, dumbwaiter)
assert FinishedState == type(expect_finished)
assert True == expect_finished.dumbwaiter.ran
assert [ three_striker[1],three_striker[4],three_striker[5] ] == expect_finished.dumbwaiter.habitual_convictions
assert True == expect_finished.dumbwaiter.hab_eligible
assert date(2018,1, 3) == expect_finished.dumbwaiter.date_eligible
def test_machine_init():
'''This is a test of the initialization and type of the habitualmachine itself.'''
machine = HabitualMachine()
assert HabitualMachine == type(machine)
assert StartState == type(machine.state)
def test_machine_strike1(one_strike):
'''This is an integration test of the habitual machine with a 1-strike record.'''
machine = HabitualMachine()
machine.on_event(one_strike, date(1999,1,1))
assert FinishedState == type(machine.state)
assert False == machine.hab_eligible
assert None == machine.date_eligible
assert True == machine.dumbwaiter.ran
assert 1 == len(machine.dumbwaiter.habitual_convictions)
def test_machine_strike2_butfor18(one_strike_because18):
'''This is an integration test of the habitual machine with a 1-strike record that would be 2 but for he second being pre-18.'''
machine = HabitualMachine()
machine.on_event(one_strike_because18, date(1999,1,1))
assert FinishedState == type(machine.state)
assert True == machine.dumbwaiter.ran
assert 1 == len(machine.dumbwaiter.habitual_convictions)
assert False == machine.hab_eligible
assert None == machine.date_eligible
def test_machine_strike2(two_strikes):
'''This is an integration test of the habitual machine with a 2-strike record.'''
machine = HabitualMachine()
machine.on_event(two_strikes, date(1999,1,1))
assert FinishedState == type(machine.state)
assert False == machine.hab_eligible
assert None == machine.date_eligible
assert 2 == len(machine.dumbwaiter.habitual_convictions)
assert True == machine.dumbwaiter.ran
def test_machine_strike3(three_striker):
'''This is an integration test of the habitual machine with a 3-strike record.'''
machine = HabitualMachine()
machine.on_event(three_striker, date(1999,1,1))
assert FinishedState == type(machine.state)
assert True == machine.dumbwaiter.ran
assert 3 == len(machine.dumbwaiter.habitual_convictions)
assert True == machine.hab_eligible
assert date(2018,1,3) == machine.date_eligible
def test_overlap(one_strike_overlapper):
'''This is an integration test of the habitual machine with a 1-strike record with overlapping dates of offense/conviction from 3 felonies.'''
machine = HabitualMachine()
machine.on_event(one_strike_overlapper, date(1999,1,1))
assert FinishedState == type(machine.state)
assert True == machine.dumbwaiter.ran
assert 1 == len(machine.dumbwaiter.habitual_convictions)
assert False == machine.hab_eligible
assert None == machine.date_eligible
def test_overlap_2striker(two_strike_overlapper):
'''This is an integration test of the habitual machine with a 2-strike record with overlapping dates of offense/conviction from 3 felonies. Excpect 2
strikes out of the three felonies'''
machine = HabitualMachine()
machine.on_event(two_strike_overlapper, date(1999,1,1))
assert FinishedState == type(machine.state)
assert True == machine.dumbwaiter.ran
assert 2 == len(machine.dumbwaiter.habitual_convictions)
assert False == machine.hab_eligible
assert None == machine.date_eligible
def test_overlap_2striker(two_strike_overlapper2):
'''This is an integration test of the habitual machine with a 2-strike record with overlapping dates of offense/conviction from 3 felonies. Excpect 2
strikes out of the three felonies'''
machine = HabitualMachine()
machine.on_event(two_strike_overlapper2, date(1999,1,1))
assert FinishedState == type(machine.state)
assert True == machine.dumbwaiter.ran
assert 2 == len(machine.dumbwaiter.habitual_convictions)
assert False == machine.hab_eligible
assert None == machine.date_eligible
def test_machine_offense_date_is_eligible(three_striker, conviction1):
'''This tests the habitual machine is_eligible method.'''
machine = HabitualMachine()
machine.on_event(three_striker, date(1999,1,1))
assert FinishedState == type(machine.state)
assert True == machine.dumbwaiter.ran
assert 3 == len(machine.dumbwaiter.habitual_convictions)
assert True == machine.hab_eligible
assert date(2018,1,3) == machine.date_eligible
assert False == machine.offense_date_is_eligible(conviction1.offense_date)
def test_machine_offense_date_is_eligible_error(three_striker, conviction1):
'''This tests the habitual machine is_eligible method's error-handling.'''
machine = HabitualMachine()
with pytest.raises(Exception) as exc_info:
machine.offense_date_is_eligible(conviction1.offense_date)
exception_raised = exc_info.value
assert type(ValueError()) == type(exception_raised)
assert "The record has not been successfully caluclated yet." in str(exc_info.__dict__)
|
Effect of unilateral cerebral cortical lesions on ocular motor behavior in monkeys: saccades and quick phases. Saccades and quick phases of vestibular and optokinetic nystagmus were quantitated using the magnetic-field search coil technique before and during 1 yr after unilateral decortication in three rhesus monkeys. Saccades were examined during several different behavioral conditions: spontaneous saccades made in the light and in the dark; intentional saccades including visually guided saccades to a target light, predictive saccades to a target light stepped to a predictable location, and target-searching saccades when the monkey was rewarded to find and fixate the target light located in the defective visual hemifield; and reflexive saccades made to novel visual, auditory, and tactile stimuli. Quick phases of nystagmus and spontaneous saccades could be initiated immediately postoperatively, although those initiated away from the side of the lesion were reduced in amplitude and rarely moved the eyes into contralateral craniotopic space. Intentional and reflexive saccades could not be initiated away from the side of the lesion during the first postoperative week. Visually guided saccades and reflexive saccades to stationary or moving visual stimuli in the defective visual hemifield never recovered. Target-searching and predictive saccades directed away from the lesioned side recovered but were generated in a staircase pattern; those saccades from orbital positions further into craniotopic space on the side opposite the lesion had progressively higher latencies and smaller amplitudes. The amplitudes of visually guided saccades to targets stepped into the normal visual hemifield were increased in amplitude by approximately 15% but slowly returned to near preoperative values by 20 wk. Pure vertical visually guided saccades to targets stepped or moved in the vertical direction were not generated throughout the postoperative period. Instead, the animals generated oblique saccades, tilted 10-15 degrees toward the side of the lesion. Velocities of saccades and quick phases were significantly reduced at all amplitudes both away from (approximately 37%) and toward (approximately 22%) the side of the lesion. This deficit diminished with time but velocities were still low one yr postoperatively. Our results suggest that cortical areas in one hemisphere are involved in the initiation of contralaterally directed intentional and reflexive saccades but not in the initiation of spontaneous saccades or quick phases. In time, other structures can initiate contralaterally directed intentional and reflexive saccades, except those guided by vision.(ABSTRACT TRUNCATED AT 400 WORDS)
|
class FeatureValidator:
"""The Feature Validator class to manage custom validators.
Methods
-------
register(self, name: str, handler: Callable, condition: Union[Tuple, Dict[str, Any]] = None, replace: bool = False) -> None
Registers new validator.
unregister(self, name: str, condition: Union[Tuple, Dict[str, Any]] = None) -> None
Unregisters validator.
registered(self) -> pd.DataFrame
Gets the list of registered validators.
Examples
--------
>>> series = pd.Series(['+1-202-555-0141', '+1-202-555-0142'], name='Phone Number')
>>> def phone_number_validator(data: pd.Series) -> pd.Series:
... print("phone_number_validator")
... return data
>>> def universal_phone_number_validator(data: pd.Series, country_code) -> pd.Series:
... print("universal_phone_number_validator")
... return data
>>> def us_phone_number_validator(data: pd.Series, country_code) -> pd.Series:
... print("us_phone_number_validator")
... return data
>>> PhoneNumber.validator.register(name="is_phone_number", handler=phone_number_validator, replace=True)
>>> PhoneNumber.validator.register(name="is_phone_number", handler=universal_phone_number_validator, condition = ('country_code',))
>>> PhoneNumber.validator.register(name="is_phone_number", handler=us_phone_number_validator, condition = {'country_code':'+1'})
>>> PhoneNumber.validator.is_phone_number(series)
phone_number_validator
0 +1-202-555-0141
1 +1-202-555-0142
>>> PhoneNumber.validator.is_phone_number(series, country_code = '+7')
universal_phone_number_validator
0 +1-202-555-0141
1 +1-202-555-0142
>>> PhoneNumber.validator.is_phone_number(series, country_code = '+1')
us_phone_number_validator
0 +1-202-555-0141
1 +1-202-555-0142
>>> PhoneNumber.validator.registered()
Validator Condition Handler
---------------------------------------------------------------------------------
0 is_phone_number () phone_number_validator
1 is_phone_number ('country_code') universal_phone_number_validator
2 is_phone_number {'country_code': '+1'} us_phone_number_validator
>>> series.ads.validator.is_phone_number()
phone_number_validator
0 +1-202-555-0141
1 +1-202-555-0142
>>> series.ads.validator.is_phone_number(country_code = '+7')
universal_phone_number_validator
0 +1-202-555-0141
1 +1-202-555-0142
>>> series.ads.validator.is_phone_number(country_code = '+1')
us_phone_number_validator
0 +1-202-555-0141
1 +1-202-555-0142
"""
def __init__(self):
"""Initializes the FeatureValidator."""
self._validators = {}
def register(
self,
name: str,
handler: Callable,
condition: Union[Tuple, Dict[str, Any]] = None,
replace: bool = False,
) -> None:
"""Registers new validator.
Parameters
----------
name : str
The validator name.
handler: callable
The handler.
condition: Union[Tuple, Dict[str, Any]]
The condition for the validator.
replace: bool
The flag indicating if the registered validator should be replaced with the new one.
Returns
-------
None
Nothing.
Raises
------
ValueError
The name is empty or handler is not provided.
TypeError
The handler is not callable.
The name of the validator is not a string.
ValidatorAlreadyExists
The validator is already registered.
"""
if not name:
raise ValueError("Validator name is not provided.")
if not isinstance(name, str):
raise TypeError("Validator name should be a string.")
if not replace and name in self._validators:
if not condition:
raise ValidatorAlreadyExists(name)
if self._validators[name]._has_condition(condition):
raise ValidatorWithConditionAlreadyExists(name)
if not handler:
raise ValueError("Handler is not provided.")
if not callable(handler):
raise TypeError("Handler should be a function.")
if condition:
self._validators[name].register(condition=condition, handler=handler)
else:
self._validators[name] = FeatureValidatorMethod(handler)
def unregister(
self, name: str, condition: Union[Tuple, Dict[str, Any]] = None
) -> None:
"""Unregisters validator.
Parameters
----------
name: str
The name of the validator to be unregistered.
condition: Union[Tuple, Dict[str, Any]]
The condition for the validator to be unregistered.
Returns
-------
None
Nothing.
Raises
------
TypeError
The name of the validator is not a string.
ValidatorNotFound
The validator not found.
ValidatorWIthConditionNotFound
The validator with provided condition not found.
"""
if not name:
raise ValueError("Validator name is not provided.")
if not isinstance(name, str):
raise TypeError("Validator name should be a string.")
if name not in self._validators:
raise ValidatorNotFound(name)
if condition and not self._validators[name]._has_condition(condition):
raise ValidatorWithConditionNotFound(name)
if condition:
self._validators[name].unregister(condition)
else:
del self._validators[name]
def registered(self) -> pd.DataFrame:
"""Gets the list of registered validators.
Returns
-------
pd.DataFrame
The list of registerd validators.
"""
result_df = pd.DataFrame((), columns=["Validator", "Condition", "Handler"])
for key, feature_validator in self._validators.items():
feature_validators_df = feature_validator.registered()
feature_validators_df.insert(0, "Validator", key)
result_df = result_df.append(feature_validators_df)
result_df.reset_index(drop=True, inplace=True)
return result_df
def _bind_data(self, data: pd.Series) -> None:
"""Binds the data to the all registered validators.
Parameters
----------
data: pd.Series
The data to be processed.
"""
for validator in self._validators.values():
validator._bind_data(data)
def __getattr__(self, attr):
"""Makes it possible to invoke registered validators as a regular method."""
if attr in self._validators:
return self._validators[attr]
raise AttributeError(attr)
|
/*
Copyright 2017 <NAME>
All rights reserved
*/
#include "Ascii85.h"
#include "../Globals.h"
// A trick that may serve
// 85 = 0b0101'0101
// 85 = (2^6)+(2^4)+(2^2)+(2^1)
// x * 85 = x<<6 + x << 4 + x << 2 + x << 1
#define mul_85(x) ((x<<6) + (x << 4) + (x << 2) + (x << 0))
static const __flash uint32_t powers[5] = {52200625, 614125, 7225, 85, 1};
void encode_16B(uint8_t *input, char *output)
{
uint8_t i = 0;
for(; i < 4; ++i)
{
uint32_t sum = ((uint32_t)input[0] << 24) + ((uint32_t)input[1] << 16) + ((uint32_t)input[2] << 8) + (uint32_t)input[3];
uint8_t j = 0;
for(; j < 5; ++j)
{
char tempOutput = sum / powers[j];
sum -= tempOutput * powers[j];
tempOutput += 33;
output[j] = tempOutput;
}
input += 4;
output+= 5;
}
}
void decode_16B(char *input, uint8_t *output)
{
uint8_t i = 0;
for(; i < 4; ++i)
{
uint32_t sum = 0;
uint8_t j = 0;
for(; j < 5; ++j)
{
sum += (input[j]-33) * powers[j];
}
output[0] = sum >> 24;
output[1] = (sum & 0xFF0000) >> 16;
output[2] = (sum & 0xFF00) >> 8;
output[3] = sum & 0xFF;
input += 5;
output+= 4;
}
}
|
Speaking of Babel: The Risks and Rewards of Writing about Polyglot Societies The Finzi-Contini Lectureship honors Bianca M. Finzi-Contini Calabresi, a scholar of European literature and a native of Ferrara who left fascist Italy to establish herself in the United States. The lectureship was founded by her sons, the Honorable Guido Calabresi, Judge, U.S. Court of Appeals for the Second Circuit, and Dr. Paul Calabresi. Whitney Humanities Center Auditorium 53 Wall Street Amitav Ghosh acclaimed Indian writer
|
First we had red-light cameras snapping photos of intersection scofflaws and generating an almost automatic ticket.
Now, it looks like we could have motorcycle traffic cops issuing citations from a little handheld device, called an E-ticket machine, rather than whipping out the ticket pad and writing a ticket by hand.
They are taking all the sport out of cop-driver hide-and-seek.
The Dallas Police Department plans to use 50 E-ticket gadgets in a test program involving motorcycle officers because statistically they write more tickets than other patrol officers.
The gizmos are billed as more efficient because an issuing officer can get the information into the city’s database within about three days versus the 10 days it takes to enter a conventional citation. E-tickets also take less time to fill out, sending cop and driver along their merry ways, well, at least one of them, in a briefer time, plus the officer can use the e-chine to scan the pulled-over driver’s license for warrants and such.
That’s all just one side of the traffic ticket scenario. After a ticket gets issued it has to get into the court system and that might be a sticking point. It was in Tulsa, Okla., where they still had to print and scan the E-tickets and that created even more work.
No precise word on when the test program begins, but if the gizmos prove their worth on the streets Dallas City Council and the City Manager’s office will start scouring the budget for available funds — uh oh, another possible sticking point — to buy enough for all police and other ticketing agencies such as code compliance.
Bruce Felps owns and operatesEast Dallas Times, an online community news outlet serving the White Rock Lake area. He’s had his fill of traffic stops after four tickets during a three-week span back in the spring.
|
Two-layer membranes of calcium phosphate/collagen/PLGA nanofibres: in vitro biomineralisation and osteogenic differentiation of human mesenchymal stem cells. The present study evaluates the in vitro biomedical performance of an electrospun, flexible, anisotropic bilayer with one layer containing a collagen to mineral ratio similar to that in bone. The double membrane consists of a poly(lactide-co-glycolide) (PLGA) layer and an amorphous calcium phosphate (a-CaP)/collagen (Col)/PLGA layer. In vitro biomineralisation and a cell culture study with human mesenchymal stem cells (hMSC) were conducted to characterise such membranes for possible application as biomaterials. Nanofibres with different a-CaP/Col/PLGA compositions were synthesised by electrospinning to mimic the actual composition of bone tissue. Immersion in simulated body fluid and in cell culture medium resulted in the deposition of a hydroxyapatite layer. Incubation of hMSC for 4 weeks allowed for assessment of the proliferation and osteogenic differentiation of the cells on both sides of the double membrane. Confocal laser scanning microscopy was used to observe the proper adhesion of the cells. Calcium and collagen content was proven by Alizarin red S and Sirius red assays. Acute cytotoxic effects of the nanoparticles or the chemicals used in the scaffold preparation could be excluded based on viability assays (alamarBlue and alkaline phosphatase activity). The findings suggest possible application of such double membranes is in treatment of bone defects with complex geometries as wound dressing material.
|
<gh_stars>1-10
'''
2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2 ^ 1000?
'''
values = list(str(2 ** 1000))
int_values = [int(value) for value in values]
sums = sum(int_values)
print(sums)
|
Production of Cellulase from Aspergillus fumigatus Under Submerged and Solid State Fermentation Using Agricultural Waste This study aimed to the production of Cellulase from Aspergillus fumigatus was isolated and identified from soil and used for the study. Aspergillus fumigatus were screened for their cellulase production ability. Cellulase production was analysed in agricultural waste such as rice bran, coconut coir pith, wheat bran and rice husk. Among the study Aspergillus fumigatus have high enzyme activity in rice bran.In the study, the optimum parameters for the isolated organism for cellulase production were studied under varying condition such as of pH, temperature and substrates constrations. The maximum production of cellulase was noticed at temperature 25 o C and pH 4, substrate concentration 5g for Aspergillus fumigatus Finally concluded that the Aspergillus fumigatus showed highest level of cellulase production which was recommended for industrial level cellulase production.
|
SPOKANE, Wash. — A retired Spokane firefighter was killed early Wednesday morning after authorities say he crashed his ultralight airplane on the Snake River.
Whitman County Sheriff’s deputies say 64-year-old Ronny F. Weston, of Cheney, crashed a Solaris 16.8 ultralight aircraft on the Snake River just east of Boyer Park and Marina after taking off from a nearby airstrip at about 6:30 a.m. He died at the scene.
An employee of the Lower Granite Dam reportedly told deputies that he saw wreckage of the small aircraft at about 7:15 a.m. on his way to work, according to a sheriff’s office news release. The employee said he saw a small portion of the aircraft on the railroad tracks just east of the park.
Weston’s family said he was an experienced ultralight pilot, according to the news release. He recently purchased the aircraft that crashed.
According to the Federal Aviation Administration, Weston was operating on a student license, which he acquired in 2009.
Spokane Fire Chief Brian Schaeffer in a written statement said he was “deeply saddened by the tragic loss” of Weston.
The Spokane Firefighters Union released a picture of Weston late Wednesday night.
“Heavy hearts tonight as we learn the tragic news that one of our own retired members, Ron Weston, was killed early this morning in a tragic ultralight crash in Whitman County,” the union said.
“You put your life in their hands,” he told the reporter.
Weston retired from the Spokane Fire Department in 2013.
A National Transportation Safety Board spokesperson couldn’t immediately say Thursday morning whether NTSB officials were assisting in the investigation.
|
def scopus_id(self) -> List[int]:
return [int(e['scopus_id']) for e in self._identifierlegend]
|
Stochastic resetting of a population of random walks with resetting-rate-dependent diffusivity We consider the problem of diffusion with stochastic resetting in a population of random walks where the diffusion coefficient is not constant, but behaves as a power-law of the average resetting rate of the population. Resetting occurs only beyond a threshold distance from the origin. This problem is motivated by physical realizations like soft matter under shear, where diffusion of a walk is induced by resetting events of other walks. We first reformulate in the broader context of diffusion with stochastic resetting the so-called H\'ebraud-Lequeux model for plasticity in dense soft matter, in which diffusivity is proportional to the average resetting rate. Depending on parameter values, the response to a weak external field may be either linear or non-linear with a non-zero average position for a vanishing applied field, and the transition between these two regimes may be interpreted as a continuous phase transition. Extending the model by considering a general power-law relation between diffusivity and average resetting rate, we notably find a discontinuous phase transition between a finite diffusivity and a vanishing diffusivity in the small field limit. Introduction Many stochastic processes consist of a combination of a continuous diffusive dynamics and discontinuous stochastic jumps. This is the case in particular for search processes which typically become more efficient by making random jumps to explore distant areas in a shorter time. A simple and paradigmatic model for such intermittent diffusive dynamics is the diffusion process with stochastic resetting -see for a review. At odds with standard random walks, a random walk with stochastic resetting to the origin converges to a stationary statistical state even in an unbounded domain. This minimal model has been extended in many different directions, including arbitrary spatial dimensions, bounded domains, Langevin dynamics, spacedependent diffusivity, time-dependent resetting rate or non-Poissonian resetting dynamics. Anomalous diffusion with stochastic resetting has also been considered, notably in the context of record statistics. The diffusion process with stochastic resetting also fostered further works on search strategies and their optimality. Beyond these different generalizations, another natural extension is to consider interacting random walks with resetting, as done recently for instance in the context of population genetics. Although interactions may occur in many different ways, like for instance non-crossing conditions, a physically-motivated type of interaction is to consider that in practical realizations, resetting events often lead to energy dissipation and may thereby generate some noise. A large population of random walks with resetting may thus continuously generate noise through resetting events, and this noise may be (fully or partly) the physical source of diffusion of the walks. This mechanism is at play in the so-called elastoplastic scenario for the deformation of soft amorphous materials. In such systems, the local mechanical stress performs a random walk with stochastic resetting (resetting corresponds here to a local stress relaxation called plastic event) once a stress threshold is overcome. Since such systems are athermal, the only source of stress diffusion is the mechanical noise generated by distant plastic events and transmitted through a long-range elastic propagator. A mean-field model of this elastoplastic scenario, called the Hbraud-Lequeux (HL) model, has been proposed more than twenty years ago. It basically consists of a population of random walks with stochastic resetting beyond a threshold distance to the origin, and such that the diffusion coefficient is proportional to the average resetting rate of the population. This dependence of the diffusion coefficient on the average resetting rate results in effective interactions between the walks. The goal of this paper is twofold. First, we aim at reformulating in the broader context of diffusion with stochastic resetting the results of the HL model known in the specific context of the deformation of soft amorphous materials. Second, we generalize the results of the HL model by considering a more general relation between diffusivity and average resetting rate. This generalization leads to a rich phenomenology that we discuss here. We believe that such a physically-motivated way to introduce mean-field interactions between random walks with stochastic resetting could be of interest to the community working on this topic, and might lead to a number of further developments in the field. The paper is organised as follows. Sec. 2 introduces the HL model and briefly discusses its interpretation in a soft matter context. Then Sec. 3 uses the derivation of the stationary probability distribution to obtain a self-consistent equation satisfied by the field-dependent diffusion coefficient. Finally Sec. 4 evaluates the diffusion coefficient in the small field limit as a function of model parameters, leading to the identification of distinct regimes, either linear or non-linear, for the average position of the walk as a function of the external field. Sec. 5 eventually draws some conclusions. A population of random walks with stochastic resetting We consider a large population of N random walks with stochastic resetting in one dimension. Each walk is described by its position x i (i = 1,..., N ), obeying the Langevin equation where h is the applied external field and i (t) is a Gaussian white noise satisfying with a time-dependent diffusion coefficient D(t). The continuous Langevin evolution described by Eq. is supplemented by a random resetting rule corresponding to a stochastic jump to x i = 0, with a position-dependent transition rate (x i ). In the following, we restrict ourselves to the functional form with 0 > 0 a constant rate, b > 0 a threshold distance, and (x) the Heaviside function, equal to (x) = 1 for x ≥ 0 and (x) = 0 for x < 0. In the following, we set 0 = 1 and b = 1 by choosing appropriate time and length units. Up to now, the N random walks are statistically independent. The idea is to introduce a mean-field coupling between them by choosing the diffusivity D(t) to be a function of the average resetting rate (t) defined as where p(x, t) is the probability distribution of the position x of a random walk at time t. In the infinite N limit, (t) precisely corresponds to the resetting rate of the population of walkers. In the following, we consider for definiteness the functional dependence with > 0 and > 0. The limiting case = 0 corresponds to the usual diffusion with stochastic resetting problem, where the N walkers are statistically independent. We exclude the case < 0 because we aim at describing a physical situation where the diffusivity of a given walker is induced by resettings of other walks in the population, and thus one should have D(t) → 0 when (t) → 0. The HL model As mentioned in the introduction, a physically grounded implementation of the above model corresponds to the HL model, which describes in a meanfield way the plastic deformation of dense soft amorphous materials (see also for more mathematically oriented studies of the HL model, and for an extension to higher dimensions). In such materials, deformation occurs via localised plastic events which release stress. Such events occur when the local stress exceeds a threshold, in analogy to the transition rate (x) defined in Eq.. Quite importantly, in finite-dimensional systems the locally released stress is redistributed throughout the system by a long-range elastic propagator. A peculiarity of this propagator is that it is anisotropic and takes either positive or negative values depending on the direction considered. In an elementary mean-field scenario, one may divide the system into boxes with a volume comparable to the volume of a rearranging region, and treat the effect of the stress redistribution process as a Gaussian white noise. This is the assumption made in the HL model, which consistently assumes = 1 in relation, that is a proportionality between the diffusivity D and the average resetting rate. Eq. may also be generalized by adding a constant term on the right hand side. Note that this term would model an additional source of noise (e.g., active noise ) that does not depend on the average resetting rate. Evolution of the probability distribution In the limit N → ∞, the population of random walks can be described by a non-linear evolution equation for the probability distribution p(x, t), with (x) the Dirac delta distribution, and where (x), (t) and D(t) are defined in Eqs., and is continuous (because of its diffusive nature), which implies the continuity of the derivative dp st /dx. At x = 0, the probability distribution is also continuous, but not its derivative, because of the resetting probability flux. One can write the corresponding probability flux balance at x = 0, which using Eq. yields an explicit condition on the discontinuity of the derivative dp st /dx at x = 0 (more details can be found in ). Having determined the stationary distribution p st (x) for fixed values of the diffusivity D and the external field h, one can express the average resetting rate as a function of D and h as where the function f (D, h) is given by f The value of D is then determined self-consistently using Eq., leading to a closed equation on D: In principle, Eq. should be solved by determining its solution D(h) for any fixed external field h. In practice, such a resolution for an arbitrary value of h can only be performed numerically. However, as discussed below, it is possible to determine analytically D(h) to leading order in the limit h → 0. Once D(h) is determined, the distribution p st (x) is known, and one can evaluate arbitrary average observables. Our interest here goes more specifically to the average position x of the walker. In the absence of external field, h = 0, the average position x = 0 in the stationary state, because of the symmetry x → −x. For h = 0, x can be evaluated from the knowledge of p st (x), and one finds after some algebra where the function (D) reads as Since (D) → 1 when D → 0, the average position x is proportional to h/D when h/D 1. Now considering the fact that D depends on h when taking into account Eq., the average position x ∼ h/D(h) may behave linearly or non-linearly with h in the limit h → 0, depending on whether D(h) goes to a finite value or to zero in this limit -provided D(h) goes to zero slower than h to fulfill the assumption h/D 1 used to derive Eq.. We will see below that both situations may occur in the model depending on parameter values. Linear and non-linear response regimes We focus in this section on the determination of the field-dependent diffusion coefficient D(h) in the limit h → 0 as a function of the two parameters and introduced in Eq.. For the sake of clarity, we analyse separately the cases = 1, < 1 and > 1. Case = 1 The case = 1 corresponds to the standard HL model, and we reformulate here in a more pedagogical way some of the results reported in, rephrasing them in the generic framework of random walks with stochastic resetting. In the case = 1, Eq. allowing for the determination of D simplifies to To determine D in the limit h → 0, one may first take the limit h → 0 in the function f (D, h), and one finds: Hence for any fixed D > 0, f 0 (D) > 1 2. For > 1 2, the equation f 0 (D) = thus admits a solution D 0 > 0 of Eq. in the limit h → 0. One can get the leading correction in h of D(h) by evaluating the first correction in h to f (D, h) when h → 0, yielding where the function f 1 (D) is given by Note that f 1 (D) < 0 for all D > 0. Expanding D(h) as for h → 0, one finds Using Eq., the average position is then given by The response to the external field is thus linear to leading order, with a regular (i.e., cubic) subleading correction that we do not evaluate explicitly -this would require to compute the cubic response in Eq.. Note that the h-dependence of D(h) does not modify here the linear response with respect to the case of a constant diffusion coefficient D 0 ; it only contributes to non-linear corrections at order h 3 and higher. In contrast, when 0 < < 1 2, the equation f 0 (D) = has no solution. In this case, one has to come back to Eq. for finite h, and to look for a parametrization of D(h) that goes to zero when h → 0. Indeed, although f 0 = 1 2 from Eq., one has lim D→0 f (D, h) = 0 for all h > 0, meaning that the limits D → 0 and h → 0 do not commute. It follows that f (D, h) actually reaches values lower than 1 2 if one parameterises D as a function of h when taking the limit h → 0. Since D(h) is expected to go to zero when h → 0, a natural parameterisation is to assume that D(h) = u|h|, with > 0 a given exponent, and u the rescaled diffusion coefficient. As a first trial, we investigate the case = 1. Assuming D = u|h|, the function f (D, h) can be expanded for h → 0 as with Interestingly, the function 0 (u) takes values in the range (0, 1 2 ). Hence for 0 < < 1 2, the equation 0 (u) = has a solution u 0 > 0. Expanding u(h) as u(h) = u 0 + |h| u 1, one finds u 1 = − 1 (u 0 )/ 0 (u 0 ) < 0. Taking into account the relation D = u|h| as well as the expression of x, the average position is obtained to leading order in a |h| expansion as Hence for 0 < < 1 2, the average position of the walk does not vanish in the limit h → 0. This comes from the fact that the diffusion coefficient also goes to zero as D ∝ |h|, which effectively enhances the bias generated by the external field h. The subleading correction, proportional to |h| is also of interest because of its singular behaviour. In the HL model for sheared soft amorphous materials, the average position is interpreted as the average mechanical stress in the material in response to a deformation rate given by h, and the behaviour given by Eq. with the |h| correction is called the Hershel-Bulkley law. Up to now, we have been able to solve Eq. in the small h limit for the two cases > 1 2 and 0 < < 1 2 by using the scaling relations D ∝ |h| with = 0 and = 1 respectively. By doing so, the value = 1 2 has been left aside. It is thus natural to expect that Eq. may be solved with the ansatz D ∝ |h| for some intermediate value of. We thus set D = u|h|, with 0 < < 1 an exponent to be determined. A lowest order expansion of f (u|h|, h) for h → 0 leads to with = max( 2, 2 − 2). Assuming first that the two exponents 2 and 2 − 2 differ, one finds no solution for Eq. with = 1 2. One then concludes that the two exponents must be equal, leading to = corresponding to a strongly non-linear response with a non-trivial exponent 1 5. In other words, one has for = 1 the equivalent of a phase transition as a function of the parameter, with a critical value c = 1 2. The order parameter of the transition is the average position x of the walk. For > c, x → 0 when h → 0 and there is no spontaneous symmetry breaking. In contrast, for < c, x goes to a finite value when h → 0 , corresponding to a spontaneous symmetry breaking. The order parameter vanishes at the critical point as x ∼ ( c − ) 1/2. In this respect, the situation is similar to the mean-field Ising model, where the average magnetisation goes when h → 0 to a non-zero value which behaves as a square-root of the distance to the critical point. However, right at the critical point = c, the average position behaves as a power law of h, x ∼ |h| 1/5 sgn(h), corresponding to a critical exponent = 5 in the usual notations of critical phenomena. Interestingly, and although the present model is purely of mean-field type, the value = 5 differs from the standard exponent = 3 found in the mean-field Ising model. = aD (other lines). For < 0 (i.e., < 1), the equation always has a single solution, illustrated here for = −1 and a = 1 (g(D) is plotted as a dotted line). For 0 < < 1 (i.e., > 1), there exists a critical amplitude a c such that the equations admits no solution for a < a c and two solutions for a > a c. Illustration: = 1 2 with a = 2 (g(D) plotted as a dashed line) and a = 2.6 (dot-dashed). The critical amplitude for = 1 2 is a c ≈ 2.414. Case < 1 When = 1, Eq. is replaced by Eq., which we rewrite for convenience as When < 1, one has < 0 and Eq. boils down for h → 0 to which always has a solution D 0 (see Fig. 1), that can be determined numerically. Using the same expansion Eq. as in the case = 1, one finds for D 1, One then eventually obtains the same formal regular expansion in h for the average position x as in Eq., but now with D 0 solution of Eq.. Note that at odds with the case = 1, no transition occurs as a function of in the case < 1. Case > 1 We now have to solve Eq. in the case > 1, which corresponds to 0 < < 1. As illustrated on Fig. 1, this equation may either have zero solution below a critical amplitude, a < a c, or two solutions D 0 and D 0 for a > a c (we assume D 0 < D 0 ). For a = a c, a single solution D 0 exists. The critical amplitude a c is determined together with the corresponding value D 0 of the diffusion coefficient by the two conditions Graphically, this correspond to the fact that for a = a c, the curves representing the functions f 0 (D) and g(D) = a D intersect at a single point D 0 and have a common tangent at this point. In addition, another solution can be found by assuming a scaling D = u|h|, with now > 1. One finds to leading order for h → 0, Hence the solution of Eq. is given for h → 0 by so that D = D h ≡ |h| ; in other words, = |h| as seen from Eq.. For a < a c, we thus have a single solution D h (with D h → 0), while for a > a c we have three solutions D h < D 0 < D 0. Physical intuition suggests that the intermediate value D 0 may be unstable, while D h and D 0 may be stable, by analogy with the mean-field Ising phase transition for instance. Yet, the stability of the three fixed points is difficult to assess analytically using the evolution equation supplemented by condition on the diffusion coefficient, as one would need to determine the time-dependent distribution p(x, t). As a simplified stability analysis which is expected to provide some hints on the true stability properties, we propose to define instead a slow dynamics of the diffusion coefficient as follows: This dynamics of D coupled to Eq. shares the same stationary state as the original dynamics given by Eqs. and. Assuming the relaxation rate to be small, one can use a quasi-stationary state approximation by plugging the slowly time-dependent diffusion coefficient D(t) into the stationary solution p st (x). The solutions D 0 and D 0 (D 0 < D 0 ) satisfy f 0 (D 0 ) = g(D 0 ) with f 0 (D 0 ) < g (D 0 ), and f 0 (D 0 ) = g(D 0 ) with f 0 (D 0 ) > g (D 0 ) (see Fig. 1, where the full line represents f 0 (D) and the dot-dashed line corresponds to g(D) in the case of interest here). The function F (D) introduced in Eq. can be rewritten as so that D 0 and D 0 are indeed fixed points of the dynamics given in Eq.. The stability of these fixed points is determined by the sign of F (D 0 ) and F (D 0 ). For a fixed point D * ∈ {D 0, D 0 }, one finds It follows that F (D 0 ) < 0 and F (D 0 ) > 0: D 0 is a stable fixed point, and D 0 is an unstable fixed point. The instability of the fixed point D 0, which satisfies D h < D 0 < D 0, also implies from the one-dimensional character of the flow of D that D h is a stable fixed point. The average position x behaves very differently for the two fixed points. For the fixed point D 0, corresponding to a finite diffusion coefficient, the average position behaves again as in Eq.. In contrast, for the fixed point D h = |h| (with > 1), the diffusion coefficient goes to zero faster than h, and the assumption h/D → 0 used to derive Eq. breaks down. However, the situation is physically quite clear. Diffusion is very inefficient to counteract the effect of the external field h, while the resetting process is much faster than both diffusion and bias. It follows that the stationary distribution p st (x) becomes sharply peaked around x = sgn(h), and thus x → sgn(h) when h → 0. Conclusion In this paper, we have shown that a population of random walks with stochastic resetting such that the diffusion coefficient is an increasing power law of the average resetting rate of the population exhibits a rich phenomenology, with phase transitions between a linear and a non-linear response to a small external field of the average position of the walk. When the diffusion coefficient is proportional to the average resetting rate ( = 1), the proportionality coefficient plays the role of a control parameter and the phase transition between linear and non-linear response occurs as function of, the non-linear regime corresponding to the low- phase. This case had been previously investigated in the specific context of the deformation of soft amorphous materials (the HL model ), where the random walk refers to the diffusion of the local mechanical stress. We have reformulated here the problem in the more general and abstract framework of diffusion with stochastic resetting. In addition, we have generalized the model to explore dependencies of the diffusion coefficient on the average resetting rate that were considered as unphysical in a soft matter context and thus not explored in this specific setting. For a sublinear dependence of the diffusion coefficient on the average resetting rate ( < 1), diffusion is strong enough to induce a linear response whatever the proportionality coefficient. In contrast, for a superlinear dependence ( > 1), diffusion may become so weak that the average position actually diverges in the zero external field limit. However, for a sufficiently large proportionality coefficient, a second stable solution emerges, with a finite diffusion coefficient leading to a linear response for h → 0. We have focused here on the stationary state of the model. A rich phenomenology can also be found by looking at the time-dependent behaviour of the model, as investigated in in a soft matter context with a linear dependence of the diffusion coefficient on the average resetting rate ( = 1). Investigating the time-dependent behaviour of the model for general values of could be of interest for future work. To conclude, this work describes a minimal way to introduce mean-field interactions in a population of random walks with stochastic resetting. We hope it may find applications beyond the previously studied soft matter problem, and that it may trigger further theoretical works on the more general problem of interacting random walks with resetting. Note that while the diffusion coefficient was assumed here to depend on the average resetting rate of the population, one may also assume that the external field depends on the resetting rate, as done for instance in the context of macroeconomic agent-based models.
|
NEW YORK (Reuters) - U.S. regulators are expected to announce a deal for the assets of failed mortgage lender IndyMac before the end of the year, a spokesman for the bank said on Wednesday.
The exact timing of an announcement and whether the company would be sold as a single entity or in pieces was not clear.
The deadline for final bids for IndyMac’s assets was December 15, said IndyMac spokesman Evan Wagner.
The Federal Deposit Insurance Corp aims to sell IndyMac before the end of the year, FDIC spokesman David Barr said. The FDIC estimates IndyMac’s failure cost the agency $8.9 billion.
The mortgage specialist’s IndyMac Bank unit was taken over by regulators after it failed on July 11 in one of the largest bank failures in U.S. history. At the time, it had $32 billion in assets and $19 billion in deposits.
When it failed, more than 130 FDIC employees swooped in on the California-based mortgage lender to prepare it to reopen under government management as IndyMac Federal Bank. Another 120 employees took part remotely via computer links.
IndyMac Bancorp Inc, the holding company, filed for Chapter 7 protection soon after with the U.S. bankruptcy Court in Los Angeles, indicating it plans to liquidate.
Founded in 1985 by Angelo Mozilo and David Loeb, who also founded Countrywide Financial Corp, IndyMac once specialized in “Alt-A” home loans, which often didn’t require borrowers to fully document income or assets.
It collapsed after defaults mounted and as tight capital markets caused losses on mortgages it couldn’t sell.
The seizure came after panicked customers withdrew more than $1.3 billion of deposits over 11 business days. The withdrawals followed comments in late June by U.S. Sen. Charles Schumer questioning IndyMac’s survival.
|
// Copyright (c) 2006-2018 <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifdef CDSUNIT_ENABLE_BOOST_CONTAINER
#if CDS_THREADING_HPX
#include <hpx/config.hpp>
#endif
#include <boost/version.hpp>
#include <cds/details/defs.h>
#if BOOST_VERSION >= 104800
#include <cds/container/striped_set/boost_stable_vector.h>
#include "test_striped_set.h"
namespace {
struct test_traits
{
typedef boost::container::stable_vector< cds_test::container_set::int_item > container_type;
struct copy_policy {
typedef container_type::iterator iterator;
void operator()( container_type& vec, iterator itInsert, iterator itWhat )
{
vec.insert( itInsert, *itWhat );
}
};
static bool const c_hasFindWith = true;
static bool const c_hasEraseWith = true;
};
INSTANTIATE_TYPED_TEST_CASE_P( BoostStableVector, StripedSet, test_traits );
INSTANTIATE_TYPED_TEST_CASE_P( BoostStableVector, RefinableSet, test_traits );
} // namespace
#else // BOOST_VERSION < 104800
// Skipped; for boost::container::stable_vector you should use boost version 1.48 or above
#endif // BOOST_VERSION
#endif // CDSUNIT_ENABLE_BOOST_CONTAINER
|
package com.spring.model;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import com.spring.model.MemberVO;
@Repository
public class MemberDAO implements InterMemberDAO {
@Resource
private SqlSessionTemplate sqlsession;
// === 로그인 처리하기 === //
@Override
public MemberVO getLoginMember(HashMap<String, String> paraMap) {
MemberVO loginuser = sqlsession.selectOne("finalproject4.getLoginMember", paraMap);
return loginuser;
}
// 마지막으로 로그인 한 날짜시간 변경(기록)하기
@Override
public void setLastLoginDate(HashMap<String, String> paraMap) {
sqlsession.update("finalproject4.setLastLoginDate", paraMap);
}
///////////// ~~~ 카카오 ~~~ //////////////
@Override
public MemberVO kakaoMember(HashMap<String, String> paraMap) {
MemberVO loginuser = sqlsession.selectOne("finalproject4.kakaoMember", paraMap);
return loginuser;
}
// 아이디 중복 유무
@Override
public String idDuplicateCheck(String userid) {
String id = sqlsession.selectOne("finalproject4.idDuplicateCheck", userid);
return id;
}
// 카카오 회원가입
@Override
public int kakaoRegister(MemberVO membervo) {
int n = sqlsession.insert("finalproject4.kakaoRegister", membervo);
return n;
}
// 이메일 중복 유무
@Override
public String emailDuplicateCheck(String email) {
String i = sqlsession.selectOne("finalproject4.emailDuplicateCheck", email);
return i;
}
// 일반 회원 가입
@Override
public int register(MemberVO membervo) {
int n = sqlsession.insert("finalproject4.register", membervo);
return n;
}
// 카카오 로그인시 kakaoStatus 1로 변경
@Override
public void kakaoStatus(String email) {
sqlsession.update("finalproject4.kakaoStatus", email);
}
// 네이버 로그인시 naverStatus 1로 변경
@Override
public void naverStauts(String email) {
sqlsession.update("finalproject4.naverStatus", email);
}
// 네이버 회원가입
@Override
public int naverRegister(MemberVO membervo) {
int n = sqlsession.insert("finalproject4.naverRegister", membervo);
return n;
}
// 회원 수정 페이지
@Override
public MemberVO modifyInfo(String idx) {
MemberVO mvo = sqlsession.selectOne("finalproject4.modifyInfo", idx);
return mvo;
}
// 회원 수정
@Override
public int modifyEnd(HashMap<String, String> paraMap) {
int n = sqlsession.update("finalproject4.modifyEnd", paraMap);
return n;
}
// 세션 id, 유효시간
@Override
public void keepLogin(HashMap<String, Object> map) {
sqlsession.update("finalproject4.keepLogin", map);
}
@Override
public MemberVO checkUserWithSessionKey(String sessionId) {
MemberVO mvo = sqlsession.selectOne("finalproject4.checkUserWithSessionKey", sessionId);
return mvo;
}
// 회원 탈퇴
@Override
public int infoDelete(HashMap<String, String> paraMap) {
int n = sqlsession.update("finalproject4.infoDelete", paraMap);
return n;
}
// 아이디 찾기
@Override
public String findID(HashMap<String, String> paraMap) {
String userid = sqlsession.selectOne("finalproject4.findID", paraMap);
return userid;
}
// 비밀번호 찾기
@Override
public String findPW(HashMap<String, String> paraMap) {
String findPW = sqlsession.selectOne("finalproject4.findPW", paraMap);
return findPW;
}
// 비밀번호 변경
@Override
public int updatePW(HashMap<String, String> paraMap) {
int n = sqlsession.update("finalproject4.updatePW", paraMap);
return n;
}
// 적립금 내역
@Override
public List<HashMap<String, String>> pointList(String userid) {
List<HashMap<String, String>> pointList = sqlsession.selectList("finalproject4.pointList", userid);
return pointList;
}
// 나의 문의 내역
@Override
public List<HashMap<String, String>> qnaList(String userid) {
List<HashMap<String, String>> qnaList = sqlsession.selectList("finalproject4.qnaList3", userid);
return qnaList;
}
// 내 문의 개수
@Override
public String qnaCount(String userid) {
String qnaCount = sqlsession.selectOne("finalproject4.qnaCount", userid);
return qnaCount;
}
// 내 쿠폰 개수
@Override
public String couponCount(String userid) {
String couponCount = sqlsession.selectOne("finalproject4.couponCount", userid);
return couponCount;
}
// 쿠폰 내역
@Override
public List<HashMap<String, String>> couponList(String userid) {
List<HashMap<String, String>> couponList = sqlsession.selectList("finalproject4.couponList", userid);
return couponList;
}
// 관리자 답변 내역
@Override
public List<HashMap<String, String>> qnaList2(String userid) {
List<HashMap<String, String>> qnaList2 = sqlsession.selectList("finalproject4.qnaList2", userid);
return qnaList2;
}
// 내 예매 내역
@Override
public List<HashMap<String, String>> myReserveList(String userid) {
List<HashMap<String, String>> myReserveList = sqlsession.selectList("finalproject4.myReserveList", userid);
return myReserveList;
}
// 내 예매 개수
@Override
public String reserveCount(String userid) {
String reserveCount = sqlsession.selectOne("finalproject4.reserveCount", userid);
return reserveCount;
}
// 내 리뷰 내역
@Override
public List<HashMap<String, String>> myReviewList(String userid) {
List<HashMap<String, String>> myReviewList = sqlsession.selectList("finalproject4.myReviewList", userid);
return myReviewList;
}
// 내 리뷰 개수
@Override
public String reviewCount(String userid) {
String reviewCount = sqlsession.selectOne("finalproject4.reviewCount", userid);
return reviewCount;
}
// 내 선호 공연 내역
@Override
public List<HashMap<String, String>> myLikeList(String userid) {
List<HashMap<String, String>> myLikeList = sqlsession.selectList("finalproject4.myLikeList", userid);
return myLikeList;
}
// 선호 공연 개수
@Override
public String likeCount(String userid) {
String likeCount = sqlsession.selectOne("finalproject4.likeCount", userid);
return likeCount;
}
// 마이티켓에서 내 리뷰 삭제
@Override
public int myReviewDelete(HashMap<String, String> paraMap) {
int n = sqlsession.update("finalproject4.myReviewDelete", paraMap);
return n;
}
// 마이티켓에서 내 리뷰 수정
@Override
public int updateReviewEnd(HashMap<String, String> paraMap) {
int n = sqlsession.update("finalproject4.updateReviewEnd", paraMap);
return n;
}
@Override
public String getPoint(String userid) {
String point = sqlsession.selectOne("finalproject4.getPoint", userid);
return point;
}
// 예매 상세
@Override
public HashMap<String, String> infoList(String rev_id, String userid) {
HashMap<String,String> paraMap = new HashMap<String,String>();
paraMap.put("rev_id", rev_id);
paraMap.put("userid", userid);
HashMap<String, String> infoList = sqlsession.selectOne("finalproject4.infoList", paraMap);
return infoList;
}
// 좌석정보
@Override
public List<HashMap<String, String>> seatInfoList(String userid) {
List<HashMap<String, String>> seatInfoList = sqlsession.selectList("finalproject4.seatInfoList", userid);
return seatInfoList;
}
// 예매 취소
@Override
public int bookingCancel(HashMap<String, String> paraMap) {
int n = sqlsession.update("finalproject4.bookingCancel", paraMap);
return n;
}
// 예매 했던 좌석 취소
@Override
public int updateSeatStatus(HashMap<String, String> paraMap) {
int x = sqlsession.update("finalproject4.updateSeatStatus", paraMap);
return x;
}
}
|
// Method to calculate k'ya.
public double calculate_kya() {
this.g_kya = Math.pow((this.g_S / this.g_V * 0.226 / this.g_F_p * Math.pow(this.g_Schmidt_Gas / 0.66, 0.5)
* Math.pow(this.g_G_L / 6.782, -0.5) * Math.pow(this.g_G_V / 0.678, 0.35)), -1);
return this.g_kya;
}
|
Officers were called to Royal Exchange Square around 6pm on Saturday October 13 after reports of an incident.
Pub-goers at the scene of a police incident in Glasgow City centre tonight say two homeless men were involved in a fight.
A police cordon was put up outside the Di Maggio's restaurant as cops confirmed they attended the scene.
Pub-goers who were in the area at the time said a fight had broken out between two homeless men.
One said: "There were a few policemen here and they put up tape around the scene. "It looked like a couple of homeless folk were fighting with each other.
"It was all over quite quickly and then things got back to normal."
|
#!/usr/bin/env python
# coding: utf-8
## Predictions Class
import cv2 as cv
import numpy as np
from tts import speak
class Predictions():
'''Provides predictions for a given binary frame where
the noise in the image has been removed.
PARAMETERS: basis: string -> "mean" or "median"
how do you provide the output
for the lane that you acquired
threshold: float(0,1) : how closely you
want the lane to be detected relative
to center of image '''
def __init__(self,basis = "mean",
threshold = 0.1):
if(basis not in ["mean","median"]):
raise ValueError("Basis should be either mean or median")
self.basis = basis
if(threshold <=0 or threshold>=1 ):
raise ValueError("Invalid range for threshold")
self.threshold = threshold
def get_lane_middle(self,img,X):
'''RETURNS: middle x co-ordinate based on the
basis defined in class parameters '''
if(self.basis == "mean"):
try:
mid = int(np.mean(X))
except:
mid = img.shape[1]//2
else:
try:
mid = int(np.median(X))
except:
mid = img.shape[1]//2
return mid
def shifted_lane(self,frame,deviation):
'''Generates outputs for where to shift
given the deviation of the lane center
with the image center orientation
RETURNS: frame with shift outputs '''
height,width = frame.shape[0],frame.shape[1]
shift_left = ["Lane present on left","Shift left"]
shift_right = ["Lane present on right","Shift right"]
if(deviation < 0):
# means person on the right and lane on the left
# need to shift left
cv.putText(frame,shift_left[0],(40,40),5,1.1,(100,10,255),2)
cv.putText(frame,shift_left[1],(40,70),5,1.1,(100,10,255),2)
# speak(shift_left)
else:
# person needs to shift right
cv.putText(frame,shift_right[0],(40,40),5,1.1,(100,255,10),2)
cv.putText(frame,shift_right[1],(40,70),5,1.1,(100,255,10),2)
# speak(shift_right)
return frame
def get_outputs(self,frame,points):
'''Generates predictions for walking
on a lane
PARAMETERS: frame : original frame on which we draw
predicted outputs. This already has the
lanes drawn on it
points : list of 2-tuples : the list
which contains the points of the lane
which is drawn on the image
RETURNS : a frame with the relevant outputs
'''
height,width = frame.shape[0], frame.shape[1]
# get the center of frame
center_x = width//2
# get the distribution of points on
# left and right of image center
left_x,right_x = 0,0
X = []
for i in points:
for k in i:
x = k[0]
if(x < center_x):
left_x+=1
else:
right_x+=1
X.append(k[0])
# get the lane middle and draw
try:
lane_mid = self.get_lane_middle(frame,X)
except:
lane_mid = center_x
cv.line(frame,(lane_mid,height-1),(lane_mid,height - width//10),(0,0,0),2)
# calculate shift
shift_allowed = int(self.threshold*width)
# calculate deviations and put on image
deviation = lane_mid - center_x
deviation_text = "Deviation: "+str(np.round((deviation * 100/width),3)) + "%"
cv.putText(frame,deviation_text,(int(lane_mid-60),int(height-width//(9.5))),1,1.3,(250,20,250),2)
# speak(deviation_text)
if(abs(deviation) >= shift_allowed):
# large deviation : give shift outputs only
frame = self.shifted_lane(frame,deviation)
return frame
else:
# if deviation lesser then that means either correct path
# or a turn is approaching : text put at the center of the
# frame
total_points= left_x + right_x
correct = ["Good Lane Maintainance"," Continue straight"]
left_turn = ["Left turn is approaching","Please start turning left"]
right_turn = ["Right turn is approaching","Please start turning right"]
# if relative change in percentage of points is < 10% then
# going fine
try:
left_perc = left_x*100/(total_points)
right_perc = right_x*100/(total_points)
except:
left_perc = 50
right_perc = 50
if(abs(left_perc - right_perc) < 25):
cv.putText(frame,correct[0],(40,40),5,1.1,(100,255,10),2)
cv.putText(frame,correct[1],(40,70),5,1.1,(100,255,10),2)
# speak(correct)
else:
if(left_perc > right_perc): # more than 25% relative change
# means a approximately a right turn is approaching
cv.putText(frame,right_turn[0],(40,40),5,1.1,(100,10,255),2)
cv.putText(frame,right_turn[1],(40,70),5,1.1,(100,10,255),2)
# speak(right_turn)
else:
cv.putText(frame,left_turn[0],(40,40),5,1.1,(100,10,255),2)
cv.putText(frame,left_turn[1],(40,70),5,1.1,(100,10,255),2)
# speak(left_turn)
# return the frame with the outputs
# to-do : output with sound
return frame
|
import moment from 'moment';
import { sortByKey } from '@utils/tools/array';
import { useTranslation } from 'react-i18next';
import Icon from '@components/Icon';
const Timers = ({ TimerItems }) => {
const { t } = useTranslation();
return (
<div className="h-full grid" style={{ width: 'calc(905px - 504px - 30px)' }}>
<div className="grid grid-rows-2 grid-cols-3 w-full rounded-8 gap-6">
{sortByKey(TimerItems, 'date').map(({ icon: iconKey, date, name }) => {
const time = [moment(date).fromNow(true), `${moment(date).diff(this, 'days').toString()} days`];
return (
<div
className="bg-primary-800 h-widget rounded-8 text-primary-200 cursor-pointer text-center py-4 flex flex-col items-center border-primary-800"
key={name}
title={time[1]}
>
<Icon icon={iconKey} className="h-4 w-4 mb-2" />
<p className="small font-semibold text-primary-100 mb-1">{t(`pages.hub.timer.${name}`)}</p>
<p className="reallySmall">{time[0]}</p>
</div>
);
})}
</div>
</div>
);
};
export default Timers;
|
Influence of complex formation on membrane transport. Abstract Theoretical aspects of the influence of complex formation on transport across a diffusional barrier of three species, participating in an association-dissociation reaction, are presented. On the basis of solution of a nonlinear differential equation derived from equations of continuity, valid for stationary states, when diffusion coefficients are constants and coupling between fluxes of different species is ignored, it is shown that the usual assumption that the complex formation reaction is at equilibrium at all locations in the system is not valid, except when the concentration of one of the reactant species is maintained equal on both sides of the membrane. In the general case, methods of calculation of reactionrate profiles and concentration profiles to any desired order of approximation in the inhomogeneous diffusional barrier region from experimentally measurable quantities are included. The method of computing the association-rate and dissociation-rate constants from suitable transport measurements is presented.
|
Wage-Earners and/or Co-Workers? Contested Identities When it came to the accumulation of working-class powera resources in the Fordist era, the Swedish labour movement was rightly considered the paradigm exemplar. With the adoption of its new strategy, 'solidaristic work for solidaristic wages', Swedish labour also seemed to have developed its own preferred vision of a post-Fordist future. Whether it will actually have the strength required to shape the terms of restructuring, however, is very much dependent on the outcome of a current struggle over the meaning of a new identity, 'co-worker' (medarbetare). Medarbetare traditionally functioned as a synonym for 'colleague' and thus was used to refer to those with high-status jobs who enjoyed a peer relationship with their co-workers and immediate boss. The term has now become an important element in the struggle over the core identity of the social figures who will shape the parameters of post-Fordist Sweden. Are the new medarbetare to be individuated members of the corporate team, as the leading firms in SAF would have it, or will they be the counterpart in production of the old alliance of lontagare (wage-earners) constituted in the sphere of distribution? That is the question to be explored in this article.
|
def squash_mask(self, *args, leave_parametrized=True, names=None, **kwargs):
if names is None:
names = list(self.data_groups.keys())
for name in names:
parametrize.remove_parametrizations(self._container, name, leave_parametrized=leave_parametrized)
|
<gh_stars>1-10
import QueryString from 'query-string';
export function queryfy(obj: Record<string, any>): string {
return QueryString.stringify(obj, {
skipNull: true,
skipEmptyString: true,
encode: true,
arrayFormat: 'comma',
});
}
export type PaginatedResult<T extends Record<string, any>> = {
data: T[];
meta: {
count: number;
block: number;
};
};
|
In recent years, films from Ex Machina to Her have caused millions of moviegoers to ask haunting questions about where “machine” ends and “human” begins. And their themes may not be so farfetched. Thanks to several key breakthroughs, AI technologies are making the leap from science fiction to the real world. They are revolutionizing how individuals make decisions, marketers target consumers, and companies do business. In the coming years, as AI continues advancing, it promises to scaffold a brave new world for the Homeland Generation—in ways some cheer, others fear, and in plenty that we have yet to understand.
Artificial intelligence refers to the development of machines and software that simulate human intuition. The field can be divided into two broad categories: efforts focused on interpreting sophisticated input (such as speech, emotions, or coordinated movements) and those aiming to recreate higher-level cognitive capabilities like learning and decision-making. Already, AI-powered systems from antilock brakes to Siri have come to surround us in everyday life, and recently these examples have grown in ambition and scale to include drones, self-driving cars, and humanoid robots.
Most of these advances have been pioneered by tech titans. Alongside Google, Microsoft, and Apple are IBM, Amazon, and Facebook, each of whom have poured billions of dollars into AI since 2010 in a race to command the field. Meanwhile, startups Affectiva, Vicarious, and Sentient tackle technological issues such as emotion analytics, image recognition, and data analytics. According to estimates from the business analytics firm Quid, AI has drawn more than $17 billion in investments since 2009.
These new capabilities are making a measurable impact on virtually every industry. AI is being used to spot financial fraud; help doctors diagnose illnesses; write news stories; carry out tasks in hazardous situations; and generate irresistible advertising copy. Where AI is most valuable, however, is in industries with the most data to crunch and high-value problems to solve—such as insurance, health care, and cybersecurity.
Long considered the stuff of science fiction, AI’s great leap forward has been driven by a perfect storm of technological change. First is a growth in capabilities: Rapid advancements in computing power and falling hardware costs have made AI-related computations much cheaper to perform. Second is the advent of Big Data, which has enabled deep-learning algorithms in which the systems themselves learn bottom-up from a vast, fast-expanding universe of digital information.
Tech gurus speculate that the marriage of Big Data, the Internet of Things, and AI will eventually result in “ambient intelligence”—an ever-present digital fog in tune with our behavior and physiological state. Affectiva’s founder, Rana el Kaliouby, predicts in The New Yorker that before long, devices will have an “emotion chip” that functions unseen in the background the way that geolocation does in phones. Verizon has drafted plans for a sensor-laden media console that could scan a room and determine a driver’s license worth of information about its occupants. All these data would then determine the console’s selection of TV advertising: Signs of stress might prompt a commercial for a vacation, while cheery humming could result in more ads with upbeat messages.
What kind of mark will AI ultimately leave on society? Observers are deeply divided. A majority of the experts surveyed in a recent Pew study see AI as a largely positive breakthrough that will help people accomplish more than ever before. The transhumanist movement even goes so far as to predict that humans will eventually merge with machines and become immortal.
Countering them are cautious voices like Erik Brynjolfsson and Andrew McAfee, who argue in their book The Second Machine Age that these technologies will displace lower-level workers and exacerbate income inequality. More drastically, tech luminaries from Bill Gates to Elon Musk have expressed fears that a Skynet-style uprising might not be far behind. Stephen Hawking even warns that the development of AI “could spell the end of the human race.”
These divergent views don’t even bother with the disorienting moral issues that AI will inevitably raise. Most frequently discussed is privacy: Emotionally aware technology could easily cross the line into intrusiveness. Author Clive Thompson offers the example of an insurance company that raises its fees once customers show signs of being ill. Another issue is accountability: Some argue that high-stakes decisions like loan approvals should require human oversight. Moreover, AI broaches uncharted legal waters. Who is responsible, for example, if a self-driving car crashes? How should autonomous weapons be treated under international law?
Responses to AI also vary significantly by generation. Boomers, interested in the “why” behind every choice, are uneasy about the idea of machines operating according to rules no one understands. These suspicions are also shared by Generation X—though Xers are more likely to let those concerns slide if they see the use of AI resulting in measurable benefits. Overall, however, neither of these generations would be comfortable with an all-encompassing “personal assistant” mindset (in which a meta-layer of intelligence draws from multiple apps at once to solve a wide range of problems) that would allow AI to work to its full potential.
Millennials, on the other hand, may see AI as simply the next phase in an always-on world that they take for granted. They don’t need to know how it works, only that it does—and view technology, even with its pitfalls, as a positive force that has largely improved their lives.
In any case, we’re still far from immersive AI being considered a normal part of life. It won’t be until the Homeland Generation comes of age that many of these questions will reflect realities rather than speculation. But the future starts now—and with it, a grand evolution in the way we interact and relate to the world around us. As el Kaliouby remarks: “I think that, ten years down the line, we won’t remember what it was like when we couldn't just frown at our device, and our device would say, ‘Oh, you didn't like that, did you?’”
|
from otree.views.export import get_export_response
import vanilla
from .export import export_wide
from otree.models import Session
from django.shortcuts import render
# BLOCK FOR MTURK HITS
from django.conf import settings
from otree.views.mturk import get_mturk_client
from botocore.exceptions import NoCredentialsError, EndpointConnectionError
import json
from django.core.urlresolvers import reverse, reverse_lazy
import otree_export_utils.forms as forms
from django.http import JsonResponse, HttpResponseRedirect
from datetime import datetime, timedelta, timezone
from dateutil import tz
# END OF BLOCK
# BLOCK FOR TESTING JSON THINGS
from django.http import JsonResponse
from django.template.loader import render_to_string
from .forms import (UpdateExpirationForm)
# END OF BLOCK
from contextlib import contextmanager
def check_if_deletable(h):
if (h['HITStatus'] == 'Reviewable' and
h['NumberOfAssignmentsCompleted'] +
h['NumberOfAssignmentsAvailable'] == h['MaxAssignments']):
h['Deletable'] = True
return h
NO_CRED_ERR_CODE = 0
NO_CONN_ERR_CODE = 1
class MturkClient(object):
client = None
errors = None
def get_errors(self):
if self.errors == NO_CONN_ERR_CODE:
return 'Sorry, there is no connection to Amazon mTurk web-site. Check your internet connection.'
if self.errors == NO_CRED_ERR_CODE:
return 'Sorry, I cannot find your Amazon credentials. Check your environment variables.'
def __init__(self, use_sandbox=True):
try:
self.client = get_mturk_client(use_sandbox=use_sandbox)
self.client.get_account_balance()
except NoCredentialsError:
self.client = None
self.errors = NO_CRED_ERR_CODE
except EndpointConnectionError:
self.client = None
self.errors = NO_CONN_ERR_CODE
class SpecificSessionDataView(vanilla.TemplateView):
def get(self, request, *args, **kwargs):
session_code = kwargs['session_code']
response, file_extension = get_export_response(
request, session_code)
export_wide(response, file_extension, session_code=session_code)
return response
class AllSessionsList(vanilla.TemplateView):
template_name = 'otree_export_utils/all_session_list.html'
url_name = 'individual_sessions_export'
url_pattern = r'^individual_sessions_export/$'
display_name = 'Exporting data from individual sessions'
def get(self, request, *args, **kwargs):
all_sessions = Session.objects.all()
return render(request, self.template_name, {'sessions': all_sessions})
class HitsList(vanilla.TemplateView):
template_name = 'otree_export_utils/hits_list.html'
url_name = 'hits_list'
url_pattern = r'^hits_list/$'
display_name = 'mTurk HITs'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
mturk = MturkClient()
client = mturk.client
if client is not None:
balance = client.get_account_balance()['AvailableBalance']
hits = client.list_hits()['HITs']
for h in hits:
h = check_if_deletable(h)
context['balance'] = balance
context['hits'] = hits
else:
context['mturk_errors'] = mturk.get_errors()
return context
class AssignmentListView(vanilla.TemplateView):
template_name = 'otree_export_utils/assignments_list.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
current_hit_id = self.kwargs.get('HITId')
mturk = MturkClient()
client = mturk.client
if client is not None:
cur_hit = check_if_deletable(client.get_hit(HITId=current_hit_id).get('HIT'))
context['hit'] = cur_hit
assignments = client.list_assignments_for_hit(HITId=current_hit_id)['Assignments']
submitted_assignments = bool(
{'Submitted', 'Rejected'} & set([a['AssignmentStatus'] for a in assignments]))
context['assignments'] = assignments
context['submitted_assignments'] = submitted_assignments
else:
context['mturk_errors'] = mturk.get_errors()
return context
class SendSomethingView(vanilla.FormView):
HITId = None
AssignmentId = None
WorkerId = None
Assignment = None
def dispatch(self, request, *args, **kwargs):
mturk = MturkClient()
client = mturk.client
if client is not None:
self.assignment = client.get_assignment(AssignmentId=kwargs['AssignmentID'])['Assignment']
self.AssignmentId = self.assignment['AssignmentId']
self.WorkerId = self.assignment['WorkerId']
self.HITId = self.assignment['HITId']
else:
self.context['mturk_errors'] = mturk.get_errors()
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['assignment'] = self.assignment
return context
def get_success_url(self):
return reverse('assignments_list', kwargs={'HITId': self.HITId})
class SendMessageView(SendSomethingView):
form_class = forms.SendMessageForm
template_name = 'otree_export_utils/send_message.html'
def form_valid(self, form):
mturk = MturkClient()
client = mturk.client
if client is not None:
sending_message = client.notify_workers(
Subject=form.cleaned_data['subject'],
MessageText=form.cleaned_data['message_text'],
WorkerIds=[self.WorkerId, ]
)
return super().form_valid(form)
class SendBonusView(SendSomethingView):
template_name = 'otree_export_utils/send_bonus.html'
form_class = forms.SendBonusForm
def get_form(self, data=None, files=None, **kwargs):
max_bon = 100
mturk = MturkClient()
client = mturk.client
if client is not None:
response = client.list_bonus_payments(
HITId=self.HITId,
MaxResults=100,
)
bs = response['BonusPayments']
today = datetime.utcnow().date()
start = datetime(today.year, today.month, today.day, tzinfo=tz.tzutc())
recent_bs = [float(i['BonusAmount']) for i in bs if i['GrantTime'] > start]
tot_bon = sum([i for i in recent_bs])
max_bon = max(0, 100 - tot_bon)
cls = self.get_form_class()
return cls(data=data, files=files, max_bonus=max_bon)
def form_valid(self, form):
mturk = MturkClient()
client = mturk.client
if client is not None:
response = client.send_bonus(
WorkerId=self.WorkerId,
BonusAmount=str(form.cleaned_data['bonus_amount']),
AssignmentId=self.AssignmentId,
Reason=form.cleaned_data['reason'],
)
return super().form_valid(form)
class DeleteHitView(vanilla.View):
def get(self, request, *args, **kwargs):
mturk = MturkClient()
client = mturk.client
if client is not None:
cur_hit = check_if_deletable(client.get_hit(HITId=self.kwargs['HITId']).get('HIT'))
if cur_hit.get('Deletable'):
response = client.delete_hit(HITId=cur_hit['HITId'])
return HttpResponseRedirect(reverse_lazy('hits_list'))
class UpdateExpirationView(vanilla.FormView):
back_to_HIT = None
form_class = UpdateExpirationForm
template_name = 'otree_export_utils/update_expiration.html'
HITId = None
HIT = None
def get_form(self, data=None, files=None, **kwargs):
cls = self.get_form_class()
# print()
return cls(data=data, files=files, initial={'expire_time': self.HIT['Expiration']})
def get_success_url(self):
if self.back_to_HIT:
return reverse('assignments_list', kwargs={'HITId': self.HITId})
else:
return reverse_lazy('hits_list')
def dispatch(self, request, *args, **kwargs):
mturk = MturkClient()
client = mturk.client
if client is not None:
self.HITId = kwargs['HITId']
self.HIT = client.get_hit(HITId=self.HITId).get('HIT')
else:
self.context['mturk_errors'] = mturk.get_errors()
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
mturk = MturkClient()
client = mturk.client
if client is not None:
response = client.update_expiration_for_hit(
HITId=self.HITId,
ExpireAt=0 # form.cleaned_data['expire_time']
)
response = client.update_expiration_for_hit(
HITId=self.HITId,
ExpireAt=form.cleaned_data['expire_time']
)
return super().form_valid(form)
class ExpireHitView(vanilla.View):
back_to_HIT = None
def get(self, request, *args, **kwargs):
mturk = MturkClient()
client = mturk.client
if client is not None:
response = client.update_expiration_for_hit(
HITId=self.kwargs['HITId'],
ExpireAt=0,
)
if self.back_to_HIT:
return HttpResponseRedirect(reverse('assignments_list', kwargs={'HITId': self.kwargs['HITId']}))
else:
return HttpResponseRedirect(reverse_lazy('hits_list'))
class ApproveAssignmentView(vanilla.FormView):
form_class = forms.ApproveAssignmentForm
template_name = 'otree_export_utils/approve_assignment.html'
success_url = reverse_lazy('hits_list')
def get(self, request, *args, **kwargs):
return super().get(request, *args, **kwargs)
def form_valid(self, form):
mturk = MturkClient()
client = mturk.client
if client is not None:
response = client.approve_assignment(
AssignmentId=self.kwargs['AssignmentID'],
RequesterFeedback=form.cleaned_data['message_text'],
OverrideRejection=True,
)
return super().form_valid(form)
class RejectAssignmentView(vanilla.FormView):
form_class = forms.RejectAssignmentForm
template_name = 'otree_export_utils/reject_assignment.html'
success_url = reverse_lazy('hits_list')
def form_valid(self, form):
mturk = MturkClient()
client = mturk.client
if client is not None:
response = client.reject_assignment(
AssignmentId=self.kwargs['AssignmentID'],
RequesterFeedback=form.cleaned_data['message_text'],
)
return super().form_valid(form)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.