content
stringlengths 10
4.9M
|
---|
def to_collection(file_path, category):
tree = ET.parse(file_path)
root = tree.getroot()
ranges = []
for child in root.iter(category):
ranges.append(child.attrib)
text = root.find("./TEXT").text
text_list = list(text)
for tag in ranges:
start = int(tag['start'])
end = int(tag['end'])
text_list[start] = '_SEK_' + tag['TYPE'] + "_" + text_list[start]
text_list[end - 1] = text_list[end - 1]+'_ESK_'
tokenized_sen = []
tags = []
for sentence in "".join(text_list).splitlines():
if len(sentence) > 0:
temp =sent_tokenize(sentence.strip())
for s in temp:
if len(s) < 400 :
words_temp = [i for i in word_tokenize(s) if i.strip() != '']
if len(words_temp) > 0:
tokenized_sen.append(words_temp)
for i, sentence in enumerate(tokenized_sen):
has_tag = False
tag_type = ""
tag = []
for j, word in enumerate(sentence):
if len(word) == 0:
continue
if re.search(r'^_SEK_', word):
temp = word.split('_')
tag.append('B_'+temp[2])
if re.search(r'_ESK_$', word) is None:
tag_type = temp[2]
has_tag = True
tokenized_sen[i][j] = re.sub('^_SEK_'+temp[2]+"_" + '|' + '_ESK_$' ,'',word)
continue
if has_tag:
tag.append("I_"+tag_type)
else:
tag.append("O")
if re.search(r'_ESK_$', word):
has_tag = False
tokenized_sen[i][j] = re.sub(r'_ESK_$','', word)
tags.append(tag)
return tokenized_sen, tags |
/**
This test must be run under a Java5 VM - so it is *not* currently
in the test suite !!!
*/
public class Autoboxing extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Autoboxing.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void testSimpleBoxing() {
runTest("simple boxing test");
}
public void testIntegerBoxing() {
runTest("integer boxing");
}
public void testCharacterBoxing() {
runTest("char boxing");
}
public void testDoubleBoxing() {
runTest("double boxing");
}
public void testFloatBoxing() {
runTest("float boxing");
}
public void testShortBoxing() {
runTest("short boxing");
}
public void testLongBoxing() {
runTest("long boxing");
}
public void testBooleanBoxing() {
runTest("boolean boxing");
}
public void testByteBoxing() {
runTest("byte boxing");
}
public void testBoxingAfterReturning() {
runTest("boxing in after returning");
}
// CompilationResult cR = binaryWeave("testcode.jar","AspectAfterReturning.aj",0,0,"-1.5");
// //System.err.println(cR.getStandardError());
// assertTrue("Expected six weaving messages but got: "+getWeavingMessages(cR.getInfoMessages()).size(),
// getWeavingMessages(cR.getInfoMessages()).size()==6);
// RunResult rR = run("AspectAfterReturning");
// int lines = countLines(rR.getStdErr());
// assertTrue("Expected 6 lines of output but got: #"+lines+":\n"+rR.getStdErr(),lines==6);
// }
//
// public int countLines(String s) {
// int count = 0;
// while (s.indexOf("\n")!=-1) {
// count++;
// s = s.substring(s.indexOf("\n")+1);
// }
// return count;
// }
//
// protected void verify(String output,String lookingFor) {
// assertTrue("Didn't find expected string '"+lookingFor+"' in:\n"+output,output.indexOf(lookingFor)!=-1);
// }
//
} |
/**
*
* Registry of ASdu handlers, used to look up the corresponding handler for a
* specific ASdu type. Each ASdu handler should register itself to this
* registry.
*
*/
@Component
public class Iec60870ASduHandlerRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(Iec60870ASduHandlerRegistry.class);
private Map<TypeId, Iec60870ASduHandler> handlers = new EnumMap<>(TypeId.class);
public Iec60870ASduHandler getHandler(final TypeId typeId) throws Iec60870ASduHandlerNotFoundException {
if (!this.handlers.containsKey(typeId)) {
LOGGER.error("No ASdu handler found for type Id {}", typeId);
throw new Iec60870ASduHandlerNotFoundException(typeId);
}
return this.handlers.get(typeId);
}
public void registerHandler(final TypeId typeId, final Iec60870ASduHandler handler) {
this.handlers.put(typeId, handler);
}
public void clearHandlers() {
this.handlers.clear();
}
} |
<filename>examples/SNA_Examples/ExternalAdapter_asm/Adapter_comp/src/SNA_Examples_Adapter_TCP_Client.cpp<gh_stars>0
//==============================================================================
// U N C L A S S I F I E D
//==============================================================================
// Copyright (c) Northrop Grumman Corporation 2010 -- ALL RIGHTS RESERVED
//==============================================================================
/// @addtogroup Adapter_comp
/// @{
/// @file SNA_Examples_Adapter_TCP_Client.cpp
/// @brief Implementation of Adapter_TCP_Client class
//==============================================================================
#include "SNA_Examples_Adapter_TCP_Client.h"
#include "SNA_ConfigParams.h"
namespace SNA_Examples
{
//Constructor
Adapter_TCP_Client::Adapter_TCP_Client(
SNA_CompBoilerplate_t & boilerplate,
std::string configFile,
ACE_Reactor & reactor) :
connected_(false),
aIpEventHandler_(0),
boilerplate_(boilerplate),
reactor_(reactor)
{
SNA::ConfigParams hostPortCfg;
if (hostPortCfg.init(configFile))
{
hostPortCfg.lookupValue("HardwareEmulator_bin.host", host_);
hostPortCfg.lookupValue("HardwareEmulator_bin.port", port_);
}
else
{
LOG4CXX_WARN(boilerplate_.getLogger(),
"Error in lookup of HardwareEmulator_bin socket host "
"information. Using host " << host_ <<
" and default port " << port_);
}
}
//Destructor
Adapter_TCP_Client::~Adapter_TCP_Client()
{
if ( aIpEventHandler_ )
{
reactor_.remove_handler(
aIpEventHandler_,
ACE_Event_Handler::READ_MASK);
delete(aIpEventHandler_);
}
}
int Adapter_TCP_Client::connect()
{
if ( ! connected_)
{
// create the TCP socket connection
ACE_INET_Addr srvr; // contains address information
ACE_SOCK_Connector connector; // connects socket endpoints
srvr.set(port_, host_.c_str());
if (connector.connect(peer_, srvr) == -1)
{
LOG4CXX_ERROR(boilerplate_.getLogger(),
"SNA Server failed to accept");
}
else
{
//External event handler object is registered to the adapter
//component's reactor.
aIpEventHandler_ = new
::SNA_Examples::AdapterIPEventHandler(
boilerplate_.getContext(),
boilerplate_.getLoggerNamePrefix(), peer_);
reactor_.register_handler
(aIpEventHandler_,ACE_Event_Handler::READ_MASK);
connected_ = true;
// write a message with the number of read bytes
peer_.send_n("Hello", 6);
// Do not reschedule timer
return -1;
}
}
// Reschedule timer to try connecting again
return 0;
}
}
/// @}
//==============================================================================
// U N C L A S S I F I E D
//==============================================================================
|
/**
* Created by HandsomeXu on 2017/3/20.
*/
public class GuokrAdapter extends RecyclerView.Adapter<GuokrAdapter.Holder> {
private Context mContext;
private LayoutInflater mInflater;
private List<GuokrNews.Result> mList;
private OnRecyclerViewOnClickListener mListener;
public GuokrAdapter(Context context, ArrayList<GuokrNews.Result> mList) {
this.mContext = context;
this.mList = mList;
mInflater = LayoutInflater.from(context);
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.home_list_item_layout, parent, false);
return new Holder(view);
}
@Override
public void onBindViewHolder(Holder holder, int position) {
GuokrNews.Result item = mList.get(position);
Glide.with(mContext)
.load(item.getHeadline_img_tb())
.asBitmap()
.placeholder(R.mipmap.expression)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.error(R.mipmap.error)
.centerCrop()
.into(holder.imageView);
holder.textView.setText(item.getTitle());
}
@Override
public int getItemCount() {
return mList.size();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView;
public Holder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
textView = (TextView) itemView.findViewById(R.id.textViewTitle);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onItemClick(getLayoutPosition());
}
}
}
public void setOnItemClickListener(OnRecyclerViewOnClickListener listener) {
mListener = listener;
}
} |
def score_texts(self, texts, models, language, raise_on_error,
do_not_store, verbose = False):
every_5_percent = _progress_points(frac=0.05, total=len(texts))
def score_one(itext):
i, text = itext
if i in every_5_percent and verbose:
print('scoring {} of {} ({:.1f}%)'.format(
i + 1, len(texts), 100 * (i + 1) / len(texts)))
return self.score_text(text, models, language, raise_on_error,
do_not_store)
return self._executor.map(score_one, enumerate(texts)) |
def convert_str_to_int(self,string, default=100000, expect_fail=False):
try:
integer = int(string)
except Exception as e:
if not expect_fail:
self.write("Unable to convert the string %s into a number"%string)
integer = default
return integer |
/**
* Invoked from ctor to create some node Metrics.
*
* @param datanodeDetails - Datanode details
*/
private void populateNodeMetric(DatanodeDetails datanodeDetails, int x) {
SCMNodeStat newStat = new SCMNodeStat();
long remaining =
NODES[x % NODES.length].capacity - NODES[x % NODES.length].used;
newStat.set(
(NODES[x % NODES.length].capacity),
(NODES[x % NODES.length].used), remaining);
this.nodeMetricMap.put(datanodeDetails, newStat);
aggregateStat.add(newStat);
if (NODES[x % NODES.length].getCurrentState() == NodeData.HEALTHY) {
healthyNodes.add(datanodeDetails);
}
if (NODES[x % NODES.length].getCurrentState() == NodeData.STALE) {
staleNodes.add(datanodeDetails);
}
if (NODES[x % NODES.length].getCurrentState() == NodeData.DEAD) {
deadNodes.add(datanodeDetails);
}
} |
/**
* Executes example.
*
* @param args Command line arguments, none required.
* @throws Exception If example execution failed.
*/
public static void main(String[] args) throws Exception {
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
System.out.println();
System.out.println(">>> Cache continuous query example started.");
try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(CACHE_NAME)) {
int keyCnt = 20;
for (int i = 0; i < keyCnt; i++)
cache.put(i, Integer.toString(i));
ContinuousQuery<Integer, String> qry = new ContinuousQuery<>();
qry.setInitialQuery(new ScanQuery<>(new IgniteBiPredicate<Integer, String>() {
@Override public boolean apply(Integer key, String val) {
return key > 10;
}
}));
qry.setLocalListener(new CacheEntryUpdatedListener<Integer, String>() {
@Override public void onUpdated(Iterable<CacheEntryEvent<? extends Integer, ? extends String>> evts) {
for (CacheEntryEvent<? extends Integer, ? extends String> e : evts)
System.out.println("Updated entry [key=" + e.getKey() + ", val=" + e.getValue() + ']');
}
});
qry.setRemoteFilterFactory(new Factory<CacheEntryEventFilter<Integer, String>>() {
@Override public CacheEntryEventFilter<Integer, String> create() {
return new CacheEntryEventFilter<Integer, String>() {
@Override public boolean evaluate(CacheEntryEvent<? extends Integer, ? extends String> e) {
return e.getKey() > 10;
}
};
}
});
try (QueryCursor<Cache.Entry<Integer, String>> cur = cache.query(qry)) {
for (Cache.Entry<Integer, String> e : cur)
System.out.println("Queried existing entry [key=" + e.getKey() + ", val=" + e.getValue() + ']');
for (int i = keyCnt; i < keyCnt + 10; i++)
cache.put(i, Integer.toString(i));
Thread.sleep(2000);
}
}
finally {
ignite.destroyCache(CACHE_NAME);
}
}
} |
N = int(input())
i = 0
u = int(0)
for i in range(N):
I = str(i+1)
L=int(len(I))
if L % 2 == 1:
u = u + 1
print(u) |
/**
* We should call thise method whenever the core data changes (mApps, mWidgets) so that we can
* appropriately determine when to invalidate the PagedView page data. In cases where the data
* has yet to be set, we can requestLayout() and wait for onDataReady() to be called in the
* next onMeasure() pass, which will trigger an invalidatePageData() itself.
*/
private void invalidateOnDataChange() {
if (!isDataReady()) {
requestLayout();
} else {
cancelAllTasks();
invalidatePageData();
}
} |
Unilateral Exserohilum Allergic Fungal Sinusitis in a Pediatric Host: Case Report
Highlights • Exserohilum species are a very rare causative organism in allergic fungal sinusitis (AFS).• Treatment of AFS consists of medical and surgical modalities.• AFS in pediatric patients is believed to be more aggressive with a higher recurrence rate.
Introduction
Allergic fungal sinusitis (AFS) is a result of an inflammatory reaction to fungi in the nasal and paranasal sinuses . Patients with AFS usually present with chronic rhinosinusitis and nasal polyps that do not respond to conservative medical therapy . AFS can be distinguished clinically, histopathologically and by imaging from other chronic fungal sinusitis . The diagnostic criteria include type I hypersensitivity confirmed by history, skin test or serology, nasal polyposis, characteristic radiological findings, a positive fungal stain or culture and eosinophilic allergic mucin . The mainstay of AFS treatment is surgical by functional endoscopic sinus surgery (FESS) along with medical treatment . The literature reports a variety of causative agents but Exserohilum species are among the rare ones . Although a few cases of AFS have been reported previously in our region, we present a case of unilateral AFS in a pediatric male patient due to a rare Exserohilum specie . This case report has been written in line with the SCARE criteria .
Case report
We present a case of AFS who initially presented at the age of 15 years and was previously operated on in 2015 by another health care provider. The patient presented to the Otolaryngology clinic at our institution (tertiary healthcare center) in 2019, complaining of intermittent smell loss and greenish nasal discharge mainly from the right side with acute intermittent nasal obstruction. Upon physical examination, smell diskettes test showed a result of 3/8 (anosmia), with an intact subjective retronasal smell (Novimed, Hemistrasse 46 CH-8953 Dietikon, Switzerland). Rhinoscopy showed second grade polyps based on Meltzer Clinical Scoring System in the right nasal cavity and a polypoid middle turbinate in the left cavity . A computerized tomography (CT) scan of the paranasal sinuses showed thick mucosal swelling outlining the right maxillary sinus with expanded ethmoid sinus ( According to the history and physical examination a diagnosis of refractory chronic rhinosinusitis was made. The patient underwent revision FESS of the paranasal sinuses and polypectomy. Specimens taken during the surgery showed no invasive infection and the culture revealed Exserohilum species. Histopathology also reported the presence of eosinophilic infiltrate at the subepithelial and epithelial surfaces as well as the presence of fungal elements within the eosinophilic mucin (Figs. 2-4). The diagnosis of AFS was confirmed according to Bent and Kuhn's criteria . No postoperative complications were reported, the patient was discharged and given a follow up appointment in 6 months. Upon follow up, the patient's signs and symptoms were reassuring and showed satisfactory outcomes. Written informed consent was obtained from the patient for publication of this case report and accompanying images. A copy of the written consent is available for review by the Editor-in-Chief of this journal on request.
Discussion
Allergic fungal sinusitis is believed to be an allergic reaction to aerosolized fungi present in the environment, in which a fungal allergen elicits a hypersensitivity reaction, affecting the paranasal sinuses and nasal cavity by fungal debris, allergic mucin and nasal polyposis. The fungi causing AFS have been identified on a broad spectrum of species. When examined histologically, most common cultures showed Dematiaceous fungi . An epidemiological study showed the prevalence of dematiaceous fungi, especially Alternaria and Cladosporium spp. causing AFS in the United States. In contrast, 96.8% of AFS patients' isolates in India showed Aspergillus flavus . A retrospective review in Saudi Arabia was done on 45 pediatric patients, of which 25 of them met at least 4 of the diagnostic criteria of AFS. During their review, the most common fungus isolated was Aspergillus species . As per previously reported specifically in India and Saudi Arabia, the majority of cases of AFS were caused by Aspergillus flavus .
We report a case of unilateral allergic fungal sinusitis by a rare type of fungi known as Exserohilum in an immunocompetent patient of a pediatric age group. AFS in pediatric patients was suggested to be more aggressive with a higher recurrence rate as compared to adults . Of all mentioned causative organisms, infections caused by Exserohilum are rare. This type of species usually occurs in warm, tropical and subtropical areas such as the southern United States and India . In a review from a single center in the southern United States, the most common fungi recovered from the paranasal sinuses were Bipolaris, followed by Curvularia and only a total of four patients had AFS caused by Exserohilum, two of which were children . A case reported in Kuwait had a similar causative agent and age group as in our case. However, the finding in that case was bilateral in contrast to our case which is unilateral .
Conclusion
We encountered an unusual pediatric case of unilateral AFS caused by a rare Exserohilum species which to our knowledge has only been reported in a few cases . Moreover, we aim to highlight the occurrence of AFS in an immunocompetent patient by an unusual organism which is unique to our region and the clinical spectrum of allergic fungal sinusitis .
Declaration of Competing Interest
The authors report no declarations of interest.
Sources of funding
None.
Ethical approval
This study has been approved by research advisory counsel at King Faisal Specialist hospital in Riyadh Saudi Arabia (RAC #5166461).
Consent
Written informed consent has been obtained from the patient, submitted and approved by the local IRB committee.
Author contribution
Arwa Al muslat: First author, writing and editing -original draft, data collection and finalized the manuscript.
Basmah Alghmdi: First author, writing and editing -original draft, data collection and finalized the manuscript.
Abdullah J. Alshehri: Writing -review, editing and finalized the manuscript for submission.
Rakan Alhaidy: Participated in writing the discussion and literature review.
Muhammad A. Dabbabo: Contributed at managing the case, revised the manuscript.
Naif H. Alotaibi: The primary physician -treating and following up the patient, writing -supervision, critical revision of article and final approval for submission.
All authors approved the final version of the manuscript. |
//abstract class with one abstract method
static abstract class Animal {
abstract void eat();
void sleep() {
System.out.println("Animal.sleep()");
}
} |
<reponame>vishnu2981997/boundary_check
"""
routes
"""
import json
import logging
from flask import Flask
from flask_restplus import Api, Resource, fields
from utils import BoundaryCheck
APP = Flask(__name__)
APP.config['JSON_SORT_KEYS'] = False
API = Api(APP, version='1.0', title='Boundary check Api',
description='given a polygon and a point verifies if the point lies within the polygon or not')
NS = API.namespace('boundaryCheck',
description='given a polygon and a point verifies if the point lies within the polygon or not')
CITY_MODEL = API.model('city', {
"name": fields.String('Required - city name'),
"boundaries": fields.Raw('Required - city boundaries')
})
LOCATE_MODEL = API.model('locate', {
"name": fields.String('Required - city name'),
"point": fields.Raw('Required - point')
})
CITIES = {}
@NS.route('/createCity')
class CreateCity(Resource):
"""
Create City
{
"name": "a",
"boundaries": {"coords":[[0, 0], [0, 2], [2, 4], [3, 4], [3, 1]]}
}
"""
message = {"code": 500, "response": "Internal server error"}
@NS.expect(CITY_MODEL)
def post(self):
"""
create a city with boundaries
"""
try:
request = API.payload
name = request.get("name", None)
coords = None
try:
coords = json.dumps(request.get("boundaries", None))
except TypeError as exe:
logger.debug(exe)
if coords not in [None, {}] and name is not None:
if json.loads(coords):
coords = json.loads(coords)
if CITIES.get(name, None) is None:
CITIES[name] = coords["coords"]
self.message["response"] = request
self.message["code"] = 201
else:
self.message["response"] = "already exists"
self.message["code"] = 404
else:
self.message["response"] = "improper data or missing parameters"
self.message["code"] = 404
except Exception as exe:
logger.debug(exe)
return self.message
@NS.route('/checkBoundary')
class CheckBoundary(Resource):
"""
Check Boundary
for a given point check if it lies with in the plain
{
"name": "a",
"point": {"coords":{"x": 2,"y": 2}}
}
"""
message = {"code": 500, "response": "Internal server error"}
@NS.expect(LOCATE_MODEL)
def post(self):
"""check if a given point is with in a desired city"""
try:
request = API.payload
name = request.get("name", None)
point = None
try:
point = json.dumps(request.get("point", None))
except TypeError as exe:
print(exe)
if point not in [None, {}] and name is not None:
if json.loads(point):
point = json.loads(point)
if name in CITIES:
point = [point["coords"]["x"], point["coords"]["y"]]
coords = CITIES[name]
bc = BoundaryCheck(coords)
if bc.exists(point=point):
self.message["response"] = "YES"
self.message["code"] = 200
else:
self.message["response"] = "NO"
self.message["code"] = 200
else:
self.message["response"] = "Unknown city"
self.message["code"] = 404
else:
self.message["response"] = "improper data or missing parameters"
self.message["code"] = 404
except Exception as exe:
logger.debug(exe)
return self.message
if __name__ == '__main__':
logging.basicConfig(filename="logs.log", format='%(asctime)s %(message)s', filemode='a+')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
APP.run(host='0.0.0.0', debug=True, port=8008)
|
package sscape_analysis
// go tool compile -m 6_escape_2.go
// go tool compile -m=2 6_escape_2.go
func f() int {
// 这里会进行逃逸分析,a不会被分配在堆上
a := 1
c := &a
return *c
}
|
<gh_stars>0
package com.sap.cloud.lm.sl.cf.process.metadata;
import java.util.HashSet;
import java.util.Set;
import com.sap.cloud.lm.sl.cf.process.Constants;
import com.sap.cloud.lm.sl.cf.web.api.model.OperationMetadata;
import com.sap.cloud.lm.sl.cf.web.api.model.ParameterMetadata;
import com.sap.cloud.lm.sl.cf.web.api.model.ParameterMetadata.ParameterType;
import com.sap.cloud.lm.sl.mta.model.VersionRule;
public class BlueGreenDeployMetadata {
private final static Set<ParameterMetadata> PARAMS = new HashSet<ParameterMetadata>();
static {
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_APP_ARCHIVE_ID).type(ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_TARGET_NAME).type(ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_EXT_DESCRIPTOR_FILE_ID).type(ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_NO_START).defaultValue(false).type(ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_START_TIMEOUT).defaultValue(Constants.DEFAULT_START_TIMEOUT).type(
ParameterType.INTEGER).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_UPLOAD_TIMEOUT).type(ParameterType.INTEGER).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_USE_NAMESPACES).defaultValue(false).type(ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_USE_NAMESPACES_FOR_SERVICES).defaultValue(false).type(
ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_ALLOW_INVALID_ENV_NAMES).defaultValue(false).type(
ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_VERSION_RULE).defaultValue(VersionRule.SAME_HIGHER.toString()).type(
ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_DELETE_SERVICES).defaultValue(false).type(ParameterType.BOOLEAN).build());
PARAMS.add(
ParameterMetadata.builder().id(Constants.PARAM_DELETE_SERVICE_KEYS).defaultValue(false).type(ParameterType.BOOLEAN).build());
PARAMS.add(
ParameterMetadata.builder().id(Constants.PARAM_DELETE_SERVICE_BROKERS).defaultValue(false).type(ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_FAIL_ON_CRASHED).defaultValue(true).type(ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_MTA_ID).type(ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_KEEP_FILES).defaultValue(false).type(ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_NO_RESTART_SUBSCRIBED_APPS).defaultValue(false).type(
ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_GIT_URI).defaultValue("").type(ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_GIT_REF).type(ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_GIT_REPO_PATH).type(ParameterType.STRING).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_GIT_SKIP_SSL).defaultValue(false).type(ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_NO_FAIL_ON_MISSING_PERMISSIONS).defaultValue(false).type(
ParameterType.BOOLEAN).build());
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_ABORT_ON_ERROR).type(ParameterType.BOOLEAN).defaultValue(false).build());
// Special blue green deploy parameters:
PARAMS.add(ParameterMetadata.builder().id(Constants.PARAM_NO_CONFIRM).type(ParameterType.BOOLEAN).defaultValue(false).build());
}
public static OperationMetadata getMetadata() {
return OperationMetadata.builder().parameters(PARAMS).processId(Constants.BLUE_GREEN_DEPLOY_SERVICE_ID).versions(
Constants.SERVICE_VERSION_1_1, Constants.SERVICE_VERSION_1_2).build();
}
}
|
def plot_cluster_decision(x, y1, y2):
f, ax = plt.subplots(2, 1)
ax[0].plot(x, y1)
ax[0].set_ylabel("inertia")
ax[1].boxplot(y2, labels=x)
ax[1].set_xlabel('clusters number')
ax[1].set_ylabel("silhouette")
ax[0].set_title("Elbow and silhouette for KMeans")
plt.tight_layout()
return f |
/* num_stmts() returns number of contained statements.
Use this routine to determine how big a sequence is needed for
the statements in a parse tree. Its raison d'etre is this bit of
grammar:
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
A simple_stmt can contain multiple small_stmt elements joined
by semicolons. If the arg is a simple_stmt, the number of
small_stmt elements is returned.
*/
static int
num_stmts(const node *n)
{
int i, l;
node *ch;
switch (TYPE(n)) {
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE)
return 0;
else
return num_stmts(CHILD(n, 0));
case file_input:
l = 0;
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == stmt)
l += num_stmts(ch);
}
return l;
case stmt:
return num_stmts(CHILD(n, 0));
case compound_stmt:
return 1;
case simple_stmt:
return NCH(n) / 2;
case suite:
if (NCH(n) == 1)
return num_stmts(CHILD(n, 0));
else {
i = 2;
l = 0;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++)
l += num_stmts(CHILD(n, i));
return l;
}
default: {
char buf[128];
sprintf(buf, "Non-statement found: %d %d",
TYPE(n), NCH(n));
Py_FatalError(buf);
}
}
assert(0);
return 0;
} |
<reponame>asirobots/dans-gdal-scripts
/*
Copyright (c) 2013, Regents of the University of Alaska
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This code was developed by <NAME> for the Geographic Information Network of Alaska.
*/
#include "common.h"
#include "polygon.h"
#include "debugplot.h"
using namespace dangdal;
void plot_points(const Ring &pl, const std::string &fn);
struct PointStats {
PointStats() :
total(0),
proj_ok(0),
contained(0)
{ }
void printYaml(const char *label) {
printf("%s:\n", label);
printf(" total: %zd\n", total);
printf(" proj_ok: %zd\n", proj_ok);
printf(" contained: %zd\n", contained);
}
size_t total;
size_t proj_ok;
size_t contained;
};
void usage(const std::string &cmdname) {
printf("Usage: %s [options] \n", cmdname.c_str());
printf(" -s_wkt <fn> File containing WKT of source region\n");
printf(" -t_bounds_wkt <fn> File containing WKT for valid region of target SRS (optional)\n");
printf(" -s_srs <srs_def> Source SRS\n");
printf(" -t_srs <srs_def> Target SRS\n");
printf(" -report <out.ppm> Output a graphical report (optional)\n");
printf("\nOutput is the envelope of the source region projected into the target SRS.\n");
printf("If the -t_bounds_wkt option is given it will be used as a clip mask in the\n");
printf("projected space.\n");
printf("\n");
exit(1);
}
// This function transforms a point, and then as a check transforms it back to
// see if it comes back to the same place. This allows us to detect cases
// where OCTTransform reports success when really it just returned some
// meaningless result.
bool picky_transform(
OGRCoordinateTransformationH fwd_xform,
OGRCoordinateTransformationH inv_xform,
Vertex *v_in
) {
// tolerance in meters, could probably be much smaller
const double toler = 1.0;
Vertex v_out = *v_in;
if(!OCTTransform(fwd_xform, 1, &v_out.x, &v_out.y, NULL)) {
return 0;
}
Vertex v_back = v_out;
if(!OCTTransform(inv_xform, 1, &v_back.x, &v_back.y, NULL)) {
return 0;
}
double err = hypot(v_in->x - v_back.x, v_in->y - v_back.y);
//fprintf(stderr, "err=%g\n", err);
if(err > toler) {
return 0;
}
*v_in = v_out;
return 1;
}
int main(int argc, char **argv) {
const std::string cmdname = argv[0];
if(argc == 1) usage(cmdname);
std::vector<std::string> arg_list = argv_to_list(argc, argv);
std::string src_wkt_fn;
std::string t_bounds_wkt_fn;
std::string s_srs;
std::string t_srs;
std::string report_fn;
size_t argp = 1;
while(argp < arg_list.size()) {
const std::string &arg = arg_list[argp++];
// FIXME - check duplicate values
if(arg[0] == '-') {
if(arg == "-v") {
VERBOSE++;
} else if(arg == "-s_wkt") {
if(argp == arg_list.size()) usage(cmdname);
src_wkt_fn = arg_list[argp++];
} else if(arg == "-t_bounds_wkt") {
if(argp == arg_list.size()) usage(cmdname);
t_bounds_wkt_fn = arg_list[argp++];
} else if(arg == "-s_srs") {
if(argp == arg_list.size()) usage(cmdname);
s_srs = arg_list[argp++];
} else if(arg == "-t_srs") {
if(argp == arg_list.size()) usage(cmdname);
t_srs = arg_list[argp++];
} else if(arg == "-report") {
if(argp == arg_list.size()) usage(cmdname);
report_fn = arg_list[argp++];
} else {
usage(cmdname);
}
} else {
usage(cmdname);
}
}
if(src_wkt_fn.empty() || s_srs.empty() || t_srs.empty()) usage(cmdname);
GDALAllRegister();
CPLPushErrorHandler(CPLQuietErrorHandler);
///////////////////////
OGRSpatialReferenceH s_sref = OSRNewSpatialReference(NULL);
if(OSRImportFromProj4(s_sref, s_srs.c_str()) != OGRERR_NONE)
fatal_error("cannot parse proj4 definition for -s_srs");
OGRSpatialReferenceH t_sref = OSRNewSpatialReference(NULL);
if(OSRImportFromProj4(t_sref, t_srs.c_str()) != OGRERR_NONE)
fatal_error("cannot parse proj4 definition for -t_srs");
OGRCoordinateTransformationH fwd_xform =
OCTNewCoordinateTransformation(s_sref, t_sref);
OGRCoordinateTransformationH inv_xform =
OCTNewCoordinateTransformation(t_sref, s_sref);
Mpoly src_mp = mpoly_from_wktfile(src_wkt_fn);
Bbox src_bbox = src_mp.getBbox();
Mpoly t_bounds_mp;
bool use_t_bounds;
Bbox t_bounds_bbox;
if(t_bounds_wkt_fn.size()) {
use_t_bounds = 1;
t_bounds_mp = mpoly_from_wktfile(t_bounds_wkt_fn);
t_bounds_bbox = t_bounds_mp.getBbox();
} else {
use_t_bounds = 0;
}
Ring pl;
PointStats ps_border;
PointStats ps_interior;
PointStats ps_bounds;
// Sample a regular grid of points, take the ones within the source region,
// and project them to the target projection. This is done to handle the
// cases where the projected border does not necessarily encircle the
// source region (such as would be the case for a source region that
// encircles the pole with a target lonlat projection).
int num_grid_steps = 100;
for(int grid_xi=0; grid_xi<=num_grid_steps; grid_xi++) {
Vertex src_pt;
double alpha_x = (double)grid_xi / (double)num_grid_steps;
src_pt.x = src_bbox.min_x + (src_bbox.max_x - src_bbox.min_x) * alpha_x;
for(int grid_yi=0; grid_yi<=num_grid_steps; grid_yi++) {
double alpha_y = (double)grid_yi / (double)num_grid_steps;
src_pt.y = src_bbox.min_y + (src_bbox.max_y - src_bbox.min_y) * alpha_y;
if(!src_mp.contains(src_pt)) continue;
ps_interior.total++;
Vertex tgt_pt = src_pt;
if(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {
continue;
}
ps_interior.proj_ok++;
if(!use_t_bounds || t_bounds_mp.contains(tgt_pt)) {
ps_interior.contained++;
pl.pts.push_back(tgt_pt);
}
}
}
// Project points along the source region border to the target projection.
double max_step_len = std::max(
src_bbox.max_x - src_bbox.min_x,
src_bbox.max_y - src_bbox.min_y) / 1000.0;
for(size_t r_idx=0; r_idx<src_mp.rings.size(); r_idx++) {
const Ring &ring = src_mp.rings[r_idx];
for(size_t v_idx=0; v_idx<ring.pts.size(); v_idx++) {
Vertex v1 = ring.pts[v_idx];
Vertex v2 = ring.pts[(v_idx+1) % ring.pts.size()];
double dx = v2.x - v1.x;
double dy = v2.y - v1.y;
double len = sqrt(dx*dx + dy*dy);
int num_steps = 1 + (int)(len / max_step_len);
for(int step=0; step<=num_steps; step++) {
double alpha = (double)step / (double)num_steps;
Vertex src_pt;
src_pt.x = v1.x + dx * alpha;
src_pt.y = v1.y + dy * alpha;
ps_border.total++;
Vertex tgt_pt = src_pt;
if(!picky_transform(fwd_xform, inv_xform, &tgt_pt)) {
continue;
}
ps_border.proj_ok++;
if(!use_t_bounds || t_bounds_mp.contains(tgt_pt)) {
ps_border.contained++;
pl.pts.push_back(tgt_pt);
}
}
}
}
// Take points along the border of the t_bounds clip shape that lie within the
// source region.
if(use_t_bounds) {
double max_step_len = std::max(
t_bounds_bbox.max_x - t_bounds_bbox.min_x,
t_bounds_bbox.max_y - t_bounds_bbox.min_y) / 1000.0;
for(size_t r_idx=0; r_idx<t_bounds_mp.rings.size(); r_idx++) {
const Ring &ring = t_bounds_mp.rings[r_idx];
for(size_t v_idx=0; v_idx<ring.pts.size(); v_idx++) {
Vertex v1 = ring.pts[v_idx];
Vertex v2 = ring.pts[(v_idx+1) % ring.pts.size()];
double dx = v2.x - v1.x;
double dy = v2.y - v1.y;
double len = sqrt(dx*dx + dy*dy);
int num_steps = 1 + (int)(len / max_step_len);
for(int step=0; step<=num_steps; step++) {
double alpha = (double)step / (double)num_steps;
Vertex tgt_pt;
tgt_pt.x = v1.x + dx * alpha;
tgt_pt.y = v1.y + dy * alpha;
ps_bounds.total++;
Vertex src_pt = tgt_pt;
if(!picky_transform(inv_xform, fwd_xform, &src_pt)) {
continue;
}
ps_bounds.proj_ok++;
if(src_mp.contains(src_pt)) {
ps_bounds.contained++;
pl.pts.push_back(tgt_pt);
}
}
}
}
}
//bool debug = 1;
//if(debug) {
// ps_border.printYaml("stats_border");
// ps_interior.printYaml("stats_interior");
// ps_bounds.printYaml("stats_bounds");
//}
//fprintf(stderr, "got %zd points\n", pl.npts);
Bbox bbox = pl.getBbox();
printf("bounds:\n");
printf(" min_e: %.15f\n", bbox.min_x);
printf(" min_n: %.15f\n", bbox.min_y);
printf(" max_e: %.15f\n", bbox.max_x);
printf(" max_n: %.15f\n", bbox.max_y);
if(report_fn.size()) plot_points(pl, report_fn);
return 0;
}
void plot_points(const Ring &pl, const std::string &fn) {
Bbox bbox = pl.getBbox();
bbox.min_x -= (bbox.max_x - bbox.min_x) * .05;
bbox.max_x += (bbox.max_x - bbox.min_x) * .05;
bbox.min_y -= (bbox.max_y - bbox.min_y) * .05;
bbox.max_y += (bbox.max_y - bbox.min_y) * .05;
double W = bbox.max_x - bbox.min_x;
double H = bbox.max_y - bbox.min_y;
DebugPlot dbuf(W, H, PLOT_NORMAL);
for(size_t i=0; i<pl.pts.size(); i++) {
Vertex v = pl.pts[i];
double x = v.x - bbox.min_x;
double y = bbox.max_y - v.y;
dbuf.plotPoint(x, y, 255, 255, 255);
}
dbuf.writePlot(fn);
}
|
def from_jd(jd):
year = gregorian.from_jd(jd)[0]
day = jwday(jd) + 1
dayofyear = ordinal.from_jd(jd)[1]
week = trunc((dayofyear - day + 10) / 7)
if week < 1:
week = weeks_per_year(year - 1)
year = year - 1
elif week == 53 and weeks_per_year(year) != 53:
week = 1
year = year + 1
return year, week, day |
def remove_remote(self, remote_name: Optional[str] = "origin") -> None:
try:
logger.info(f"Removing remote {remote_name} from {str(self)}")
self.git.remove_remote(remote_name)
except Exception as e:
raise GigantumException(e) |
/**
* @ClassName ProductCategory
* @Author fan
* @Date 2019-01-02 15:43
* @Version 1.0
**/
@Entity
@Table(name = "product_category")
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
@ToString
public class ProductCategory {
/**
*
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer categoryId;
/**
* 类目名字
*/
private String categoryName;
/**
* 类目编号
*/
private Integer categoryType;
/**
* 创建时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
@org.hibernate.annotations.CreationTimestamp
private Date createTime;
/**
* 修改时间
*/
@org.hibernate.annotations.UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;
} |
package org.smartregister.anc.library.fragment;
import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.smartregister.anc.library.R;
import org.smartregister.anc.library.activity.BaseHomeRegisterActivity;
import org.smartregister.view.activity.BaseRegisterActivity;
@SuppressLint("ValidFragment")
public class NoMatchDialogFragment extends DialogFragment {
private final NoMatchDialogActionHandler noMatchDialogActionHandler = new NoMatchDialogActionHandler();
private final BaseRegisterActivity baseRegisterActivity;
private final String whoAncId;
public NoMatchDialogFragment(BaseRegisterActivity baseRegisterActivity, String whoAncId) {
this.whoAncId = whoAncId;
this.baseRegisterActivity = baseRegisterActivity;
}
@Nullable
public static NoMatchDialogFragment launchDialog(BaseRegisterActivity activity, String dialogTag, String whoAncId) {
NoMatchDialogFragment noMatchDialogFragment = new NoMatchDialogFragment(activity, whoAncId);
if (activity != null) {
FragmentTransaction fragmentTransaction = activity.getFragmentManager().beginTransaction();
Fragment prev = activity.getFragmentManager().findFragmentByTag(dialogTag);
if (prev != null) {
fragmentTransaction.remove(prev);
}
fragmentTransaction.addToBackStack(null);
noMatchDialogFragment.show(fragmentTransaction, dialogTag);
return noMatchDialogFragment;
} else {
return null;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog);
}
@Override
public void onCancel(DialogInterface dialogInterface) {
super.onCancel(dialogInterface);
baseRegisterActivity.setSearchTerm("");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup dialogView = (ViewGroup) inflater.inflate(R.layout.dialog_no_woman_match, container, false);
Button cancel = dialogView.findViewById(R.id.cancel_no_match_dialog);
cancel.setOnClickListener(noMatchDialogActionHandler);
Button advancedSearch = dialogView.findViewById(R.id.go_to_advanced_search);
advancedSearch.setOnClickListener(noMatchDialogActionHandler);
return dialogView;
}
////////////////////////////////////////////////////////////////
// Inner classes
////////////////////////////////////////////////////////////////
private class NoMatchDialogActionHandler implements View.OnClickListener {
@Override
public void onClick(View view) {
int i = view.getId();
if (i == R.id.cancel_no_match_dialog) {
dismiss();
baseRegisterActivity.setSearchTerm("");
} else if (i == R.id.go_to_advanced_search) {
baseRegisterActivity.setSearchTerm("");
goToAdvancedSearch(whoAncId);
baseRegisterActivity.setSelectedBottomBarMenuItem(R.id.action_search);
dismiss();
}
}
private void goToAdvancedSearch(String whoAncId) {
((BaseHomeRegisterActivity) baseRegisterActivity).startAdvancedSearch();
android.support.v4.app.Fragment currentFragment =
baseRegisterActivity.findFragmentByPosition(BaseRegisterActivity.ADVANCED_SEARCH_POSITION);
((AdvancedSearchFragment) currentFragment).getAncId().setText(whoAncId);
}
}
}
|
//NewNatsPublisher creates an instance of the NATS publisher handler.
// It transforms the received HTTP request using the transformMessageFunc into a message, publishes the message to NATS and
// returns the http response built using buildResponseFunc
func NewNatsPublisher(config Config, options ...Option) (handler.Func, CloseConnectionFunc, error) {
config.transformMessageFunc = NoTransformation
config.buildResponseFunc = EmptyResponse
config.logger = log.NewNop()
config = applyOptions(config, options)
natsConnection, closeConnectionFunc, err := connect(config.NatsUrl, config.ClientId, config.Cluster, config.logger)
if err != nil {
return nil, closeConnectionFunc, err
}
handlerFunc := func(endpoint abstraction.Endpoint, loggerFactory log.Factory) http.Handler {
var cfg EndpointConfig
_ = mapstructure.Decode(endpoint.HandlerConfig, &cfg)
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
var messageContext = messageContext{Headers: map[string]interface{}{}}
messageContext.Source = config.Source
messageContext.Topic = config.TopicPrefix + cfg.Topic
messageContext.Logger = loggerFactory(request.Context())
messageBytes, err := ioutil.ReadAll(request.Body)
if err != nil {
badRequest(messageContext.Logger, err, "cannot read body", writer)
return
}
messageBytes, err = config.transformMessageFunc(messageContext, request.Context(), messageBytes)
if err != nil {
internalServerError(messageContext.Logger, err, "cannot transform", writer)
return
}
if err := natsConnection.Publish(messageContext.Topic, messageBytes); err != nil {
internalServerError(messageContext.Logger, err, "cannot publish", writer)
return
}
messageContext.Logger.Debug(
fmt.Sprintf("Forwarding request from %v to %v", request.URL.String(), messageContext.Topic),
zap.String("request_url", request.URL.String()),
zap.String("topic", messageContext.Topic))
responseBytes, err := config.buildResponseFunc(messageContext, request.Context())
if err != nil {
internalServerError(messageContext.Logger, err, "build response error", writer)
return
}
if responseBytes != nil {
_, _ = writer.Write(responseBytes)
}
})
}
return handlerFunc, closeConnectionFunc, nil
} |
/**
* Utility class that trims all whitespace from all String fields
* Stolen from StackOverflow
* Don't @ me
*/
public class SpaceUtil {
private static final Logger LOG = LoggerFactory.getLogger(SpaceUtil.class);
public static Object trimReflective(Object object) {
if (object == null)
return null;
Class<? extends Object> c = object.getClass();
try {
for (PropertyDescriptor propertyDescriptor : Introspector
.getBeanInfo(c, Object.class).getPropertyDescriptors()) {
Method method = propertyDescriptor.getReadMethod();
if (method != null) {
String name = method.getName();
if (method.getReturnType().equals(String.class)) {
String property = (String) method.invoke(object);
if (property != null) {
try {
Method setter = c.getMethod("set" + name.substring(3),
new Class<?>[] { String.class });
if (setter != null)
setter.invoke(object, property.trim());
} catch (NoSuchMethodException ne) {
LOG.warn("Problem trying to set field " + name.substring(3));
}
}
} else {
//handle child objects
Object property = (Object) method.invoke(object);
if (property != null && !(object instanceof java.lang.Class)) {
if (!(property instanceof AnnotatedType)
&& !(property instanceof Annotation)) {
trimReflective(property);
}
}
}
}
}
} catch (Exception e) {
LOG.error("Problem trimming " + object, e);
}
return object;
}
} |
import java.util.Scanner;
class DivideMoney {
long inputAmount() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the amount to divide in INR: Rs.");
long amount = sc.nextLong();
return amount;
}
long handleAmount(long amount, long currency) {
long notes = amount / currency;
amount %= currency;
System.out.println(currency + " \t: \t" + notes);
return amount;
}
void divideMoney(long amount) {
DivideMoney ob = new DivideMoney();
System.out.println("\n\nAmount - Rs." + amount + "\n\n");
if (amount > 2000) {
amount = ob.handleAmount(amount, 2000);
}
if (amount > 500) {
amount = ob.handleAmount(amount, 500);
}
if (amount >= 200) {
amount = ob.handleAmount(amount, 200);
}
if (amount >= 100) {
amount = ob.handleAmount(amount, 100);
}
if (amount >= 50) {
amount = ob.handleAmount(amount, 50);
}
if (amount >= 20) {
amount = ob.handleAmount(amount, 20);
}
if (amount >= 10) {
amount = ob.handleAmount(amount, 10);
}
if (amount >= 5) {
amount = ob.handleAmount(amount, 5);
}
if (amount >= 2) {
amount = ob.handleAmount(amount, 2);
}
if (amount >= 1) {
System.out.println("1 \t: \t" + amount);
}
}
public static void main(String args[]) {
DivideMoney ob = new DivideMoney();
long amount = ob.inputAmount();
ob.divideMoney( amount );
}
}
|
// license:GPL-2.0+
// copyright-holders:<NAME>,<NAME>
/***************************************************************************
z88.c
Functions to emulate the video hardware of the Cambridge Z88
***************************************************************************/
#include "emu.h"
#include "includes/z88.h"
inline void z88_state::plot_pixel(bitmap_ind16 &bitmap, int x, int y, uint16_t color)
{
if (x<Z88_SCREEN_WIDTH)
bitmap.pix16(y, x) = color;
}
// convert absolute offset into correct address to get data from
inline uint8_t* z88_state::convert_address(uint32_t offset)
{
uint8_t *ptr = nullptr;
if (offset < 0x080000) // rom
ptr = m_bios + (offset & 0x7ffff);
else if (offset < 0x100000) // slot0
ptr = m_ram_base + (offset & 0x7ffff);
else if (offset < 0x200000) // slot1
ptr = m_carts[1]->get_cart_base() + (offset & 0xfffff);
else if (offset < 0x300000) // slot2
ptr = m_carts[2]->get_cart_base() + (offset & 0xfffff);
else if (offset < 0x400000) // slot3
ptr = m_carts[3]->get_cart_base() + (offset & 0xfffff);
return ptr;
}
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
// Initialise the palette
PALETTE_INIT_MEMBER(z88_state, z88)
{
m_palette->set_pen_color(0, rgb_t(138, 146, 148));
m_palette->set_pen_color(1, rgb_t(92, 83, 88));
m_palette->set_pen_color(2, rgb_t(122, 126, 129));
}
/* temp - change to gfxelement structure */
void z88_state::vh_render_8x8(bitmap_ind16 &bitmap, int x, int y, uint16_t pen0, uint16_t pen1, uint8_t *gfx)
{
for (int h=0; h<8; h++)
{
uint8_t data = gfx[h];
for (int b=0; b<8; b++)
{
plot_pixel(bitmap, x+b, y+h, (data & 0x80) ? pen1 : pen0);
data = data<<1;
}
}
}
void z88_state::vh_render_6x8(bitmap_ind16 &bitmap, int x, int y, uint16_t pen0, uint16_t pen1, uint8_t *gfx)
{
for (int h=0; h<8; h++)
{
uint8_t data = gfx[h]<<2;
for (int b=0; b<6; b++)
{
plot_pixel(bitmap, x+1+b, y+h, (data & 0x80) ? pen1 : pen0);
data = data<<1;
}
}
}
void z88_state::vh_render_line(bitmap_ind16 &bitmap, int x, int y, uint16_t pen)
{
for (int i=0; i<8; i++)
plot_pixel(bitmap, x + i, y + 7, pen);
}
UPD65031_SCREEN_UPDATE(z88_state::lcd_update)
{
if (sbf == 0)
{
// LCD disabled
bitmap.fill(0);
}
else
{
uint8_t *vram = convert_address(sbf<<11);
for (int y=0; y<(Z88_SCREEN_HEIGHT>>3); y++)
{
int x = 0, c = 0;
while (x < Z88_SCREEN_WIDTH)
{
uint16_t pen0, pen1;
uint8_t *char_gfx;
uint8_t byte0 = vram[(y * 0x100) + c];
uint8_t byte1 = vram[(y * 0x100) + c + 1];
// inverted graphics?
if (byte1 & Z88_SCR_HW_REV)
{
pen0 = (byte1 & Z88_SCR_HW_GRY) ? 2 : 1;
pen1 = 0;
}
else
{
pen0 = 0;
pen1 = (byte1 & Z88_SCR_HW_GRY) ? 2 : 1;
}
if ((byte1 & Z88_SCR_HW_NULL) == Z88_SCR_HW_NULL)
{
// hidden
}
else if (!(byte1 & Z88_SCR_HW_HRS) || (((byte1 & Z88_SCR_HW_CURS) == Z88_SCR_HW_CURS)))
{
// low-res 6x8
uint16_t ch = (byte0 | (byte1<<8)) & 0x1ff;
if ((ch & 0x01c0) == 0x01c0)
{
ch &= 0x3f;
char_gfx = convert_address(lores0<<9);
}
else
{
char_gfx = convert_address(lores1<<12);
}
char_gfx += (ch<<3);
// cursor flash
if (flash && (byte1 & Z88_SCR_HW_CURS) == Z88_SCR_HW_CURS)
vh_render_6x8(bitmap, x,(y<<3), pen1, pen0, char_gfx);
else
vh_render_6x8(bitmap, x,(y<<3), pen0, pen1, char_gfx);
// underline?
if (byte1 & Z88_SCR_HW_UND)
vh_render_line(bitmap, x, (y<<3), pen1);
x += 6;
}
else if ((byte1 & Z88_SCR_HW_HRS) && !(byte1 & Z88_SCR_HW_REV))
{
// high-res 8x8
uint16_t ch = (byte0 | (byte1<<8)) & 0x3ff;
if (ch & 0x0100)
{
ch &= 0xff;
char_gfx = convert_address(hires1<<11);
}
else
{
ch &= 0xff;
char_gfx = convert_address(hires0<<13);
}
char_gfx += (ch<<3);
// flash
if ((byte1 & Z88_SCR_HW_FLS) && flash)
pen0 = pen1 = 0;
vh_render_8x8(bitmap, x,(y<<3), pen0, pen1, char_gfx);
x += 8;
}
// every char takes 2 bytes
c += 2;
}
}
}
}
|
def _check_exceptions(self, tranches:Optional[Union[str, Sequence[str]]]=None, flat_granularity:str="record") -> List[str]:
exceptional_records = []
_two_leads = set(two_leads)
_three_leads = set(three_leads)
_four_leads = set(four_leads)
_six_leads = set(six_leads)
for t in (tranches or self.db_tranches):
for rec in self.all_records[t]:
data = self.load_data(rec)
if np.isnan(data).any():
print(f"record {rec} from tranche {t} has nan values")
elif np.std(data) == 0:
print(f"record {rec} from tranche {t} is flat")
elif (np.std(data, axis=1) == 0).any():
exceptional_leads = set(np.array(self.all_leads)[np.where(np.std(data, axis=1) == 0)[0]].tolist())
cond = any([
_two_leads.issubset(exceptional_leads),
_three_leads.issubset(exceptional_leads),
_four_leads.issubset(exceptional_leads),
_six_leads.issubset(exceptional_leads),
])
if cond or flat_granularity.lower() == "lead":
print(f"leads {exceptional_leads} of record {rec} from tranche {t} is flat")
else:
continue
else:
continue
exceptional_records.append(rec)
return exceptional_records |
<reponame>zhy6599/cc-admin-api<filename>module-system/src/main/java/cc/admin/modules/message/service/ISysMessageTemplateService.java<gh_stars>10-100
package cc.admin.modules.message.service;
import cc.admin.common.sys.base.service.BaseService;
import cc.admin.modules.message.entity.SysMessageTemplate;
import java.util.List;
/**
* @Description: 消息模板
* @Author: jeecg-boot
* @Date: 2019-04-09
* @Version: V1.0
*/
public interface ISysMessageTemplateService extends BaseService<SysMessageTemplate> {
List<SysMessageTemplate> selectByCode(String code);
}
|
//--------------------------------------------------------------------------
// File and Version Information:
// $Id: ComPackBoolsIntoOctet.cc 443 2010-01-14 12:24:42Z stroili $
//
// Description:
// Class ComPackBoolsIntoOctet
// Do not use this for comPackBoolsIntoOctetd class (foo<T>). use ComPackBoolsIntoOctetComPackBoolsIntoOctet.hh
// instead.
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author List:
// <NAME> Originator
//
// Copyright Information:
// Copyright (C) 2001 Lawrence Berkeley National Lab
//
//------------------------------------------------------------------------
#include "BaBar/BaBar.hh"
//-----------------------
// This Class's Header --
//-----------------------
#include "CommonUtils/ComPackBoolsIntoOctet.hh"
//-------------
// C Headers --
//-------------
extern "C" {
#include <assert.h>
}
//---------------
// C++ Headers --
//---------------
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
//----------------
// Constructors --
//----------------
ComPackBoolsIntoOctet::ComPackBoolsIntoOctet()
: _octet( 0 ),
_index( 0 )
{
reset();
}
//--------------
// Destructor --
//--------------
ComPackBoolsIntoOctet::~ComPackBoolsIntoOctet()
{
}
//-------------
// Methods --
//-------------
//-------------
// Operators --
//-------------
bool
ComPackBoolsIntoOctet::operator()( unsigned int index ) const
{
return _bools[ index ];
}
bool
ComPackBoolsIntoOctet::operator[]( unsigned int index ) const
{
assert( index < 8 );
return _bools[ index ];
}
//-------------
// Selectors --
//-------------
uint8
ComPackBoolsIntoOctet::pack( bool v1, bool v2, bool v3, bool v4,
bool v5, bool v6, bool v7, bool v8 ) const
{
uint8 packed = 0;
packed += v1;
packed += v2 << 1;
packed += v3 << 2;
packed += v4 << 3;
packed += v5 << 4;
packed += v6 << 5;
packed += v7 << 6;
packed += v8 << 7;
return packed;
}
//-------------
// Modifiers --
//-------------
void
ComPackBoolsIntoOctet::unpack( uint8 valueToUnpack )
{
for ( unsigned int i=0; i<8; i++ )
{
uint8 mask = 1 << i;
_bools[i] = ( ( valueToUnpack & mask ) == mask ) ? true : false;
}
}
bool
ComPackBoolsIntoOctet::add( bool toAdd )
{
assert( _index < 8 );
_octet += toAdd << _index++;
// If we've finished adding bools let the user know
if ( _index == 8 ) return true;
else return false;
}
// -----------------------------------------------
// -- Static Data & Function Member Definitions --
// -----------------------------------------------
// -------------------------------------------
// -- Protected Function Member Definitions --
// -------------------------------------------
// -----------------------------------------
// -- Private Function Member Definitions --
// -----------------------------------------
// -----------------------------------
// -- Internal Function Definitions --
// -----------------------------------
|
// Retrieve a query and execute it against the database
func (w *worker) doWork(ctx context.Context, db *sql.DB) {
var err error
var str string
work, q, args := w.getWork()
w.lastWork = work
w.lastArgs = args
switch work {
case exec:
w.kvKeys = append(w.kvKeys, fmt.Sprintf("%v", (args[0])))
defer w.tracker.measure(time.Now(), work, &err)
_, err = db.ExecContext(ctx, q, args...)
if err != nil {
w.kvKeys = w.kvKeys[:len(w.kvKeys)-1]
}
case query:
defer w.tracker.measure(time.Now(), work, &err)
err = db.QueryRowContext(ctx, q, args...).Scan(&str)
default:
return
}
} |
// NewEventsClient creates a new EventsClient
func NewEventsClient(client ClientInterface) *EventsClient {
return &EventsClient{
client: client,
}
} |
<filename>src/errors/errors.rs<gh_stars>0
#![allow(unused_qualifications)]
use super::*;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
foreign_links {
IoError(::std::io::Error);
}
links {
PDFError(pdf_error::Error, pdf_error::ErrorKind);
IndexError(index_error::Error, index_error::ErrorKind);
}
errors {
FontError {
description("Font could not be read")
display("Corrupt font file")
}
}
}
|
Simulation of multi and single carrier modes for millimeter-wave transmission in presence of transmitter imperfections
This paper is focused on the evaluation of transmitter imperfections influence on single carrier and multi carrier schemes for high speed data transmission in millimeter wave band. The influence of quantization in data converters, transmitter IQ imbalances together with RF channel on the constellation diagram is evaluated. It is shown that the transceiver impairments and RF channel distort the IQ diagram in similar way for both modes, nevertheless the multi carrier mode is more suitable for the case of multipath propagation and higher user data rates. Bit-error-rate on AWGN channel is used as performance comparison criterion for foregoing imperfections. |
def from_plink_ld_table_to_zarr_chunked(ld_file, dir_store, ld_boundaries, snps):
rows, avg_ncols = len(snps), int((ld_boundaries[1, :] - ld_boundaries[0, :]).mean())
chunks = estimate_row_chunk_size(rows, avg_ncols)
z_arr = zarr.open(dir_store,
mode='w',
shape=rows,
chunks=chunks[:1],
dtype=object,
object_codec=numcodecs.VLenArray(float))
row_chunk_size = z_arr.chunks[0]
ld_chunks = pd.read_csv(ld_file,
delim_whitespace=True,
usecols=['SNP_A', 'SNP_B', 'R'],
engine='c',
chunksize=row_chunk_size*avg_ncols // 2)
z_arr = zarr.open(dir_store,
mode='w',
shape=rows,
chunks=(row_chunk_size,),
dtype=object,
object_codec=numcodecs.VLenArray(float))
snp_dict = dict(zip(snps, np.arange(len(snps))))
sp_mat = None
curr_chunk = 0
for ld_chunk in ld_chunks:
ld_chunk['index_A'] = ld_chunk['SNP_A'].map(snp_dict)
ld_chunk['index_B'] = ld_chunk['SNP_B'].map(snp_dict)
ld_chunk['R'].values[ld_chunk['R'].values == 0.] = np.nan
chunk_mat = csr_matrix((ld_chunk['R'].values,
(ld_chunk['index_A'].values, ld_chunk['index_B'].values)),
shape=(rows, rows))
if sp_mat is None:
sp_mat = chunk_mat + chunk_mat.T
sp_mat.setdiag(1.)
else:
sp_mat = sp_mat + (chunk_mat + chunk_mat.T)
max_index_chunk = ld_chunk['index_A'].max() // row_chunk_size
if max_index_chunk > curr_chunk:
write_csr_to_zarr(sp_mat, z_arr,
start_row=curr_chunk*row_chunk_size,
end_row=max_index_chunk*row_chunk_size,
ld_boundaries=ld_boundaries,
purge_data=True)
curr_chunk = max_index_chunk
write_csr_to_zarr(sp_mat, z_arr,
start_row=curr_chunk * row_chunk_size,
ld_boundaries=ld_boundaries,
purge_data=True)
return z_arr |
DELAND, Fla. -- A 4-year-old Russian blue cat named Kush is being quarantined after apparently going berserk inside a central Florida home, prompting its owners to call 911.
Police say the feline scratched owners Teresa and James Gregory on their arms and legs Saturday, causing the couple to retreat to a bedroom, where they called 911.
"She freaked out. ... She's got us locked in our bedroom," Teresa Gregory said, according to CBS affiliate WKMG. "She's never been like this."
The Daytona Beach News-Journal reports Teresa Gregory told the dispatcher she had mistakenly stepped on the cat's tail earlier in the day and the cat went after her husband. They locked Kush in the bedroom for most of the day. When they finally opened the door, Kush wasn't happy.
"I just called about my crazy cat. ... She tore me and my husband up," Teresa Gregory said on the 911 call, according to WKMG. "We're ripped up."
The woman told the 911 dispatcher that Kush acted aggressively when she took the cat to vet six months ago to get shots, WKMG reports.
"I took her to the vet about six months ago to get everything done and they called me and told me to come get her because she freaked out on them, and they wouldn't (treat) her," the woman said.
The woman is then heard on the 911 call yelling to an officer.
"We're trapped," the woman said.
Kush was placed in quarantine for 10 days at a pet shelter. Officials say the owners can then take the cat back home, relinquish ownership or have it put down.
This is not the first time a crazed cat has prompted a family to call 911. In March, a 22-pound house cat attacked a baby inside a Portland house, forcing the family and a dog to barricade themselves inside a bedroom. |
Beating Heart Mitral Valve Replacement Surgery without Aortic Cross-Clamping via Right Thoracotomy in a Patient with Compromised Left Ventricular Functions.
Abstract Global myocardial ischemia and ischemia-reperfusion injury are potential adverse events related with cardioplegic arrest. Beating heart surgery has avoided such complications and adapted to valve surgery following successful results published on myocardial revascularization. Difficulty in weaning from cardiopulmonary bypass may be lessened by using on-pump beating heart surgery for mitral valve interventions. Here we describe a 64-year-old male patient with severe mitral regurgitation and dilated cardiomyopathy. Beating heart mitral valve replacement surgery was performed without aortic cross-clamping through a right thoracotomy approach. We believe that, particularly in patients with poor left ventricular functions, beating heart mitral valve surgery may be advantageous.
Introduction
Following the popularization of beating heart techniques for myocardial revascularization, its use for heart valve surgery has proven its safety in the second half of 2000s and successful results have been reported. Various protocols have been defined for myocardial protection during arrested heart surgery, but each strategy has its limitations and pitfalls and none has proven ideal. 4,5 Particularly, in patients with compromised ventricular functions, cardioplegic arrest may make weaning from cardiopulmonary bypass (CPB) very challenging. 3 The on-pump beating heart technique without aortic cross-clamping is an acceptable alternative to mitral valve surgery with low operative morbidity and mortality in cases with compromised ventricular functions. 1 Here we report a case of severe mitral regurgitation with poor left ventricular functions. Mitral valve replacement surgery was successfully performed via right thoracotomy under CPB without aortic cross-clamping.
Case Report
A 64-year-old man was admitted to our hospital with the complaints of severe dyspnea, orthopnea, and palpitations. The patient was in the New York Heart Association (NYHA) Class III-IV. He had received an implantable cardioverter-defibrillator two years previously and had been followed up for mitral regurgitation and atrial fibrillation with medical therapy for 4 years. Electrocardiography (ECG) revealed biventricular enlargement and atrial fibrillation. Echocardiography documented third-degree mitral regurgitation and first-to-second-degree tricuspid regurgitation. The left ventricular end-diastolic diameter was 8.0 cm, left ventricular end-systolic diameter was 6.4 cm, left atrial diameter was 54 mm, and the calculated systolic pulmonary artery pressure was 52 mmHg. Left ventricular ejection fraction was 30% with the Simpson method. Coronary angiography was normal. Mitral valve surgery was planned. Written informed consent was obtained from the patient.
Right anterolateral thoracotomy was performed on the fifth intercostal space. Normothermic CPB (36-37 °C) was established following femoral arterial and selective bicaval venous cannulation with a flow rate of 2.2 l/min/m 2 . The mean arterial pressure was maintained between 65 and 80 mmHg. The aorta was not cross-clamped, no cardioplegia was used during the procedure, and the heart was allowed to beat. The patient was kept in the Trendelenburg position throughout the procedure while the aortic root was vented in order to prevent any possible air embolism. The adequacy of the myocardial perfusion was confirmed by ECG monitorization.
Standard left atriotomy incision was made. Both leaflets were normal in appearance, and the annulus was severely dilated. The leaflets were left in place, not resected. The mitral valve was replaced with a 33-mm Carpentier-Edwards Perimount pericardial bioprosthesis. De-airing maneuvers were performed prior to the cessation of CPB. The patient was weaned from CPB without any inotropic support. The total CPB time was 110 minutes. The postoperative course was uneventful. The patient was intubated for 12 hours, kept in the intensive care unit for 48 hours, and discharged on the sixth postoperative day. Postoperative echocardiography revealed a normally functioning bioprosthetic mitral valve.
Discussion
Beating heart mitral valve surgery has the particular advantage of minimizing ischemia-reperfusion injury due to aortic cross-clamping and myocardial ischemia. 1,6 During the global myocardial ischemic period, especially in the previously damaged myocardium with a predisposition, due to increased demand and reduced perfusion, irreversible cellular damage may occur further compromising ventricular functions. 7 Physiologic normothermic blood perfusion of the heart is employed during the procedure, which protects the myocardium. 8 Although the adverse events related to CPB itself cannot be avoided, the avoidance of myocardial damage makes the beating heart technique a logical alternative for patients with poor ventricular functions.
Regarding the blood transfusion requirements, need for inotropic support, and intubation times, controversial results have been documented. Ghosh et al. 9 reported decreased requirements in their series, whereas Karadeniz et al. 10 found no difference on outcomes.
One of the most feared complications of beating heart mitral valve surgery is air embolism. The position of the patient (head down), continuous aortic root venting, strict employment of routine de-airing maneuvers, intraoperative use of transesophageal echocardiography for the detection of bubbles, and most importantly a competent aortic valve decrease the incidence of air embolism. 8, 11 We also did not employ aortic cross-clamping unlike Mojena et al. 7 We believe that aortic cross-clamping causes micro and macro emboli from the aorta as Cicekoglu et al. 8 suggested. Furthermore, it has been documented that beating heart mitral valve surgery has no adverse effects on neurocognitive functions. 8 Beating heart mitral valve surgery has a major drawback: the presence of aortic insufficiency. In case of aortic insufficiency, the blood may flood to the operation field and render exposure very challenging. 11 As a matter of fact, the concept of the beating heart technique has a limited surgical exposure, so there is a limited potential for complex mitral valve procedures. The presence of aortic competence maintains a bloodless field, but still this approach causes a relatively blood-filled field compared to conventional mitral valve surgery. In addition to this, aortic competence also serves as a secure aortic-clamp and prevents air embolism. 8 Our patient had dilated cardiomyopathy with a left ventricular end-diastolic diameter of 8.0 cm. The mitral annulus was severely dilated, causing severe mitral regurgitation. There was prominent tethering due to an enlarged ventricular cavity. The use of cardioplegic arrest may further compromise ventricular functions, tipping the balance in favor of beating heart surgery. Our patient's cardiomyopathy prompted us to protect all his chordae; we, therefore, did not perform leaflet resection and sutured the bioprosthesis to the annulus. We opted against ring annuloplasty because tethering would not lead to a satisfactory reduction in the annular size and would give rise to residual insufficiency. |
def rotate(self, x, M, boxshift):
y = linalg.einsum('ij,kj->ki', (M, x))
y = y + self.pm.BoxSize * boxshift
d = linalg.take(y, 2, axis=1)
xy = linalg.take(y, (0, 1), axis=1)
return dict(xy=xy, d=d) |
With its focus on how we interact with and are affected - both on a personal and societal level - by technology, Black Mirror has always felt like a very contemporary show with its finger on the button. Little did we know when it first began, however, that the series is so keyed into the modern world nearly every episode acts a blueprint for the near-future.
After five years of foreseeing new inventions, political scandals and shock elections, Black Mirror now has a reputation for being the TV series that predicts the future (alongside The Simpsons, of course). Most of its 13 episodes so far have ended up pre-empting some strangely specific event or unforeseen trend. It has got to the point where the show's title seems misplaced. It's not like looking into a dark reflection of the real world anymore. It's like staring into a crystal ball.
We are heading towards an inexorably heady and uncertain future, my friends. At least thanks to Black Mirror, we now know of some of the terrors that await us.
Listed here for your horror are the 10 times (at current count) that Black Mirror has creepily predicted future occurrences. Well, either that or Brooker is selling his ideas to governments, tech developers, cybercriminals et al. The monster. |
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file testIterative.cpp
* @brief Unit tests for iterative methods
* @author Frank Dellaert
**/
#include <tests/smallExample.h>
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/nonlinear/NonlinearEquality.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/linear/iterative.h>
#include <gtsam/geometry/Pose2.h>
#include <CppUnitLite/TestHarness.h>
using namespace std;
using namespace gtsam;
using namespace example;
using symbol_shorthand::X; // to create pose keys
using symbol_shorthand::L; // to create landmark keys
static ConjugateGradientParameters parameters;
// add following below to add printing:
// parameters.verbosity_ = ConjugateGradientParameters::COMPLEXITY;
/* ************************************************************************* */
TEST( Iterative, steepestDescent )
{
// Create factor graph
GaussianFactorGraph fg = createGaussianFactorGraph();
// eliminate and solve
VectorValues expected = fg.optimize();
// Do gradient descent
VectorValues zero = VectorValues::Zero(expected); // TODO, how do we do this normally?
VectorValues actual = steepestDescent(fg, zero, parameters);
CHECK(assert_equal(expected,actual,1e-2));
}
/* ************************************************************************* */
TEST( Iterative, conjugateGradientDescent )
{
// Create factor graph
GaussianFactorGraph fg = createGaussianFactorGraph();
// eliminate and solve
VectorValues expected = fg.optimize();
// get matrices
Matrix A;
Vector b;
Vector x0 = Z_6x1;
boost::tie(A, b) = fg.jacobian();
Vector expectedX = (Vector(6) << -0.1, 0.1, -0.1, -0.1, 0.1, -0.2).finished();
// Do conjugate gradient descent, System version
System Ab(A, b);
Vector actualX = conjugateGradientDescent(Ab, x0, parameters);
CHECK(assert_equal(expectedX,actualX,1e-9));
// Do conjugate gradient descent, Matrix version
Vector actualX2 = conjugateGradientDescent(A, b, x0, parameters);
CHECK(assert_equal(expectedX,actualX2,1e-9));
// Do conjugate gradient descent on factor graph
VectorValues zero = VectorValues::Zero(expected);
VectorValues actual = conjugateGradientDescent(fg, zero, parameters);
CHECK(assert_equal(expected,actual,1e-2));
}
/* ************************************************************************* */
TEST( Iterative, conjugateGradientDescent_hard_constraint )
{
Values config;
Pose2 pose1 = Pose2(0.,0.,0.);
config.insert(X(1), pose1);
config.insert(X(2), Pose2(1.5,0.,0.));
NonlinearFactorGraph graph;
graph += NonlinearEquality<Pose2>(X(1), pose1);
graph += BetweenFactor<Pose2>(X(1),X(2), Pose2(1.,0.,0.), noiseModel::Isotropic::Sigma(3, 1));
boost::shared_ptr<GaussianFactorGraph> fg = graph.linearize(config);
VectorValues zeros = config.zeroVectors();
ConjugateGradientParameters parameters;
parameters.setEpsilon_abs(1e-3);
parameters.setEpsilon_rel(1e-5);
parameters.setMaxIterations(100);
VectorValues actual = conjugateGradientDescent(*fg, zeros, parameters);
VectorValues expected;
expected.insert(X(1), Z_3x1);
expected.insert(X(2), Vector3(-0.5,0.,0.));
CHECK(assert_equal(expected, actual));
}
/* ************************************************************************* */
TEST( Iterative, conjugateGradientDescent_soft_constraint )
{
Values config;
config.insert(X(1), Pose2(0.,0.,0.));
config.insert(X(2), Pose2(1.5,0.,0.));
NonlinearFactorGraph graph;
graph.addPrior(X(1), Pose2(0.,0.,0.), noiseModel::Isotropic::Sigma(3, 1e-10));
graph += BetweenFactor<Pose2>(X(1),X(2), Pose2(1.,0.,0.), noiseModel::Isotropic::Sigma(3, 1));
boost::shared_ptr<GaussianFactorGraph> fg = graph.linearize(config);
VectorValues zeros = config.zeroVectors();
ConjugateGradientParameters parameters;
parameters.setEpsilon_abs(1e-3);
parameters.setEpsilon_rel(1e-5);
parameters.setMaxIterations(100);
VectorValues actual = conjugateGradientDescent(*fg, zeros, parameters);
VectorValues expected;
expected.insert(X(1), Z_3x1);
expected.insert(X(2), Vector3(-0.5,0.,0.));
CHECK(assert_equal(expected, actual));
}
/* ************************************************************************* */
int main() {
TestResult tr;
return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */
|
/* SPDX-License-Identifier: GPL-2.0 */
/*
* Greybus Audio Sound SoC helper APIs
*/
#ifndef __LINUX_GBAUDIO_HELPER_H
#define __LINUX_GBAUDIO_HELPER_H
int gbaudio_dapm_link_component_dai_widgets(struct snd_soc_card *card,
struct snd_soc_dapm_context *dapm);
int gbaudio_dapm_free_controls(struct snd_soc_dapm_context *dapm,
const struct snd_soc_dapm_widget *widget,
int num);
int gbaudio_remove_component_controls(struct snd_soc_component *component,
const struct snd_kcontrol_new *controls,
unsigned int num_controls);
#endif
|
<gh_stars>1-10
//! Class 1 Compact Flash emulation (8-bit ATA (LBA) mode only)
use std::{error, ops::IndexMut};
use crate::bus::{Device, DeviceBus};
bitflags::bitflags! {
struct Status: u8 {
// Last operation was an error
const ERR = 0x01;
// A data error was corrected
const CORR = 0x04;
// Requesting data from host
const DRQ = 0x08;
// Compact flash ready
const DSC = 0x10;
// Write fault
const DWF = 0x20;
// Ready to accept first command
const RDY = 0x40;
// Busy executing command
const BUSY = 0x80;
}
}
bitflags::bitflags! {
struct Error: u8 {
// Address mark not found (generic r/w bit)
const AMNF = 0x01;
// Aborted (unsupported operation)
const ABRT = 0x04;
// ID not found (bad lba)
const IDNF = 0x10;
// Uncorrectable (data error)
const UNC = 0x40;
// Bad block (bad sector)
const BBK = 0x80;
}
}
#[derive(Debug)]
enum CommandState {
None,
IdentifyDevice,
ReadSectors,
WriteSectors,
}
pub trait MemoryMap: IndexMut<usize, Output = u8> {
type Error: error::Error;
fn flush(&mut self) -> Result<(), Self::Error>;
fn len(&self) -> usize;
}
#[derive(Debug)]
struct Card<M> {
mmap: M,
device_info: Vec<u8>,
interrupt: bool,
interrupt_pending: bool,
interrupt_enabled: bool,
interrupt_vector: u8,
is_8_bit: bool,
state: CommandState,
error: u8,
status: u8,
lba: u32,
sector_offset: usize,
}
#[derive(Debug, Default)]
struct SharedRegisters {
feature: u8,
sector_count: u8,
sector_number: u8,
cylinder_low: u8,
cylinder_high: u8,
drive_head: u8,
}
impl<M: MemoryMap> Card<M> {
fn device_info(disk_size: usize) -> Vec<u8> {
let mut info = vec![0; 512];
let cf_card_sig = 0x848A_u16;
for (i, b) in cf_card_sig.to_le_bytes().iter().enumerate() {
info[0 + i] = *b;
}
let sector_count = (disk_size / 512) as u32;
for (i, b) in sector_count.to_le_bytes().iter().enumerate() {
info[14 + i] = *b;
}
let serial_number = b"0-12345-67890-123456";
for (i, b) in serial_number.iter().enumerate() {
info[40 - serial_number.len() + i] = *b; // note: it is right-justified ending at 39
}
info[44] = 0x04; // defined by spec
let firmware_revision = b"POSSUM01";
for (i, b) in firmware_revision.iter().enumerate() {
info[46 + i] = *b;
}
let model_number = b"POSSUM-CF-CARD-EMULATOR-01";
for (i, b) in model_number.iter().enumerate() {
info[54 + i] = *b;
}
let max_multiple_sectors = 0x0001_u16;
for (i, b) in max_multiple_sectors.to_le_bytes().iter().enumerate() {
info[94 + i] = *b;
}
info[99] = 0x02; // LBA supported
info[118] = 0x01; // sectors per interrupt for multiple read/write (though not enabled)
info[119] = 0x00; // multiple sector read/writes *NOT* allowed
for (i, b) in sector_count.to_le_bytes().iter().enumerate() {
info[120 + i] = *b;
}
// I technically don't need to set any capability flags
info
}
fn new(mmap: M) -> Self {
let device_info = Self::device_info(mmap.len());
Self {
mmap,
device_info,
interrupt: false,
interrupt_enabled: false,
interrupt_pending: false,
interrupt_vector: 0,
is_8_bit: false,
state: CommandState::None,
error: 0,
status: Status::RDY.bits() | Status::DSC.bits(), // assume always ready
lba: 0,
sector_offset: 0,
}
}
fn read_data(&mut self) -> u8 {
if (self.status & Status::BUSY.bits()) != 0 {
return 0;
}
match self.state {
CommandState::None => 0,
CommandState::IdentifyDevice => {
let data = self.device_info[self.sector_offset];
self.sector_offset += 1;
if self.sector_offset == 512 {
self.error = 0;
self.status &= !Status::DRQ.bits();
self.state = CommandState::None;
}
data
}
CommandState::ReadSectors => {
let offset = ((self.lba as usize) * 512) + self.sector_offset;
let data = self.mmap[offset];
self.sector_offset += 1;
if self.sector_offset == 512 {
self.status &= !Status::DRQ.bits();
self.state = CommandState::None;
}
data
}
CommandState::WriteSectors => 0,
}
}
fn write_data(&mut self, data: u8) {
if (self.status & Status::BUSY.bits()) != 0 {
return;
}
match self.state {
CommandState::None => {}
CommandState::IdentifyDevice => {}
CommandState::ReadSectors => {}
CommandState::WriteSectors => {
let offset = ((self.lba as usize) * 512) + self.sector_offset;
self.mmap[offset] = data;
self.sector_offset += 1;
if self.sector_offset == 512 {
if self.mmap.flush().is_err() {
self.error |= Error::AMNF.bits() | Error::BBK.bits();
self.status &= !(Status::BUSY.bits() | Status::DRQ.bits());
self.status |= Status::ERR.bits();
}
}
}
}
}
fn write_command(&mut self, registers: &SharedRegisters, data: u8) {
if (self.status & Status::BUSY.bits()) != 0 {
return;
}
// Latch the LBA (and sector count if we want to support it)
#[rustfmt::skip]
{
self.lba = (self.lba & 0xFFFFFF00) | ((registers.sector_number as u32) << 0); // [0:7]
self.lba = (self.lba & 0xFFFF00FF) | ((registers.cylinder_low as u32) << 8); // [8:15]
self.lba = (self.lba & 0xFF00FFFF) | ((registers.cylinder_high as u32) << 16); // [16:23]
self.lba = (self.lba & 0x00FFFFFF) | (((registers.drive_head & 0x0F) as u32) << 24); // [24:27]
}
// Clear errors :-)
self.error = 0;
self.status &= !Status::ERR.bits();
match data {
// Execute drive diagnostic
0x90 => {
// 1 means no error detected
self.error = 0x01;
}
// Erase sectors
0xC0 => {
// check for LBA mode
if (registers.drive_head & 0x40) == 0 {
self.status |= Status::ERR.bits();
self.error |= Error::AMNF.bits() | Error::IDNF.bits() | Error::ABRT.bits();
return;
}
let offset = (self.lba as usize) * 512;
for i in 0..512 {
self.mmap[offset + i] = 0xFF;
}
if self.mmap.flush().is_err() {
self.error |= Error::AMNF.bits() | Error::BBK.bits();
self.status |= Status::ERR.bits();
}
}
// Identify device
0xEC => {
self.interrupt = true;
self.sector_offset = 0;
self.status |= Status::DRQ.bits();
self.state = CommandState::IdentifyDevice;
}
// Nop
0x00 => {
// Always aborts
self.status |= Status::ERR.bits();
self.error |= Error::AMNF.bits() | Error::ABRT.bits();
}
// Read sectors
0x20 | 0x21 => {
// check for LBA mode
if (registers.drive_head & 0x40) == 0 {
self.status |= Status::ERR.bits();
self.error |= Error::AMNF.bits() | Error::IDNF.bits() | Error::ABRT.bits();
return;
}
self.interrupt = true;
self.sector_offset = 0;
let offset = ((self.lba as usize) * 512) + self.sector_offset;
if self.mmap.len() < offset {
self.error |= Error::AMNF.bits() | Error::IDNF.bits();
self.status |= Status::ERR.bits();
return;
}
self.status |= Status::DRQ.bits();
self.state = CommandState::ReadSectors;
}
// Read verify sectors
0x40 | 0x41 => {
// check for LBA mode
if (registers.drive_head & 0x40) == 0 {
self.status |= Status::ERR.bits();
self.error |= Error::AMNF.bits() | Error::IDNF.bits() | Error::ABRT.bits();
return;
}
// Does nothing. We assume the disk is fine :-)
self.interrupt = true;
}
// Request sense
0x03 => todo!(),
// Set features
0xEF => {
match registers.feature {
// Enable 8-bit
0x01 => self.is_8_bit = true,
// Disable 8-bit
0x02 => self.is_8_bit = false,
_ => {
self.status |= Status::ERR.bits();
self.error |= Error::AMNF.bits() | Error::ABRT.bits();
}
}
}
// Write sectors
0x30 | 0x31 | 0x38 | 0x3C => {
// check for LBA mode
if (registers.drive_head & 0x40) == 0 {
self.status |= Status::ERR.bits();
self.error |= Error::AMNF.bits() | Error::IDNF.bits() | Error::ABRT.bits();
return;
}
self.sector_offset = 0;
self.status |= Status::DRQ.bits();
self.state = CommandState::WriteSectors;
}
// Invalid command
_ => {
self.status |= Status::ERR.bits();
self.error |= Error::AMNF.bits() | Error::ABRT.bits()
}
}
}
}
#[derive(Debug)]
pub struct CardBus<M> {
card0: Card<M>,
card1: Option<Card<M>>,
registers: SharedRegisters,
}
impl<M: MemoryMap> CardBus<M> {
#[inline]
pub fn single(mmap: M) -> Self {
Self::new(mmap, None)
}
#[inline]
pub fn dual(mmap0: M, mmap1: M) -> Self {
Self::new(mmap0, Some(mmap1))
}
#[inline]
fn new(mmap0: M, mmap1: Option<M>) -> Self {
Self {
card0: Card::new(mmap0),
card1: mmap1.map(|mmap| Card::new(mmap)),
registers: SharedRegisters::default(),
}
}
}
impl<M: MemoryMap> Device for CardBus<M> {
fn tick(&mut self, _: &mut dyn DeviceBus) {}
fn read(&mut self, port: u16) -> u8 {
match port & 0x07 {
// Data port
0 => {
if (self.registers.drive_head & 0x10) == 0 {
self.card0.read_data()
} else {
match self.card1.as_mut() {
Some(card1) => card1.read_data(),
_ => 0,
}
}
}
// Error Code
1 => {
if (self.registers.drive_head & 0x10) == 0 {
self.card0.error
} else {
match self.card1.as_ref() {
Some(card1) => card1.error,
_ => 0,
}
}
}
// Sector Count
2 => self.registers.sector_count,
// a.k.a. Logical Block Address (LBA) [0:7]
3 => self.registers.sector_number,
// a.k.a LBA [8:15]
4 => self.registers.cylinder_low,
// a.k.a LBA [16:23]
5 => self.registers.cylinder_high,
// a.k.a. LBA [24:27]
6 => self.registers.drive_head,
// Status
7 => {
// Reading the status clears the interrupts apparently
if (self.registers.drive_head & 0x10) == 0 {
self.card0.interrupt = false;
self.card0.status
} else {
match self.card1.as_mut() {
Some(card1) => {
card1.interrupt = false;
card1.status
}
_ => 0,
}
}
}
_ => unreachable!(),
}
}
fn write(&mut self, port: u16, data: u8) {
match port & 0x07 {
// Data port
0 => {
if (self.registers.drive_head & 0x10) == 0 {
self.card0.write_data(data)
} else {
match self.card1.as_mut() {
Some(card1) => card1.write_data(data),
_ => {}
}
}
}
// Feature
1 => self.registers.feature = data,
// Sector Count
2 => self.registers.sector_count = data,
// a.k.a. Logical Block Address (LBA) [0:7]
3 => self.registers.sector_number = data,
// a.k.a LBA [8:15]
4 => self.registers.cylinder_low = data,
// a.k.a LBA [16:23]
5 => self.registers.cylinder_high = data,
// a.k.a. LBA [24:27]
6 => self.registers.drive_head = data,
// Command
7 => {
let Self {
card0,
card1,
registers,
..
} = self;
if (registers.drive_head & 0x10) == 0 {
card0.write_command(®isters, data)
} else {
match card1.as_mut() {
Some(card1) => card1.write_command(®isters, data),
_ => {}
}
}
}
_ => unreachable!(),
}
}
fn interrupting(&self) -> bool {
if self.card0.interrupt_enabled && self.card0.interrupt {
return true;
}
match self.card1.as_ref() {
Some(card1) => card1.interrupt_enabled && card1.interrupt,
_ => false,
}
}
fn interrupt_pending(&self) -> bool {
if self.card0.interrupt_enabled {
return self.card0.interrupt_pending;
}
match self.card1.as_ref() {
Some(card1) if card1.interrupt_enabled => card1.interrupt_pending,
_ => false,
}
}
fn ack_interrupt(&mut self) -> u8 {
// AFAICT, interrupts are low-level and won't populate the data bus.
if self.card0.interrupt_enabled && self.card0.interrupt {
self.card0.interrupt = false;
self.card0.interrupt_pending = true;
return self.card0.interrupt_vector;
}
match self.card1.as_mut() {
Some(card1) if card1.interrupt_enabled && card1.interrupt => {
card1.interrupt = false;
card1.interrupt_pending = true;
card1.interrupt_vector
}
_ => 0,
}
}
fn ret_interrupt(&mut self) {
if self.card0.interrupt_enabled && self.card0.interrupt_pending {
self.card0.interrupt_pending = false;
}
match self.card1.as_mut() {
Some(card1) if card1.interrupt_enabled && card1.interrupt_pending => {
card1.interrupt_pending = false;
}
_ => {}
}
}
}
|
<reponame>Dr-Fabulous/libmm
#include "mm/unit.h"
#include "mm/co.h"
struct counter_state {
struct mm_co co;
int i;
};
MM_COROUTINE( counter, struct counter_state *this ) {
MM_CO_BEGIN( &this->co );
for( this->i = 0; this->i < 5; ++this->i ) {
MM_CO_YIELD( &this->co );
}
MM_CO_END( &this->co );
}
MM_UNIT_CASE( counter_case, NULL, NULL ) {
struct counter_state st = { 0 };
int i = 0;
while( MM_CO_RESUME( counter( &st ) ) ) {
MM_UNIT_ASSERT_EQ( i++, st.i );
}
return MM_UNIT_DONE;
}
MM_UNIT_SUITE( co_suite ) {
MM_UNIT_RUN( counter_case );
return MM_UNIT_DONE;
}
|
#ifndef _agg_upp_bind_AggCtrl_h_
#define _agg_upp_bind_AggCtrl_h_
#include "agg_upp_bind.h"
class AggCtrl : public ParentCtrl {
ImageBuffer uibuf;
public:
typedef AggCtrl CLASSNAME;
AggCtrl();
~AggCtrl() {;}
};
#endif
|
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
/** \file
* This is a convenience header for Catch2's Matcher support. It includes
* **all** of Catch2 headers related to matchers.
*
* Generally the Catch2 users should use specific includes they need,
* but this header can be used instead for ease-of-experimentation, or
* just plain convenience, at the cost of increased compilation times.
*
* When a new header is added to either the `matchers` folder, or to
* the corresponding internal subfolder, it should be added here.
*/
#ifndef CATCH_MATCHERS_ALL_HPP_INCLUDED
#define CATCH_MATCHERS_ALL_HPP_INCLUDED
#include <catch2/matchers/catch_matchers.hpp>
#include <catch2/matchers/catch_matchers_container_properties.hpp>
#include <catch2/matchers/catch_matchers_contains.hpp>
#include <catch2/matchers/catch_matchers_exception.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include <catch2/matchers/catch_matchers_predicate.hpp>
#include <catch2/matchers/catch_matchers_quantifiers.hpp>
#include <catch2/matchers/catch_matchers_range_equals.hpp>
#include <catch2/matchers/catch_matchers_string.hpp>
#include <catch2/matchers/catch_matchers_templated.hpp>
#include <catch2/matchers/catch_matchers_vector.hpp>
#include <catch2/matchers/internal/catch_matchers_impl.hpp>
#endif // CATCH_MATCHERS_ALL_HPP_INCLUDED
|
{-# htermination lookup :: (Eq a, Eq k) => (a, k) -> [((a, k),b)] -> Maybe b #-}
|
But on one issue -- guns -- President Barack Obama lets the public mask slip, revealing the ire boiling within.
Before the cameras, moved by the massacres of innocents that have punctuated his presidency, Obama has wept, his voice has cracked, he's visibly shaken with frustration, he's lashed out at lawmakers he sees as cowards and even led a congregation in "Amazing Grace."
On Tuesday, as he faced a room filled with parents and relatives of victims of gun violence, he stopped speaking, grew silent and wiped away the tears that began to fall when he recalled the first graders killed in a Connecticut elementary school three years ago.
"Every time I think about those kids, it gets me mad," Obama said in the East Room of the White House.
At times, the President has questioned the nation he leads, asking why no other advanced country seems so blighted with regular killing sprees and wondering aloud why Americans will not choose to stop the bloodshed.
Evolving through a cycle of sadness, poleaxing grief, frustration and outright fury, Obama has even offered hints of self-recrimination at his own earlier failure to touch the perfidious politics of gun control himself.
JUST WATCHED How Obama responds to shooting attacks Replay More Videos ... MUST WATCH How Obama responds to shooting attacks 02:37
But so far, all the emoting, anger and frustration have added up to little. Despite an expansive flexing of his executive powers, Obama, hampered by a Republican Congress and wary Democrats, has failed to significantly tighten gun control laws.
Now, following a new clutch of killings in places like Oregon, South Carolina and California last year, Obama's public evolution on gun control may be complete. Instead of talking, he's acting. At the White House, he unveiled a series of executive actions on guns, including expanding mandatory background checks for some private sales.
"We are not inherently more prone to violence. But we are the only advanced country on Earth that sees this kind of mass violence erupt with this kind of frequency. It doesn't happen in other advanced countries. It's not even close," Obama said. "Somehow we become numb to it and we start to feel that this is normal. And instead of thinking about how to solve the problem, this has become one of our most polarized, partisan debates, despite the fact that there's a general consensus in America about what needs to be done."
He added, "We do have to feel a sense of urgency about it. In Dr. King's words, we need to feel the fierce urgency of now -- because people are dying."
He will also press for public support on the issue at a live town hall meeting hosted by CNN on Thursday night -- making gun violence a priority of his final year in office, days before his valedictory State of the Union address.
Obama insisted Tuesday that he merely wants to enact a few common-sense gun safety measures. But the gun lobby is mobilizing and Republicans, led by 2016 front-runner Donald Trump, insist Obama is out to make it impossible for people to buy guns.
From the campaign trail to Tucson to Aurora
Obama's often demoralizing and politically radioactive experience with the politics of gun control started when he first set eyes on the White House and have confounded him ever since.
He got off on the wrong foot with Second Amendment advocates with an offhand remark during his 2008 campaign, when he said people in Midwest communities hit hard by economic blight "cling to guns or religion."
That seemed to many critics as disdainful of lawful firearms owners themselves, a slip his foes have used again and again to warn the president is coming to get their guns.
Obama also appeared to underestimate the potency of the gun lobby and National Rifle Association back then as well.
"What we have to do is get beyond the politics of this issue," Obama he said at a 2008 Democratic debate in Philadelphia.
But when he took office, gun control seemed far from his mind. With a financial crisis raging, and other priorities like health care reform demanding political capital, Obama was absent on the issue while Democrats controlled both chambers of Congress.
And to be fair, there were few Democrats -- especially those in red states -- who would have welcomed tough votes on gun control.
But the President was forced to confront the consequences of gun violence before the eyes of the nation after shooting sprees at Fort Hood, Texas, in November 2009, and in a Tucson, Arizona, supermarket parking lot that left Congresswoman Gabrielle Giffords with brain damage and six people dead in January 2011.
Photos: What's the answer to gun violence? Photos: What's the answer to gun violence? Hide Caption 1 of 11 Photos: What's the answer to gun violence? Hide Caption 2 of 11 Photos: What's the answer to gun violence? Hide Caption 3 of 11 Photos: What's the answer to gun violence? Hide Caption 4 of 11 Photos: What's the answer to gun violence? Hide Caption 5 of 11 Photos: What's the answer to gun violence? Hide Caption 6 of 11 Photos: What's the answer to gun violence? Hide Caption 7 of 11 Photos: What's the answer to gun violence? Hide Caption 8 of 11 Photos: What's the answer to gun violence? Hide Caption 9 of 11 Photos: What's the answer to gun violence? Hide Caption 10 of 11 Photos: What's the answer to gun violence? Hide Caption 11 of 11
At a memorial service, a saddened Obama comforted relatives and cracked hearts when he hoped the youngest victim, nine-year-old Christina Taylor Green, was jumping "in rain puddles in Heaven."
But he used the tragedy, not to make the kind of outspoken call for gun control that would become familiar in later years but to call on Americans to cleanse their poisoned politics.
"Rather than pointing fingers or assigning blame, let's use this occasion to expand our moral imaginations, to listen to each other more carefully," he said.
In the months to come, Obama would be called upon to react to more shootings, including one at a Sikh temple in Wisconsin in which six people died and a massacre at a movie theater in Aurora, Colorado, in which 12 were killed.
But the emotional strain was clearly beginning to take a toll as he wondered after Aurora how he would feel if his daughters had been caught at the scene.
Sandy Hook
For Obama, the dam broke on what he later named as the worst day of his presidency in December 2012.
Hours after 20 children and six adults were gunned down at Sandy Hook Elementary School in Newtown, Connecticut, Obama wiped a tear from his left eye and fell silent before reporters to compose himself as he mourned the "beautiful little kids."
A few days later, at a heart-searing memorial service, loud sobs rang out in a school auditorium as Obama slowly read the roll of those killed, while crossing a threshold -- no longer reluctant to start talking politics as he mourned the dead.
"We, as a nation, are left with some hard questions .... can we truly say, as a nation, that we're meeting our obligations?" Obama said, offering to put whatever power his office held to prevent more tragedies.
And Obama kept to his word -- for several months.
But his effort to convince Congress to tighten background checks and to introduce an assault weapons ban foundered on the power of the NRA and the entrenched politics of gun control. The Senate failed to get the 60 votes needed to move forward on legislation that would expand background checks on firearms sales.
The process did not only leave Obama looking like he'd let the relatives of the Newtown dead down, it appeared to further sour him on Washington itself, a town he no longer saw as moveable by the forces of hope and change.
JUST WATCHED Obama angry about gun bill failure Replay More Videos ... MUST WATCH Obama angry about gun bill failure 01:43
"This was a pretty shameful day for Washington," Obama said, in a stunningly frank appearance in the White House Rose Garden after the lost Senate vote in April 2013.
"It came down to politics -- the worry that that vocal minority of gun owners would come after them in future elections," said Obama. "They worried that the gun lobby would spend a lot of money and paint them as anti-Second Amendment."
Obama did enact 23 executive actions that the White House says have been successful, though officials admit that true reform is only possible through Congress.
But gun control once again slipped down the president's agenda -- after the White House apparently concluded the politics of the issue were impossible.
It took another year shattered by tragedies in 2015 from a bloodbath in a church in Charleston, South Carolina, to a massacre at a community college in Roseburg, Oregon, to draw Obama back into the fray.
In one of the seminal moments of his presidency, Obama broke into "Amazing Grace" at a memorial service for a preacher and eight others killed in South Carolina by a gunman who wanted to incite a race war.
After another weary appearance at the White House podium after the Oregon shooting, Obama made clear his heart was sick at the whole futile business of going before the cameras to bemoan another massacre.
"Somehow this has become routine," Obama told reporters.
He made no apologies for politicizing the issue and warned "this is not something I can do myself" before going the extra step of worrying about his nation's soul.
JUST WATCHED When leaders say 'it's not the time' to talk gun control Replay More Videos ... MUST WATCH When leaders say 'it's not the time' to talk gun control 01:31
"I would ask the American people to think about how they can get our government to change these laws," he said.
But the killings went on. After a radicalized Muslim couple staged a mass killing in San Bernardino, California, Obama faced a buzzsaw of Republican opposition when he spoke of the need to stop potential terrorists getting hold of guns. GOP presidential candidates said he should be focused on the threat from radical Islam not making it more difficult for law abiding Americans to defend themselves.
Now, Obama is back to try again, but even the President admits the measures are limited in scope.
"We maybe can't save everybody, but we could save some. Just as we don't prevent all traffic accidents, but we ... try to reduce traffic accidents," Obama said Tuesday. "As Ronald Reagan once said, if mandatory background checks could save more lives, it would be well worth making it the law of the land."
And with prospects bleak for any significant action in Congress, Obama's latest effort may be more about making peace with the relatives of the dead and his own conscience as the result of a realistic assessment that change is possible now. |
def ensure_type(self, *, cset: ABCConcreteSet):
if not isinstance(cset, UnitSet):
raise UnitException("Must be UnitSet") |
If you’ve been avoiding student politics for this last year (and we don’t blame you) but still want to vote, look no further than this handy compendium.
Start here:
http://www.martlet.ca/news/elections-faq/
Slate information:
Involve UVic
Refresh UVic
The Independents (and other independent candidates)
Executive video interviews:
Director-at-large questionnaire responses:
http://www.martlet.ca/news/director-at-large-candidates-2015/
Official Facebook pages:
Involve UVic
Refresh UVic
The Independents
Referendum questions:
Food Bank
Martlet articles:
Food bank shortage raises questions about funding (Oct. 2013)
UVSS Food Bank and Free Store relocates in SUB (Oct. 2014)
Why do you think the food bank is needed? (Streeters, Oct. 2013)
Fee re-allocation question: Both slates support re-allocating money from the UVSS Election Fund to the food bank, as the funding level was set when the society still used paper ballots. After transitioning to online voting, money is now left over.
Information from proponents:
Referendum event page
UVSS page
Food bank info video (YouTube)
Fossil fuel divestment
Martlet articles:
Detailed FAQ
UVSS endorsement in 2013
Getting it onto the agenda (Oct. 2014)
UVic climate forum video link
Information from proponents:
Proponent FAQ
Facebook event
Community Garden:
Martlet articles:
Campus Community Garden profile (Profile, May 2014)
UVSS meeting that covers the increase for community garden (Jan. 2015)
Information from proponents:
Official website
Campus Community Garden Facebook page
Environmental Roundtable Facebook event
Campaign video (Vimeo)
Proponent FAQ
Students of Colour Collective referendum:
UVSS audited financial statements (go to page 13). According to SOCC, they receive about $16,000 per year in advocacy council funding, but that just pays for the co-ordinator, who organizes work study students, does clerical work, and fields questions. With additional funding, SOCC hopes to hold more movie screenings, panel events, and re-open their food bank for self-identified people of colour, which closed due to lack of funding. Currently, other advocacy groups get 95 cents from each full-time student per semester. SOCC is looking for 70 cents per full-time student.
Relevant links:
UVSS Elections Office (for official rules and regulations) |
Two Olentangy Orange High School students are facing charges for making explosive devices, according to the Columbus Division of Fire.
The two students were charged with unlawful possession of dangerous ordinance, a fifth-degree felony, after a recent investigation of a discarded improvised explosive device.
Columbus Fire says the investigation is ongoing and other students involved could possibly be facing charges.
On June 15, Delaware County Sheriff’s deputies, Columbus Division of Police, and the Columbus Division of Fire Bomb Squad responded to the area of Arrow Feather Lane after someone found an improvised explosive device attached to a fire extinguisher. Columbus Fire Bomb technicians rendered the improvised explosive safe.
Investigators identified a local high school student as a suspect and executed a search warrant at his home. The search of the residence found approximately 15 other improvised explosive devices, approximately five pounds of explosive powders and many other components of explosives and improvised explosive devices, according to Columbus Fire.
According to lead investigator Mike DeFrancisco, “The variety and quantity of different explosives that were in this apartment would have definitely destroyed the unit if not the entire third floor.”
Authorities say the teens had no intention of attacking a school or students. They claim the two students were fascinated with fireworks. |
import random
def solve(n, rating):
temp = list(rating)
rating.sort()
new = [1 for i in range(n)]
ans = []
on = rating[0]
for i in range(n):
temp2 = rating[i]
if temp2 != on:
on = temp2
new[rating[i - 1] - 1] += (len(rating) - i)
for i in range(len(temp)):
ans.append(new[temp[i] - 1])
return ans
def solve2(n, rating):
new = [1 for i in range(len(rating))]
for i in range(len(rating)):
for x in range(len(rating)):
if rating[x] > rating[i]:
new[i] += 1
return new
a = int(raw_input())
b = map(int, raw_input().split(" "))
print " ".join(map(str, solve2(a, b)))
|
/**
* The main class to run the preview service.
*/
public class PreviewServiceMain extends AbstractServiceMain<EnvironmentOptions> {
// Following constants are same as defined in AbstractKubeTwillPreparer
private static final String KUBE_CPU_MULTIPLIER = "master.environment.k8s.container.cpu.multiplier";
private static final String KUBE_MEMORY_MULTIPLIER = "master.environment.k8s.container.memory.multiplier";
/**
* Main entry point
*/
public static void main(String[] args) throws Exception {
main(PreviewServiceMain.class, args);
}
@Override
protected CConfiguration updateCConf(CConfiguration cConf) {
Map<String, String> keyMap = ImmutableMap.of(
Constants.Preview.CONTAINER_CPU_MULTIPLIER, KUBE_CPU_MULTIPLIER,
Constants.Preview.CONTAINER_MEMORY_MULTIPLIER, KUBE_MEMORY_MULTIPLIER,
Constants.Preview.CONTAINER_HEAP_RESERVED_RATIO, Configs.Keys.HEAP_RESERVED_MIN_RATIO
);
for (Map.Entry<String, String> entry : keyMap.entrySet()) {
String value = cConf.get(entry.getKey());
if (value != null) {
cConf.set(entry.getValue(), value);
}
}
return cConf;
}
@Override
protected List<Module> getServiceModules(MasterEnvironment masterEnv,
EnvironmentOptions options, CConfiguration cConf) {
List<Module> modules = new ArrayList<>(Arrays.asList(
new DataSetServiceModules().getStandaloneModules(),
new DataSetsModules().getStandaloneModules(),
new AppFabricServiceRuntimeModule(cConf).getStandaloneModules(),
new ProgramRunnerRuntimeModule().getStandaloneModules(),
new MetricsStoreModule(),
new MessagingClientModule(),
new AuditModule(),
new SecureStoreClientModule(),
new MetadataReaderWriterModules().getStandaloneModules(),
getDataFabricModule(),
new DFSLocationModule(),
new MetadataServiceModule(),
new AuthorizationModule(),
new AuthorizationEnforcementModule().getDistributedModules(),
new AbstractModule() {
@Override
protected void configure() {
bind(TwillRunnerService.class).toProvider(
new SupplierProviderBridge<>(masterEnv.getTwillRunnerSupplier())).in(Scopes.SINGLETON);
bind(TwillRunner.class).to(TwillRunnerService.class);
bind(ExploreClient.class).to(UnsupportedExploreClient.class);
}
}
));
if (cConf.getInt(Constants.Preview.CONTAINER_COUNT) > 0) {
modules.add(new PreviewManagerModule(true));
} else {
modules.add(new PreviewManagerModule(false));
modules.add(new PreviewRunnerManagerModule().getStandaloneModules());
}
return modules;
}
@Override
protected void addServices(Injector injector, List<? super Service> services,
List<? super AutoCloseable> closeableResources,
MasterEnvironment masterEnv, MasterEnvironmentContext masterEnvContext,
EnvironmentOptions options) {
CConfiguration cConf = injector.getInstance(CConfiguration.class);
// When internal auth is enabled, start TokenManager first, so it is ready
// for generating and validating tokens needed for communicating with other
// system services.
if (SecurityUtil.isInternalAuthEnabled(cConf)) {
services.add(injector.getInstance(TokenManager.class));
}
services.add(new TwillRunnerServiceWrapper(injector.getInstance(TwillRunnerService.class)));
services.add(injector.getInstance(PreviewHttpServer.class));
Binding<ZKClientService> zkBinding = injector.getExistingBinding(Key.get(ZKClientService.class));
if (zkBinding != null) {
services.add(zkBinding.getProvider().get());
}
if (cConf.getInt(Constants.Preview.CONTAINER_COUNT) <= 0) {
services.add(injector.getInstance(PreviewRunnerManager.class));
}
}
@Nullable
@Override
protected LoggingContext getLoggingContext(EnvironmentOptions options) {
return new ServiceLoggingContext(NamespaceId.SYSTEM.getNamespace(),
Constants.Logging.COMPONENT_NAME,
Constants.Service.PREVIEW_HTTP);
}
} |
def map2cosmo(ds, filename=None):
cosmo = dict(samples=ds.samples)
cosmo.update(_attributes_dict2cosmo(ds))
cosmo_fixed = _mat_make_saveable(cosmo)
_check_cosmo_dataset(cosmo_fixed)
if filename is not None:
savemat(filename, cosmo_fixed)
return cosmo_fixed |
Introduction
Originally appeared in Socialism Today No. 40, July 1999
Something unremarkable happened on June 28, 1969 in New York’s Greenwich Village, an event which had occurred a thousand times before across the U.S. over the decades. The police raided a gay bar.
At first, everything unfolded according to a time-honored ritual. Seven plain-clothes detectives and a uniformed officer entered and announced their presence. The bar staff stopped serving the watered-down, overpriced drinks, while their Mafia bosses swiftly removed the cigar boxes which functioned as tills. The officers demanded identification papers from the customers and then escorted them outside, throwing some into a waiting paddy-wagon and pushing others off the sidewalk.
But at a certain point, the “usual suspects” departed from the script and decided to fight back. A debate still rages over which incident sparked the riot. Was it a ‘butch’ lesbian dressed in man’s clothes who resisted arrest, or a male drag queen who stopped in the doorway between the officers and posed defiantly, rallying the crowd?
Riot veteran and gay rights activist Craig Rodwell says: “A number of incidents were happening simultaneously. There was no one thing that happened or one person, there was just… a flash of group, of mass anger.”
The crowd of ejected customers started to throw coins at the officers, in mockery of the notorious system of payoffs – earlier dubbed “gayola” – in which police chiefs leeched huge sums from establishments used by gay people and used “public morals” raids to regulate their racket. Soon, coins were followed by bottles, rocks, and other items. Cheers rang out as the prisoners in the van were liberated. Detective Inspector Pine later recalled, “I had been in combat situations, but there was never any time that I felt more scared than then.”
Pine ordered his subordinates to retreat into the empty bar, which they proceeded to trash as well as savagely beating a heterosexual folk singer who had the misfortune to pass the doorway at that moment. At the end of the evening, a teenager had lost two fingers from having his hand slammed in a car door. Others received hospital treatment following assaults with police billy clubs.
People in the crowd started shouting “Gay Power!” And as word spread through Greenwich Village and across the city, hundreds of gay men and lesbians, black, white, Hispanic, and predominantly working class, converged on the Christopher Street area around the Stonewall Inn to join the fray. The police were now reinforced by the Tactical Patrol Force (TPF), a crack riot-control squad that had been specially trained to disperse people protesting against the Vietnam War.
Historian Martin Duberman describes the scene as the two dozen “massively proportioned” TPF riot police advanced down Christopher Street, arms linked in Roman Legion-style wedge formation: “In their path, the rioters slowly retreated, but – contrary to police expectations – did not break and run … hundreds … scattered to avoid the billy clubs but then raced around the block, doubled back behind the troopers, and pelted them with debris. When the cops realized that a considerable crowd had simply re-formed to their rear, they flailed out angrily at anyone who came within striking distance.
“But the protestors would not be cowed. The pattern repeated itself several times: The TPF would disperse the jeering mob only to have it re-form behind them, yelling taunts, tossing bottles and bricks, setting fires in trash cans. When the police whirled around to reverse direction at one point, they found themselves face-to-face with their worst nightmare: a chorus line of mocking queens, their arms clasped around each other, kicking their heels in the air Rockettes-style and singing at the tops of their sardonic voices:
‘We are the Stonewall girls
We wear our hair in curls
We wear no underwear
We show our pubic hair…
We wear our dungarees
Above our nelly knees!’
“It was a deliciously witty, contemptuous counterpoint to the TPF’s brute force.” (Stonewall, Duberman, 1993) The following evening, the demonstrators returned, their numbers now swelled to thousands. Leaflets were handed out, titled “Get the Mafia and cops out of gay bars!” Altogether, the protests and disturbances continued with varying intensity for five days.
In the wake of the riots, intense discussions took place in the city’s gay community. During the first week of July, a small group of lesbians and gay men started talking about establishing a new organization called the Gay Liberation Front. The name was consciously chosen for its association with the anti-imperialist struggles in Vietnam and Algeria. Sections of the GLF would go on to organize solidarity for arrested Black Panthers, collect money for striking workers, and link the battle for gay rights to the banner of socialism.
During the next year or so, lesbians and gay men built a Gay Liberation Front (GLF) or comparable body in Canada, France, Britain, Germany, Belgium, Holland, Australia, and New Zealand.
The word “Stonewall” has entered the vocabulary of lesbians, gay men, bisexuals, and transgendered (LGBT) people everywhere as a potent emblem of the gay community making a stand against oppression and demanding full equality in every area of life.
The GLF is no more, but the idea of Gay Power is as strong as ever. Meanwhile, in many countries and cities the concept of “gay pride” literally marches on each year in the form of an annual Gay Pride march.
The present generation of young LGBT people and many of today’s gay rights activists were born or grew up after 1969. And over the intervening decades, politics in the U.S. have passed through a very different period. While there have been huge advances in the struggle for LGBT rights, there is still a long way to go to achieve full liberation as the growing attacks by the religious right makes very clear. |
// Get returns an Quote quote that matches the parameters specified.
func Get(symbol string) (*finance.Quote, error) {
i := List([]string{symbol})
if !i.Next() {
return nil, i.Err()
}
return i.Quote(), nil
} |
import sys
N = int(input())
As = list(map(int, input().split()))
As.sort()
for i in range(N):
for j in range(i + 1, N):
if As[i] == As[j]:
print('NO')
sys.exit(0)
if As[j] > As[i]:
break
print('YES') |
/**
* Rechunks the strings based on a regex pattern and works on infinite stream.
*
* <pre>
* split(["boo:an", "d:foo"], ":") --> ["boo", "and", "foo"]
* split(["boo:an", "d:foo"], "o") --> ["b", "", ":and:f", "", ""]
* </pre>
*
* See {@link Pattern}
*
* @param src
* @param regex
* @return the Observable streaming the split values
*/
public static Observable<String> split(final Observable<String> src, String regex) {
final Pattern pattern = Pattern.compile(regex);
return src.lift(new Operator<String, String>() {
@Override
public Subscriber<? super String> call(final Subscriber<? super String> o) {
return new Subscriber<String>(o) {
private String leftOver = null;
@Override
public void onCompleted() {
output(leftOver);
if (!o.isUnsubscribed())
o.onCompleted();
}
@Override
public void onError(Throwable e) {
output(leftOver);
if (!o.isUnsubscribed())
o.onError(e);
}
@Override
public void onNext(String segment) {
String[] parts = pattern.split(segment, -1);
if (leftOver != null)
parts[0] = leftOver + parts[0];
for (int i = 0; i < parts.length - 1; i++) {
String part = parts[i];
output(part);
}
leftOver = parts[parts.length - 1];
}
private int emptyPartCount = 0;
/**
* when limit == 0 trailing empty parts are not emitted.
*
* @param part
*/
private void output(String part) {
if (part.isEmpty()) {
emptyPartCount++;
}
else {
for (; emptyPartCount > 0; emptyPartCount--)
if (!o.isUnsubscribed())
o.onNext("");
if (!o.isUnsubscribed())
o.onNext(part);
}
}
};
}
});
} |
Image copyright AFP Image caption The Qatari foreign minister was talking to an audience in London
Bahrain, Egypt, Saudi Arabia and the United Arab Emirates are meeting to discuss the Qatar crisis, a month after they severed ties with the Gulf state.
The meeting of foreign ministers in Cairo comes on the day a deadline expires for Qatar to accept a list of demands or face further sanctions.
The demands to Qatar including shutting down the Al Jazeera broadcaster and scaling down ties with Iran.
Qatar has called the list of demands "unrealistic and not actionable".
Qatar is accused of destabilising the region by supporting extremism and terrorism - which it denies.
In London, Qatari Foreign Minister Sheikh Mohammed bin Abdulrahman al-Thani described the cutting of ties with his country as "a siege that is a clear aggression and an insult".
"The answer to our disagreement is not blockades and ultimatums, it is dialogue and reason," he said.
The tiny gulf emirate has been under unprecedented diplomatic and economic sanctions from Saudi Arabia, Egypt, the UAE and Bahrain.
The restrictions have caused turmoil in the oil- and gas-rich nation, which is dependent on imports to meet the basic needs of its population of 2.7 million.
On Monday, Saudi Arabia and its Arab allies gave Qatar an extra two days to accept their ultimatum for restoring relations, after an earlier 10-day deadline expired.
The authorities in Doha have responded to the demands - but no details have been publicly released. Qatar has said the demands break international law.
The four countries accuse Doha of harbouring Islamist groups that they consider terrorist organisations - including the Muslim Brotherhood - and giving them a platform on the Al Jazeera satellite channel, which is funded by the Qatari state.
Qatar denies the accusations.
As a result of the sanctions, Iran and Turkey have been increasingly supplying Qatar with food and other goods.
On Tuesday, Qatar announced plans for a steep rise in Liquefied Natural Gas (LNG) production capacity over the coming years.
The country is the world's leading producer of LNG.
What are the other demands?
According to Associated Press news agency, which obtained a copy of the list, Qatar must also:
Refuse to naturalise wanted citizens from Bahrain, Egypt, Saudi Arabia and the UAE, in what the countries describe as an effort to keep Qatar from meddling in their internal affairs
Hand over all individuals who are wanted by the four countries for terrorism
Stop funding any extremist entities that are designated as terrorist groups by the US
Provide detailed information about opposition figures whom Qatar has funded, ostensibly in Saudi Arabia and the other nations
Align itself politically, economically and otherwise with the Gulf Co-operation Council (GCC)
Stop funding other news outlets in addition to Al Jazeera, including Arabi21 and Middle East Eye
Pay an unspecified sum in compensation
The demands have not been officially unveiled. Their publication has increased the friction between the two sides.
How did we get here? |
/**
* Saves an automation property to the the properties file.
*
* @param key
* The key of the property
* @param index
* The index of the automation
* @param value
* The value of the property
*/
private void saveAutomationProperty(String key, int index, Object value) {
String strValue = String.valueOf(value);
if (strValue.equals("null") || strValue.equals("")) {
strValue = MidiAutomatorProperties.VALUE_NULL;
}
properties.setProperty(key + MidiAutomatorProperties.INDEX_SEPARATOR
+ index, strValue);
presenter.storePropertiesFile();
} |
import {JsonSchemesRegistry, PropertyRegistry} from "@tsed/common";
import {expect} from "chai";
import * as Sinon from "sinon";
import {MONGOOSE_SCHEMA} from "../../src/constants";
import {buildMongooseSchema, mapProps} from "../../src/utils/buildMongooseSchema";
describe("buildMongooseSchema", () => {
describe("mapProps()", () => {
it("should map a jsonSchema to mongoose schema", () => {
expect(
mapProps({
pattern: "pattern",
minimum: "minimum",
maximum: "maximum",
minLength: "minLength",
maxLength: "maxLength",
enum: ["value1", "value2"],
default: "defaultValue"
})
).to.deep.equal({
match: new RegExp("pattern"),
min: "minimum",
max: "maximum",
minlength: "minLength",
maxlength: "maxLength",
enum: ["value1", "value2"],
default: "defaultValue"
});
});
});
describe("buildMongooseSchema()", () => {
describe("when property is not a class", () => {
class Test {
}
before(() => {
this.propertyMetadata = {
type: String,
required: true,
isClass: false,
store: {
get: Sinon.stub().returns({minLength: 1})
}
};
const map = new Map();
map.set("test", this.propertyMetadata);
this.getPropertiesStub = Sinon.stub(PropertyRegistry, "getProperties").returns(map);
this.getSchemaDefinitionStub = Sinon.stub(JsonSchemesRegistry, "getSchemaDefinition").returns({
properties: {
test: {
maxLength: 9
}
}
});
this.result = buildMongooseSchema(Test);
});
after(() => {
this.getPropertiesStub.restore();
this.getSchemaDefinitionStub.restore();
});
it("should call getProperties and returns a list of properties", () => {
this.getPropertiesStub.should.have.been.calledWithExactly(Test);
});
it("should call store.get", () => {
this.propertyMetadata.store.get.should.have.been.calledWithExactly(MONGOOSE_SCHEMA);
});
it("should return a schema", () => {
expect(this.result.test.maxlength).to.eq(9);
expect(this.result.test.minLength).to.eq(1);
expect(this.result.test.required).to.be.a("function");
expect(this.result.test.type).to.eq(String);
});
});
describe("when property is a class", () => {
class Test {
}
class Children {
}
before(() => {
this.propertyMetadata = {
type: Children,
required: true,
isClass: true,
store: {
get: Sinon.stub().returns(undefined)
}
};
const map = new Map();
map.set("test", this.propertyMetadata);
map.set("_id", {});
const map2 = new Map();
map2.set("test2", {
type: String,
required: false,
isClass: false,
isArray: true,
store: {
get: Sinon.stub().returns(undefined)
}
});
this.getPropertiesStub = Sinon.stub(PropertyRegistry, "getProperties")
.onFirstCall()
.returns(map)
.onSecondCall()
.returns(map2);
this.getSchemaDefinitionStub = Sinon.stub(JsonSchemesRegistry, "getSchemaDefinition")
.onFirstCall()
.returns({
properties: {
test: {}
}
});
this.result = buildMongooseSchema(Test);
});
after(() => {
this.getPropertiesStub.restore();
this.getSchemaDefinitionStub.restore();
});
it("should call getProperties and returns a list of properties", () => {
this.getPropertiesStub.should.have.been.calledWithExactly(Test);
});
it("should call store.get", () => {
this.propertyMetadata.store.get.should.have.been.calledWithExactly(MONGOOSE_SCHEMA);
});
it("should return a schema", () => {
expect(this.result.test.required).to.be.a("function");
expect(this.result.test.required).to.be.a("function");
expect(this.result.test.test2).deep.eq([
{
required: false,
type: String
}
]);
});
it("should not have an _id", () => {
expect(this.result._id).to.eq(undefined);
});
});
});
});
|
/**
* @brief Deletes the cubes from the world once its collected
* by the robot
*
* @param[in] id Id of the cube
*/
void OrderManager::deleteCube(std::string name) {
ros::ServiceClient delete_client =
nh_.serviceClient<gazebo_msgs::DeleteModel>
("gazebo/delete_model");
gazebo_msgs::DeleteModel delete_model;
if (std::find(delete_cubes_.begin(),
delete_cubes_.end(), name) == delete_cubes_.end()) {
delete_model.request.model_name = name;
delete_client.call(delete_model);
delete_cubes_.push_back(name);
}
} |
// Convert between Bob module names, and the name we will give the generated
// cc_library module. This is required when a module supports being built on
// host and target; we cannot create two modules with the same name, so
// instead, we use the `shortName()` (which may include a `__host` or
// `__target` suffix) to disambiguate, and use the `stem` property to fix up
// the output filename.
// Note that this function returns a list of names instead of a single name.
// This is due to resource module that can generate multiple Blueprint modules.
// All other bob modules only return one name.
func bpModuleNamesForDep(mctx blueprint.BaseModuleContext, name string) []string {
var dep blueprint.Module
mctx.VisitDirectDeps(func(m blueprint.Module) {
if m.Name() == name {
dep = m
}
})
if dep == nil {
panic(fmt.Errorf("%s has no dependency '%s'", mctx.ModuleName(), name))
}
if r, ok := dep.(*resource); ok {
var modNames []string
for _, src := range r.Properties.getSources(mctx) {
modNames = append(modNames, r.getAndroidbpResourceName(src))
}
if len(modNames) == 0 {
panic(fmt.Errorf("bob_resource %s has empty srcs", name))
}
return modNames
}
if l, ok := getLibrary(dep); ok {
return []string{l.shortName()}
}
return []string{dep.Name()}
} |
<reponame>Markoy8/Foundry
/*
* File: FriedmanConfidenceTest.java
* Authors: <NAME>
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright May 4, 2011, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government.
* Export of this program may require a license from the United States
* Government. See CopyrightHistory.txt for complete details.
*
*/
package gov.sandia.cognition.statistics.method;
import gov.sandia.cognition.collection.CollectionUtil;
import gov.sandia.cognition.statistics.distribution.ChiSquareDistribution;
import gov.sandia.cognition.statistics.distribution.SnedecorFDistribution;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for class FriedmanConfidenceTest.
* @author krdixon
*/
public class FriedmanConfidenceTest
{
/**
* Random number generator to use for a fixed random seed.
*/
public final Random RANDOM = new Random( 1 );
/**
* Default tolerance of the regression tests, {@value}.
*/
public final double TOLERANCE = 1e-5;
/**
* Default number of samples to test against, {@value}.
*/
public final int NUM_SAMPLES = 1000;
/**
* Default Constructor
*/
public FriedmanConfidenceTest()
{
}
/**
* Test of clone method, of class FriedmanConfidence.
*/
@Test
public void testConstructors()
{
System.out.println("Constructors");
FriedmanConfidence instance = new FriedmanConfidence();
assertNotNull( instance );
}
@Test
public void testCreateStatistic()
{
System.out.println( "Create statistic" );
// Demsar's paper, p. 13
ArrayList<Double> treatmentRankMeans = CollectionUtil.asArrayList(
Arrays.asList( 3.143, 2.000, 2.893, 1.964 ) );
FriedmanConfidence.Statistic instance =
new FriedmanConfidence.Statistic( 4, 14, treatmentRankMeans );
assertEquals( 9.28, instance.getChiSquare(), 0.01 );
assertEquals( 3.69, instance.getF(), 0.01 );
assertEquals( 1.0-SnedecorFDistribution.CDF.evaluate(instance.getF(),3.0, 39.0), instance.getNullHypothesisProbability(), TOLERANCE );
assertEquals( 1.0-ChiSquareDistribution.CDF.evaluate(instance.getChiSquare(),3.0), instance.getChiSquareNullHypothesisProbability(), TOLERANCE );
}
/**
* Test of evaluateNullHypothesis method, of class FriedmanConfidence.
*/
@Test
public void testEvaluateNullHypothesis_Collection_Collection()
{
System.out.println("evaluateNullHypothesis");
Collection<Double> A = Arrays.asList( 9.0, 9.5, 5.0, 7.5, 9.5, 7.5, 8.0, 7.0, 8.5, 6.0 );
Collection<Double> C = Arrays.asList( 6.0, 8.0, 4.0, 6.0, 7.0, 6.5, 6.0, 4.0, 6.5, 3.0 );
FriedmanConfidence instance = new FriedmanConfidence();
FriedmanConfidence.Statistic result = instance.evaluateNullHypothesis(A,C);
System.out.println( "Result: " + result );
}
/**
* Test of evaluateNullHypothesis method, of class FriedmanConfidence.
*/
@Test
public void testEvaluateNullHypothesis_Collection()
{
System.out.println("evaluateNullHypothesis");
// From: http://faculty.vassar.edu/lowry/ch15a.html
Collection<Double> A = Arrays.asList( 9.0, 9.5, 5.0, 7.5, 9.5, 7.5, 8.0, 7.0, 8.5, 6.0 );
Collection<Double> B = Arrays.asList( 7.0, 6.5, 7.0, 7.5, 5.0, 8.0, 6.0, 6.5, 7.0, 7.0 );
Collection<Double> C = Arrays.asList( 6.0, 8.0, 4.0, 6.0, 7.0, 6.5, 6.0, 4.0, 6.5, 3.0 );
@SuppressWarnings("unchecked")
Collection<? extends Collection<Double>> experiment = Arrays.asList( A, B, C );
FriedmanConfidence.Statistic result =
FriedmanConfidence.INSTANCE.evaluateNullHypothesis(experiment);
System.out.println( "Result: " + result );
assertEquals( 9.95, result.getChiSquare(), TOLERANCE );
assertEquals( 2.0, result.getDegreesOfFreedom(), TOLERANCE );
assertEquals( 3, result.getTreatmentCount() );
assertEquals( 10, result.getSubjectCount() );
assertEquals( 2.65, result.getTreatmentRankMeans().get(0), TOLERANCE );
assertEquals( 2.1, result.getTreatmentRankMeans().get(1), TOLERANCE );
assertEquals( 1.25, result.getTreatmentRankMeans().get(2), TOLERANCE );
FriedmanConfidence.Statistic clone = result.clone();
assertNotSame( result.getTreatmentRankMeans(), clone.getTreatmentRankMeans() );
assertEquals( result.toString(), clone.toString() );
}
/**
* Test of evaluateNullHypothesis method, of class FriedmanConfidence.
*/
@Test
public void testEvaluateNullHypothesis2()
{
System.out.println("evaluateNullHypothesis2");
// From: http://www.scribd.com/doc/14109461/Friedman-nonparametric-test
Collection<Integer> A = Arrays.asList( 167, 267, 303, 110, 120, 210, 113, 223 );
Collection<Integer> B = Arrays.asList( 111, 222, 245, 134, 345, 304, 129, 289 );
Collection<Integer> C = Arrays.asList( 310, 456, 532, 220, 678, 315, 189, 430 );
@SuppressWarnings("unchecked")
Collection<? extends Collection<Integer>> experiment = Arrays.asList( A, B, C );
FriedmanConfidence.Statistic result =
FriedmanConfidence.INSTANCE.evaluateNullHypothesis(experiment);
System.out.println( "Result: " + result );
assertEquals( 3.884892407768348E-5, result.getNullHypothesisProbability(), TOLERANCE );
assertEquals( 0.0021874911181828383, result.getChiSquareNullHypothesisProbability(), TOLERANCE );
assertEquals( 12.25, result.getChiSquare(), TOLERANCE );
assertEquals( 2.0, result.getDegreesOfFreedom(), TOLERANCE );
assertEquals( 3, result.getTreatmentCount() );
assertEquals( 8, result.getSubjectCount() );
assertEquals( 22.866666666666667, result.getF(), TOLERANCE );
assertEquals( 1.375, result.getTreatmentRankMeans().get(0), TOLERANCE );
assertEquals( 1.625, result.getTreatmentRankMeans().get(1), TOLERANCE );
assertEquals( 3.0, result.getTreatmentRankMeans().get(2), TOLERANCE );
}
}
|
/**
* Base class of all cylindrical projections.
*/
public abstract strictfp class Cylindrical extends AbstractProjectedProjection {
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Construct a Cylindrical projection.
* @param ellipsoid the ellipsoid for the projection
* @param center the center of the projection
*/
public Cylindrical (Ellipsoid ellipsoid,
Coordinate center,
Unit<Length> units,
double falseEasting,
double falseNorthing) {
super(ellipsoid, center, units, falseEasting, falseNorthing);
}
/** */
public Cylindrical (Ellipsoid ellipsoid, ProjectionParameters parameters)
throws ParseException {
super(ellipsoid, parameters);
}
//-------------------------------------------------------------------------
// AbstractProjection implementation
//-------------------------------------------------------------------------
/** */
public Point process (Point point) {
return point;
}
/** */
public MultiPolygon process (Polygon poly) {
if ((_lineType == LineType.RHUMB) && (!(this instanceof Mercator))) {
poly = ProjectionUtils.createRhumbPoly(poly);
} else if (_lineType == LineType.GREATCIRCLE) {
poly = ProjectionUtils.createGreatCirclePoly(poly);
}
return ProjectionUtils.wrap(poly, _lambda0);
}
/** */
public MultiLineString process (LineString line) {
if ((_lineType == LineType.RHUMB) && (!(this instanceof Mercator))) {
line = ProjectionUtils.createRhumbLine(line);
} else if (_lineType == LineType.GREATCIRCLE) {
line = ProjectionUtils.createGreatCircleLine(line);
}
return ProjectionUtils.wrap(line, _lambda0);
}
/**
* Initialize parameters, and recompute them whenever the ellipsoid or
* projection center changes.
*/
protected void computeParameters () { }
} |
def load_chemkin_output(output_file, reaction_model):
import rmgpy.constants as constants
from rmgpy.quantity import Quantity
core_reactions = reaction_model.core.reactions
species_list = reaction_model.core.species
time = []
core_species_concentrations = []
core_reaction_rates = []
with open(output_file, 'r') as f:
line = f.readline()
while line != '' and 'SPECIFIED END' not in line:
line.strip()
tokens = line.split()
if ' TIME ' in line:
time.append(float(tokens[-2]))
elif ' PRESSURE ' in line:
P = Quantity(float(tokens[-2]), 'atm')
elif ' TEMPERATURE ' in line:
T = Quantity(float(tokens[-2]), 'K')
elif ' MOLE FRACTIONS ' in line:
molefractions = []
line = f.readline()
line = f.readline()
while line.strip() != '':
tokens = line.split()
for value in tokens[2::3]:
if value.find('-') == 0:
value = value.replace('-', '', 1)
if value.find('-') != -1:
if value.find('E') == -1:
value = value.replace('-', 'E-')
molefractions.append(float(value))
line = f.readline()
total_concentration = P.value_si / constants.R / T.value_si
core_species_concentrations.append([molefrac * total_concentration for molefrac in molefractions])
core_rates = []
for reaction in core_reactions:
rate = reaction.get_rate_coefficient(T.value_si, P.value_si)
for reactant in reaction.reactants:
rate *= molefractions[species_list.index(reactant)] * total_concentration
core_rates.append(rate)
if core_rates:
core_reaction_rates.append(core_rates)
line = f.readline()
time = np.array(time)
core_species_concentrations = np.array(core_species_concentrations)
core_reaction_rates = np.array(core_reaction_rates)
return time, core_species_concentrations, core_reaction_rates |
Disruption of catenin‐cadherin interaction decreases tail regeneration in Lumbriculus variegatus.
Lumbriculus variegatus is an aquatic oligochaete that can regenerate new tail segments within two to three weeks of tail removal. While many studies have investigated this ability to regenerate, not much is known about the molecular pathways that are activated during the regeneration process in Lumbriculus. Regeneration of animal tissue must also involve the formation of adherens junctions between new cells in the proliferating tissue. Cadherins are calcium‐dependent adherens molecules that bind adjacent cells together. Cadherins in turn bind to catenins. The β‐catenin has been shown to be important for cell adhesion as well as for the Wnt signaling pathway which influences the polarity of developing organisms. As a first step in determining if β‐catenin is involved in regeneration of new tissue in Lumbriculus, we tested the effect of the β‐catenin inhibitor quercetin, on tail regeneration rate. Low Dose groups were exposed to 25 mM of quercetin and High Dose groups were exposed to 50 mM of quercetin for two weeks. Controls were not exposed to this inhibitor. Results showed that, while all groups experienced tail segment regeneration during the first week of treatment, the rate of regeneration was significantly slower in groups exposed to both low and high doses of quercetin from the second to the fifth day. We suggest that the β‐catenin‐cadherin signaling pathway plays a role in Lumbriculus tissue regeneration. |
<gh_stars>0
#define __MAKEMORE_AUTOGAZER_CC__ 1
#include <netinet/in.h>
#include <string>
#include <algorithm>
#include "cudamem.hh"
#include "tron.hh"
#include "multitron.hh"
#include "twiddle.hh"
#include "closest.hh"
#include "shibboleth.hh"
#include "shibbomore.hh"
#include "convo.hh"
#include "parson.hh"
#include "strutils.hh"
#include "cholo.hh"
#include "normatron.hh"
#include "autogazer.hh"
#include "partrait.hh"
namespace makemore {
using namespace std;
Autogazer::Autogazer(const std::string &_dir) : Project(_dir, 1) {
assert(mbn == 1);
assert(config["type"] == "autogazer");
char gazoutlayfn[4096];
sprintf(gazoutlayfn, "%s/gazoutput.lay", dir.c_str());
gazoutlay = new Layout;
gazoutlay->load_file(gazoutlayfn);
char gazinlayfn[4096];
sprintf(gazinlayfn, "%s/gazinput.lay", dir.c_str());
gazinlay = new Layout;
gazinlay->load_file(gazinlayfn);
char gazmapfn[4096], gaztopfn[4096];
sprintf(gaztopfn, "%s/gaz.top", dir.c_str());
sprintf(gazmapfn, "%s/gaz.map", dir.c_str());
gaztop = new Topology;
gaztop->load_file(gaztopfn);
gazmap = new Mapfile(gazmapfn);
gaz = new Multitron(*gaztop, gazmap, mbn, false);
assert(gaz->outn == gazoutlay->n);
assert(gazoutlay->n == 2);
cumake(&cugaztgt, gaz->outn);
cumake(&cugazin, gaz->inn);
rounds = 0;
}
Autogazer::~Autogazer() {
delete gaz;
delete gazmap;
delete gaztop;
delete gazinlay;
delete gazoutlay;
cufree(cugazin);
cufree(cugaztgt);
}
void Autogazer::report(const char *prog) {
fprintf(
stderr,
"%s %s rounds=%u\n"
"%s %s gaz_err2=%g gaz_errm=%g\n"
"\n",
prog, dir.c_str(), rounds,
prog, dir.c_str(), gaz->err2, gaz->errm
);
}
void Autogazer::save() {
gazmap->save();
}
void Autogazer::load() {
gazmap->load();
}
void Autogazer::observe(const Partrait &par, double mu) {
assert(par.has_mark());
assert(par.has_gaze());
Point gz = par.get_gaze();
Triangle mark;
mark.p = Point(64, 64);
mark.q = Point(64 + 256, 64);
mark.r = Point(64 + 128, 64 + 128 * 3);
Partrait leye(128, 128);
leye.set_mark(mark);
par.warp(&leye);
mark.p = Point(64 - 256, 64);
mark.q = Point(64, 64);
mark.r = Point(64 - 128, 64 + 128 * 3);
Partrait reye(128, 128);
reye.set_mark(mark);
par.warp(&reye);
assert(gaz->inn ==
leye.w * leye.h * 3 +
reye.w * reye.h * 3 +
12
);
leye.encudub(cugazin);
reye.encudub(cugazin + 128 * 128 * 3);
mark = par.get_mark();
double ext[12];
ext[0] = mark.p.x / (double)par.w;
ext[1] = mark.p.y / (double)par.h;
ext[2] = mark.q.x / (double)par.w;
ext[3] = mark.q.y / (double)par.h;
ext[4] = mark.r.x / (double)par.w;
ext[5] = mark.r.y / (double)par.h;
Pose pose = par.get_pose();
ext[6] = pose.center.x / (double)par.w;
ext[7] = pose.center.y / (double)par.h;
ext[8] = pose.scale / (double)par.h;
ext[9] = pose.angle;
ext[10] = pose.stretch;
ext[11] = pose.skew;
encude(ext, 12, cugazin + 2 * (128 * 128 * 3));
gaz->feed(cugazin, NULL);
assert(gaz->outn == 2);
double tgt[2] = {gz.x, gz.y};
//fprintf(stderr, "tgt=%lf,%lf\n", tgt[0], tgt[1]);
encude(tgt, 2, cugaztgt);
gaz->target(cugaztgt);
gaz->train(mu);
}
void Autogazer::autogaze(Partrait *parp) {
const Partrait &par(*parp);
assert(par.has_mark());
Triangle mark;
mark.p = Point(64, 64);
mark.q = Point(64 + 256, 64);
mark.r = Point(64 + 128, 64 + 128 * 3);
Partrait leye(128, 128);
leye.set_mark(mark);
par.warp(&leye);
mark.p = Point(64 - 256, 64);
mark.q = Point(64, 64);
mark.r = Point(64 - 128, 64 + 128 * 3);
Partrait reye(128, 128);
reye.set_mark(mark);
par.warp(&reye);
assert(gaz->inn ==
leye.w * leye.h * 3 +
reye.w * reye.h * 3 +
12
);
leye.encudub(cugazin);
reye.encudub(cugazin + 128 * 128 * 3);
mark = par.get_mark();
double ext[12];
ext[0] = mark.p.x / (double)par.w;
ext[1] = mark.p.y / (double)par.h;
ext[2] = mark.q.x / (double)par.w;
ext[3] = mark.q.y / (double)par.h;
ext[4] = mark.r.x / (double)par.w;
ext[5] = mark.r.y / (double)par.h;
Pose pose = par.get_pose();
ext[6] = pose.center.x / (double)par.w;
ext[7] = pose.center.y / (double)par.h;
ext[8] = pose.scale / (double)par.h;
ext[9] = pose.angle;
ext[10] = pose.stretch;
ext[11] = pose.skew;
encude(ext, 12, cugazin + 2 * (128 * 128 * 3));
const double *cugazout = gaz->feed(cugazin, NULL);
double gz[2];
decude(cugazout, 2, gz);
//fprintf(stderr, "gz0=%lf,%lf\n", gz[0], gz[1]);
parp->set_gaze(Point(gz[0], gz[1]));
}
}
|
//this bean will be automatically injected inside boot's ObjectMapper
@Bean
public Module customizeCloudProcessModelObjectMapper() {
SimpleModule module = new SimpleModule("mapProcessRuntimeEvents",
Version.unknownVersion());
module.registerSubtypes(new NamedType(CloudBPMNActivityStartedEventImpl.class,
BPMNActivityEvent.ActivityEvents.ACTIVITY_STARTED.name()));
module.registerSubtypes(new NamedType(CloudBPMNActivityCompletedEventImpl.class,
BPMNActivityEvent.ActivityEvents.ACTIVITY_COMPLETED.name()));
module.registerSubtypes(new NamedType(CloudBPMNActivityCancelledEventImpl.class,
BPMNActivityEvent.ActivityEvents.ACTIVITY_CANCELLED.name()));
module.registerSubtypes(new NamedType(CloudBPMNSignalReceivedEventImpl.class,
BPMNSignalEvent.SignalEvents.SIGNAL_RECEIVED.name()));
module.registerSubtypes(new NamedType(CloudProcessDeployedEventImpl.class,
ProcessDefinitionEvent.ProcessDefinitionEvents.PROCESS_DEPLOYED.name()));
module.registerSubtypes(new NamedType(CloudStartMessageDeployedEventImpl.class,
MessageDefinitionEvent.MessageDefinitionEvents.START_MESSAGE_DEPLOYED.name()));
module.registerSubtypes(new NamedType(CloudProcessStartedEventImpl.class,
ProcessRuntimeEvent.ProcessEvents.PROCESS_STARTED.name()));
module.registerSubtypes(new NamedType(CloudProcessCreatedEventImpl.class,
ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name()));
module.registerSubtypes(new NamedType(CloudProcessUpdatedEventImpl.class,
ProcessRuntimeEvent.ProcessEvents.PROCESS_UPDATED.name()));
module.registerSubtypes(new NamedType(CloudProcessCompletedEventImpl.class,
ProcessRuntimeEvent.ProcessEvents.PROCESS_COMPLETED.name()));
module.registerSubtypes(new NamedType(CloudProcessSuspendedEventImpl.class,
ProcessRuntimeEvent.ProcessEvents.PROCESS_SUSPENDED.name()));
module.registerSubtypes(new NamedType(CloudProcessResumedEventImpl.class,
ProcessRuntimeEvent.ProcessEvents.PROCESS_RESUMED.name()));
module.registerSubtypes(new NamedType(CloudProcessCancelledEventImpl.class,
ProcessRuntimeEvent.ProcessEvents.PROCESS_CANCELLED.name()));
module.registerSubtypes(new NamedType(CloudSequenceFlowTakenEventImpl.class,
SequenceFlowEvent.SequenceFlowEvents.SEQUENCE_FLOW_TAKEN.name()));
module.registerSubtypes(new NamedType(CloudIntegrationRequestedEventImpl.class,
IntegrationEvent.IntegrationEvents.INTEGRATION_REQUESTED.name()));
module.registerSubtypes(new NamedType(CloudIntegrationResultReceivedEventImpl.class,
IntegrationEvent.IntegrationEvents.INTEGRATION_RESULT_RECEIVED.name()));
module.registerSubtypes(new NamedType(CloudIntegrationErrorReceivedEventImpl.class,
IntegrationEvent.IntegrationEvents.INTEGRATION_ERROR_RECEIVED.name()));
module.registerSubtypes(new NamedType(CloudBPMNTimerFiredEventImpl.class,
BPMNTimerEvent.TimerEvents.TIMER_FIRED.name()));
module.registerSubtypes(new NamedType(CloudBPMNTimerScheduledEventImpl.class,
BPMNTimerEvent.TimerEvents.TIMER_SCHEDULED.name()));
module.registerSubtypes(new NamedType(CloudBPMNTimerExecutedEventImpl.class,
BPMNTimerEvent.TimerEvents.TIMER_EXECUTED.name()));
module.registerSubtypes(new NamedType(CloudBPMNTimerFailedEventImpl.class,
BPMNTimerEvent.TimerEvents.TIMER_FAILED.name()));
module.registerSubtypes(new NamedType(CloudBPMNTimerRetriesDecrementedEventImpl.class,
BPMNTimerEvent.TimerEvents.TIMER_RETRIES_DECREMENTED.name()));
module.registerSubtypes(new NamedType(CloudBPMNTimerCancelledEventImpl.class,
BPMNTimerEvent.TimerEvents.TIMER_CANCELLED.name()));
module.registerSubtypes(new NamedType(CloudBPMNMessageReceivedEventImpl.class,
BPMNMessageEvent.MessageEvents.MESSAGE_RECEIVED.name()));
module.registerSubtypes(new NamedType(CloudBPMNMessageSentEventImpl.class,
BPMNMessageEvent.MessageEvents.MESSAGE_SENT.name()));
module.registerSubtypes(new NamedType(CloudBPMNMessageWaitingEventImpl.class,
BPMNMessageEvent.MessageEvents.MESSAGE_WAITING.name()));
module.registerSubtypes(new NamedType(CloudBPMNErrorReceivedEventImpl.class,
BPMNErrorReceivedEvent.ErrorEvents.ERROR_RECEIVED.name()));
module.registerSubtypes(new NamedType(CloudMessageSubscriptionCancelledEventImpl.class,
MessageSubscriptionEvent.MessageSubscriptionEvents.MESSAGE_SUBSCRIPTION_CANCELLED.name()));
module.registerSubtypes(new NamedType(CloudApplicationDeployedEventImpl.class,
ApplicationEvent.ApplicationEvents.APPLICATION_DEPLOYED.name()));
SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver() {
@Override
public JavaType resolveAbstractType(DeserializationConfig config,
BeanDescription typeDesc) {
return findTypeMapping(config,
typeDesc.getType());
}
};
resolver.addMapping(IntegrationRequest.class, IntegrationRequestImpl.class);
resolver.addMapping(IntegrationResult.class, IntegrationResultImpl.class);
resolver.addMapping(IntegrationError.class, IntegrationErrorImpl.class);
resolver.addMapping(CloudProcessDefinition.class,
CloudProcessDefinitionImpl.class);
resolver.addMapping(CloudStartMessageDeploymentDefinition.class,
CloudStartMessageDeploymentDefinitionImpl.class);
resolver.addMapping(CloudProcessInstance.class,
CloudProcessInstanceImpl.class);
resolver.addMapping(CloudBPMNActivity.class,
CloudBPMNActivityImpl.class);
resolver.addMapping(CloudIntegrationContext.class,
CloudIntegrationContextImpl.class);
resolver.addMapping(CloudServiceTask.class,
CloudServiceTaskImpl.class);
resolver.addMapping(Deployment.class,
DeploymentImpl.class);
resolver.addMapping(CloudApplication.class,
CloudApplicationImpl.class);
module.setAbstractTypes(resolver);
return module;
} |
package org.enlightenseries.DomainDictionary.infrastructure.datasource.relation;
import org.enlightenseries.DomainDictionary.domain.model.relation.Relation;
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 java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.setRemoveAssertJRelatedElementsFromStackTrace;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RelationMapperTest {
@Autowired
private RelationMapper relationMapper;
@Before
public void setup() {
}
@Test
public void insertOne() {
// when
Relation assertData = new Relation();
// try
relationMapper.insert(assertData);
Relation subject = relationMapper.select(assertData.getId());
// expect
assertThat(subject.getId().toString()).isEqualTo(assertData.getId().toString());
}
@Test
public void delete() throws Exception {
// when
Relation assertData = new Relation();
relationMapper.insert(assertData);
// try
relationMapper.delete(UUID.fromString(assertData.getId().toString()));
Relation subject = relationMapper.select(assertData.getId());
// expect
assertThat(subject).isNull();
}
}
|
<filename>model/application.go<gh_stars>1-10
package model
// Application 应用
type Application struct {
AppSecret string `json:"secret" gorm:"column:secret;not null;size:32"`
BaseModel
}
|
It can be a hard negotiation with yourself, summer league.
You see the numbers, but you also want to discredit them. I mean, I was listening to the Basketball Analogy Podcast and ESPN’s Tom Haberstroh rattled off the top scorers from the Vegas league dating back to 2005. The list had some impressive names (including Damian Lillard and Kawhi Leonard), but also a bunch of other random dudes who carved out fine enough careers, but never turned into franchise altering players.
Lonzo Ball isn’t on the list of Vegas’ top bucket getters, but he’s putting up other types of numbers. He’s leading all of Vegas in assists. He’s rung up two triple-doubles in his last three games and had a 36 point, 11 assist contest sandwiched in the middle of them. Even though his outside shot isn’t falling, the numbers pop. I so badly want them to matter, but understand any weight I want them to carry comes with a caveat of this being Las Vegas in July, not STAPLES Center in May or June.
The eye test can be funny, too, because the human brain can be funny. It has a way of attaching value to things to create a lasting memory; a way of ascribing importance to things that verify what you already want to believe while diminishing the things which don’t quite fit into your pre-established outlook.
As I negotiate that in my head, though, a realization starts to seep in. I don’t care if it’s only summer league, Lonzo Ball is special.
I see a kid who is, without exaggeration, changing the approach his team takes on the floor. He is the patient zero in the outbreak of unselfish summer league basketball. Guys are running harder because he’s willing to give up the ball in the backcourt by throwing ahead to them. I see guys making the extra pass, not necessarily because they know it’s the right play, but because it’s how this team now plays. I see guys who are typically gunners, getting hockey assists. And I credit this kid, this rookie.
I also see a player who, despite his experience level and an age still in the teens, being someone who is smarter than most of his peers in how he’s thinking out scenarios in front of him. I see someone who is manipulating angles, taking a screen in one direction only to set up a re-screen in the other. I see a player taking as many extra dribbles as is needed to freeze the help defender so the pass he makes is going to a wide open teammate. I see someone who pauses a beat, waiting until the exact moment when a teammate’s crease into open space develops, to deliver the ball.
And he does this stuff naturally. As if it’s instinct. But not many players have these instincts. At least not from what I can tell. Because if they did, we’d see more people play like this, right?
None of this makes a perfect player, of course. To this point in Vegas, the shot making has been low and the turnover count high. Fatigue has led to forced passes, some suspect shot selection, and some defensive effort issues which can (and have) hurt the team. On one possession, I saw him jog back on defense, see his man out of the corner of his eye start to cut behind him, and then him just stand there above the shoulder of the three point line guarding no one. On another I saw him dribble the ball up and launch a three pointer when his defender went under a screen. Yeah, he was tired and on many levels it’s excusable. But I point it out to say that improvement will be needed.
But he’s 19 years old. Do you think he’s going to find a way to improve? That he’ll get stronger? That he’ll find the range on his jumper? Gain experience and become smarter? Become more in tune with what his limits are? What his teammates’ limits are? Learn where he can take risks? When he can force shots?
I believe the answer to these questions are yes. To all of them. Time is on his side. And so are smarts and, at least to me, what looks like an innate and acute understanding of how to play basketball within the team concept. No, that’s wrong. An innate and acute ability to foster and contribute to an environment where team play thrives.
I don’t care if it’s summer league. Lonzo Ball is special. This, I am pretty much sure of. |
<reponame>andrey-nakin/gneis-geant4
#ifndef isnp_dist_UniformCircle_hh
#define isnp_dist_UniformCircle_hh
#include <G4Types.hh>
#include "isnp/dist/AbstractDistribution.hh"
#include "isnp/util/PropertyHolder.hh"
namespace isnp {
namespace dist {
class UniformCircleProps {
public:
UniformCircleProps(G4double aDiameter);
G4double GetDiameter() const {
return diameter;
}
void SetDiameter(G4double const v) {
diameter = v;
}
private:
G4double diameter;
};
class UniformCircle: public AbstractDistribution, public util::PropertyHolder<
UniformCircleProps> {
public:
using util::PropertyHolder<UniformCircleProps>::PropertyHolder;
G4ThreeVector Generate() const override;
};
}
}
#endif // isnp_dist_UniformCircle_hh
|
Labour was thrown into fresh embarrassment over MPs and their expenses yesterday when the husband of the home secretary, Jacqui Smith, was forced to apologise for trying to claim back the cost of the family's television package, which included rental of two pornographic movies.
Richard Timney, who is employed by the home secretary in her constituency office, submitted a claim for a £67 Virgin Media bill last June for a television in the couple's family home in Redditch, Smith's constituency. The bill included two adult films, at a cost of £5 each, as well as two viewings of the heist movie Ocean's 13 and one of Surf's Up, a children's film about a rockhopper penguin.
Smith, who was already in the spotlight over expenses, was understood to be furious with her husband. Last month she was revealed to have claimed taxpayer-funded allowances for her family home while living with her sister in London. Smith designated her sister's house as her "main" residence, allowing her to claim payments on the Redditch constituency home she shares with her husband and children. Smith is due to explain that to the parliamentary commissioner for standards, John Lyon.
The new row brought an immediate climbdown from the Smiths. Within hours of the story being published in a Sunday newspaper, Timney appeared outside the family home to give a brief statement.
Barely looking up, he said he had submitted the claim for the television package "inadvertently" alongside a legitimate claim for his wife's internet connection. Timney said: "I am really sorry for any embarrassment I have caused Jacqui. I can fully understand why people might be angry and offended by this. Quite obviously, a claim should never have been made for these films, and as you know that money is being paid back."
Smith, who employs her husband on a salary of £40,000 a year to run her office, was said to be "mortified" after she was forced to apologise for the claim. A close friend of Smith's said Timney would be "sleeping on the sofa for a while. To say she's angry with her husband is an understatement".
Although parliamentary rules on expenses allow MPs to claim the cost of their television package alongside their internet connection, the friend said Smith planned to repay the entire amount. The committee on standards in public life has announced it will look at the system of expense claims by MPs, but it is unlikely to report until after the general election.
There are rumours in Whitehall about how details of the Smiths' television bill emerged. It follows a run of recent expenses scandals involving Labour MPs, suggesting that stories are being leaked from the parliamentary office for expenses claims.
Apologising for the wrongful claim, Smith said: "I am sorry that, in claiming for my internet connection, I mistakenly claimed for a television package alongside it. As soon as the matter was brought to my attention, I took immediate steps to contact the relevant parliamentary authorities and rectify the situation. All money claimed for the television package will be paid back in full."
Opposition MPs cast doubt on Smith's ability to continue as home secretary. Former shadow home secretary David Davis said: "My first response was, under what category would this expense claim be?" He added: "I don't call for people to go unless I think there is absolutely a smoking gun, but I do think on this circumstance the sympathy for her will be even less than it otherwise would have been because she is not that good at her job."
No 10 said Smith had done the "right thing" by acting to rectify the "inadvertent mistake". A spokesman said: "She is doing a great job as home secretary and will not let this issue detract from her determination to ensure we protect the public and make our neighbourhoods safer." |
// GameInit -- [re]initializes a new round of gameplay
static void GameInit(uint8_t initFlags)
{
if ( ! (initFlags & GAME_INIT_KEEP_SCORES)) {
SDL_memset(&Scores, 0, sizeof(Scores));
}
GameTicksToNextRound = 0;
for (uint8_t i = 0; i < SDL_arraysize(Paddles); ++i) {
Paddles[i].x = PaddleXs[i];
if ( ! (initFlags & GAME_INIT_KEEP_PADDLE_STATE)) {
Paddles[i].y = (ScreenHeight - HUDHeight - PaddleMaxH) / 2.f;
Paddles[i].vy = 0.f;
Paddles[i].laserRechargeTicks = 0;
}
}
Paddles[0].ballBounceDirection = 1;
Paddles[0].ballType = BallTypeBlue;
Paddles[1].ballBounceDirection = -1;
Paddles[1].ballType = BallTypeRed;
for (uint8_t i = 0; i < SDL_arraysize(Paddles); ++i) {
if ((!(initFlags & GAME_INIT_ONLY_HEAL_DEAD_PADDLES)) ||
(Paddles[i].cutTop >= Paddles[i].cutBottom))
{
PaddleHeal(i);
}
}
Paddles[0].keyUp = SDL_SCANCODE_LSHIFT;
Paddles[0].keyDown = SDL_SCANCODE_LCTRL;
Paddles[0].keyLaser = SDL_SCANCODE_Z;
Paddles[1].keyUp = SDL_SCANCODE_RETURN;
Paddles[1].keyDown = SDL_SCANCODE_RSHIFT;
Paddles[1].keyLaser = SDL_SCANCODE_SLASH;
for (uint8_t i = 0; i < SDL_arraysize(Lasers); ++i) {
Lasers[i].magnitude = 0.f;
}
if ( ! (initFlags & GAME_INIT_KEEP_POWERUPS)) {
SDL_memset(Powerups, 0, sizeof(Powerups));
uint8_t numPowerupsToSpawn = MathRandRangeI(0, 4);
for (uint8_t i = 0; i < SDL_arraysize(Powerups); ++i) {
if (i < numPowerupsToSpawn) {
PowerupRespawn(i);
} else {
PowerupDeactivate(i);
}
}
}
BallRespawn(0);
} |
For Beginners LLC
155 Main Street, Suite 211
Danbury, CT 06810 USA
www.forbeginnersbooks.com
Text: © 1993 Lydia Alix Fillingham
Illustrations: © 1986 Moshe "MOSH" Süsser
Cover Illustration: Moshe "MOSH" Süsser
Cover Design: Terrie Dunkelberger
Book Design: Daryl Long and Terrie Dunkelberger
Production Assistant: Marcia "MONTANA" DeVoe
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior permission of the publisher.
A For Beginners® Documentary Comic Book
Originally published by Writers and Readers, Inc.
Copyright © 1993
Cataloging-in-Publication information is available from the Library of Congress.
eISBN: 978-1-939994-08-0
For Beginners® and Beginners Documentary Comic Books® are published
by For Beginners LLC.
v3.1
## Table of Contents
Introduction
Madness and Civilization
The Birth of the Clinic
The Order of Things
Discipline and Punish
The History of Sexuality
Further Reading
Index
Let's answer the second question first.
First name is pronounced like the English girl's name, Michelle. Foucault is **foo** as in fooey, plus **co** as in coco-nut, coming down harder on the coconut.
**Who was he?**
A French guy, of a peculiar French type,
**THE FAMOUS**
**INTELLECTUAL.**
The Famous Intellectual of the generation before his was
**JEAN-PAUL SATRE,**
who really defined the type: a thinker with thoughts on a wide variety of subjects, popularly recognized as an important national resource, expected to say brilliant, unexpected things,to get involved in politics from time to time, and to symbolize knowledge and thought for the nation and the world.
After Sartre, there was no agreement about who stood on the intellectual pinnacle.
Struggling towards the peak in the sixties were:
He worked in so many different fields that it is very hard to categorize his work. In a bookstore today you might find his books in Philosophy, History, Psychology, Sociology, Medicine, Gender Studies, and Literary or Cultural Criticism.
You might say he started with the truism
"KNOWLEDGE IS POWER,"
took it apart, analyzed it, and put it back together. He was particularly interested in Knowledge **of** human beings, and Power that acts **on** human beings.
Suppose we start with the statement
"KNOWLEDGE IS POWER"
but doubt that we have any knowledge of absolute truth.
If you take away the idea of absolute truth, what does knowledge mean?
In one case physical force, in the other mental force, is exerted by a powerful minority who are thus able to impose their idea of the right, or the true, on the majority.
When we're talking about knowledge of human beings, the social sciences, or, as Foucault calls them, "the human sciences," then the people deciding what is true (constructing Truth) are deciding matters that define humanity, and affect people in general. If they can get enough people to believe what they have decided, then that may be more important than some unknowable truth.
### But hang on!
How do some people get the rest of us to accept their ideas of who we are? That involves some power to create belief. And these same people who decide what is knowledge in the first place can easily claim to be the most knowledgeable—to know more about us than we do ourselves.
But how does knowledge/power get its work done? Often knowledge/power and physical force are allied, as when a child is spanked to teach her a lesson. But primarily knowledge/power works through language. At a basic level, when a child learns to speak, she picks up the basic knowledge and rules of her culture at the same time.
On a more specialized level, all the human sciences (psychology, sociology, economics, linguistics, even medicine) define human beings at the same time as they describe them, and work together with such institutions as mental hospitals, prisons, factories, schools, and law courts to have specific and serious effects on people.
We would naturally tend to define
as everything which differs significantly from the
But by looking at a wide variety of historical documents, Foucault challenges all of these assumptions. He shows that definitions of madness, illness, criminality, and perverted sexuality vary greatly over time.
Behavior that got people locked up or put in hospitals at one time was glorified in another.
Societies, knowledge/power, and the human sciences have, since the 18th century, carefully defined the difference between normal and abnormal, and then used these definitions all the time to regulate behavior. Distinguishing between the two may appear to be easy, but is in fact extremely difficult—there is always a hazy and highly contested borderline.
Our society has increasingly locked up, excluded, and hidden abnormal people, while nevertheless watching, examining, questioning them carefully.
It has not always been this way. In earlier times madmen were an accepted part of the community; sick people were treated at home; no one expected disabled or disfigured people to stay out of sight; and criminals were punished as publicly as possible.
This exclusion of abnormal people does not make these people unimportant to the culture. The normal is not defined first, with the abnormal established in contrast! We actually define the normal through the abnormal; only through abnormality do we know what normal is. Therefore, although abnormality is excluded and supposedly hidden, the remaining people, normal people, study and question it incessantly, obsessively.
The study of abnormality is one of the main ways that power relations are established in society. When an abnormality and its corresponding norm are defined, somehow it is always the normal person who has power over the abnormal.
The psychologist tells us about the madmen, the physician about the patients, the criminologist (or the legal theorist, or the politician) talks about the criminals, but we never expect to hear the latter talk about the former—what they have to say has already been ruled irrelevant, because by definition they have no knowledge (but that is code for not wanting them to have any power).
**Ever-so-quick summary of Foucault's life:**
Born in 1926, in Poitiers, a provinicial city, and named Paul-Michel Foucault.
Father Paul was a surgeon, father's father was a surgeon. So guess what Papa wanted young Paul-Michel to be?
When he was 17, Paul-Michel decided he couldn't be a doctor, despite a big fight with his father, and later he decided he couldn't be Paul, either. When he was 13, World War II began, and Poitiers was occupied by the Germans. In his Jesuit school, Paul-Michel wasn't exactly a war hero, but he did help the other kids steal wood from the Nazis to heat the school.
The war was an ordeal he lived through, but the real adventure of his life was his school career.
The French academic system has, for the most successful students, a sense of competition and excitement about it, probably only equalled in the US by the Olympics.
Foucault entered school, the Lycée Henri-IV, at the age of four. He was too young for school, but he didn't want to be separated from his older sister. For two years he sat in the back of the classroom, playing with crayons, and maybe listening. He liked school, and stayed on, getting top grades in everything but math, until suddenly in his eighth year he was barely passing.
His mother decided it was time for him to go to a Jesuit school, the Collège Saint-Stanislaus. He did very well there, but almost always came in second to his friend Pierre Rivière. (Remember that name, it might come up later.)
Foucault went from school to school, doing extremely well on his exams, until he had reached the summit: he scored fourth among all the students in the country competing for entry to the Ecole Normale Supérieure in Paris—the most exclusive and intellectually intense college-level school in France.
But at the Ecole Normale, Foucault was not a happy boy. He grew more and more depressed, didn't get along with the others, and finally attempted suicide.
His father took him to see a psychiatrist, whom young Michel told of his sexual interest in men.
Psychiatrists then tended to treat homosexuality as an illness that inevitably caused misery, which didn't do much to relieve Michel's depression.
But he began at this point to get the idea that perhaps psychiatrists were doing more than just helping the distraught—maybe they were mental police, deciding what should or shouldn't be allowed in society.
Still, he wanted to study psychology for himself, and found it fascinating. He read Freud, and the Kinsey Report.
His teachers at the Ecole Normale took students to see patients at a mental hospital in Paris, and to visit another hospital near Orléans for a week each year, to observe both doctors and patients.
Foucault was a bit obsessed with Rorschach tests, giving them to all the students at the Ecole Normale (and to many others throughout his life), and then making quick evaluations of their underlying psyches.
Along with pretty much every one else he knew, Foucault joined the Communist Party (1950-1953), quitting around the time of Stalin's death, when many others were questioning what had been going on in the Soviet Union.
In 1955 Foucault took a job as French instructor in Upsalla, Sweden. There he came upon a huge library of medical works from the 16th to the 20th centuries. For the next few years he immersed himself in this library, and did the research for what would become **Folie et déraie;on (Madneess and Civilization)** and **Naissance de la clinique (The Birth of the Clinic)**.
What we have in English is only a great abridgment of the original book, which is over 600 pages long.
Well, suppose you see a man who has odd violent outbursts at no one in particular and strikes out at the air meet around him.
Now you meet another man who tells you that the FBI has planted a radio receiver in his brain and is monitoring his thoughts, and he believes they will soon take control of him. (Let's assume you don't believe him.)
Then you meet a man who sits perfectly still and does not move or speak, though you discover that he is physically capable of doing so.
Look at these three men, forgetting for a moment everything you have heard about insanity. Clearly each of them has a problem that may keep him from functioning well in our society.
They might seem to be using logic very rigorously. If the FBI had placed a transmitter in your brain to monitor your thoughts, it would make sense to suspect them of trying to take control of you.
### But then, suddenly, in the 14th century, leprosy disappeared!
Everyone was happy about it, but what were they supposed to do with these big places to lock people up? They left them empty, but just for a while...
In the 15th century a new idea cropped up, and became a central image in the popular imagination:
Wandering down a river, a ship of outcast men are taken from one town to the next, always expelled, frequently with a payment to the captain to keep them on their way.
Why did this image suddenly pop up? A cultural fascination with madness. A terrifying threat that may contain an even more terrifying truth. Erasmus (1466-1536), a Dutch philosopher, wrote **The Praise of Folly** ( **Moriae Encomium,** 1509). It and Shakespeare's **King Lear** (1605) both focus on the dangerous insights the madman may have.
IN the 17th century, suddenly as many people as possible were locked up. Criminals, yes, for any small infraction, and madmen, anyone acting strangely (and this certainly included epileptics), and the sick who might earlier have been taken care of at home, but the poor as well, anyone out of work. One Parisian in a hundred was confined. This is where the old leprosy houses came in very handy.
The mad became thought of as a subcategory of the unemployed. You might think that the poor were victims of an economic problem, but no, they were creators of a moral one.
Madness was now shameful and must be hidden.
In the 17th and 18th centuries, not content with pinning down the madman, people wanted to pin down the idea of madness as well.
#### How did they think of madness?
By the end of the 18th century, it was said that physical treatment alone would not cure madness.
This did not mark the beginning of psychological treatment, but rather the breakdown of the unity of body and soul, the breakdown of the internal consistency of the symbol system.
Mirabeau and the Marquis de Sade, two French Counts were both in prison at the same time, as incorrigible upper-class libertines.
Sade, father of sadism, the "true madman, and truly immoral," is let out first, while Mirabeau, soon to be the hero of his country, rots in jail for no real reason; this irony symbolizes, for the Revolutionaries, the whole problem with the world.
### THEN THE REVOLUTION HAPPENS.
STORMING OF THE BASTILLE.
MIRABEAU WILL LEAD THE PEOPLE IN THEIR FIGHT AGAINST
### THE PEOPLE ARE IN POWER!
GET RID OF THE KING!
GET RID OF THE CHURCH!
GET RID OF THE RICH!
Until, eventually, too many people are being gotten rid of.
But meanwhile, this is not quite how the mad experienced it. After the Revolution began, they were supposed to be taken out of prisons (mostly because it was too humiliating to the prisoners to be locked up with them), and put in special hospitals.
> But the hospitals didn't exist.
> So they were sent home to their families.
Then they were sent away from their homes because they were too much trouble (or at least seemed like they might be).
Myths developed of the two great liberators of the mad; noble and wise men who humanized the treatment of insanity:
**Pinel** (Philippe Pinel), the great liberator of the mad during the French Revolution, walks into the prisons and throws off the chains of the madmen. When questioned, he says, "Citizen, I am convinced that these madmen are so intractable only because they have been deprived of air and liberty."
The mad have their own revolution, and their own liberator.
**Samuel Tuke,** a gentle Quaker, sets up a rural retreat for the mad. No bars, no chains. Looks like a farm, feels like a family.
#### The REAL story behind the myth:
Tuke—Yes, the retreat is a family, and the mad are the children, who must learn to respect the authority of the father, Tuke himself. The mad must be raised and disciplined as children. They must be taught religion, the source of all morality, and they must have chores, since work is enormously important in teaching one to regulate oneself. The chains are taken off, but if you are bad, they will be put back on, and you will have only yourself to blame.
As an 18th century madman you had a certain kind of freedom from responsibility that was now utterly removed. Now madness was your own fault, your responsibility, and because other people were always watching you, you learned to watch yourself.
Tuke and his attendants would conduct tea-parties for the patients, but far from being social treats, they were fearsome tests. The patients each had to act the part of an unknown stranger visiting from afar, and had to behave with decorum and make small talk. Thus the new ideal is set for patient behavior. They must each learn to become the perfectly anonymous "normal" person, with no unusual traits, no individuality.
Pinel established a system of morality very much connected to the newly dominant middle-class as the absolute power within the asylum, and thus the standard for society as a whole. The danger of madness now came from lower-class people who did not wish to conform to this standard.
The keepers continually sat in judgment on the mad, meting out punishment for every transgression.
The pattern of judgment and punishment had to be repeated until firmly **internalized** by the patient.
### Enter... the Doctor!
(He wasn't there in the older asylums.)
**W** hat good can someone trained in medicine do to those who are not physically ill? THE DOCTOR IS A CERTIFIED WISE AND NOBLE MAN. Both Tuke and Pinel found the most important thing to be the presence of a great moral authority, and both hired doctors for their asylums. Gradually the doctor took over as THE FATHER from such non-specialists as Tuke and Pinel. The only problem was that doctors forgot that they were there because they were noble and wise. They thought that medicine was a hard science, that they were in the asylum as scientists, and that they could shed exact light upon this disease.
To the patients, and to the world at large, the doctor's power seemed increasingly magical, even as the doctors told us how scientific it was.
Everything centers on the doctor-patient relationship—only there can the sickness be understood; only there can the cure be effected. And here, at the end of the trail, we find
**F** reud knew that the doctor was a wise father, and that it was all about parental authority. Freud knew that the doctor had to be a wise man, and that everything hinged on the doctor-patient relationship—in fact, the cure could be found exactly there—in how the patient reacted to the doctor.
Having been to an analyst himself, Foucault had some doubts.
Foucault started thinking about Freud in writing this book, but he wasn't finished by a long shot.
### What exactly does Foucault mean by the Clinic?
Actually, you've seen it on TV. Think of Dr. Kildare, Dr. Welby, St. Elsewhere, or Doogie Howser (pick the one from your generation). In all of those shows you've seen the experienced doctor making the rounds of the wards, along with eager and scared novices.
If you've been in a hospital you may have seen the same thing. You probably accept it as a natural part of being sick and in a hospital, part of what helps you. But notice what happens to the patient in these interchanges.
A bunch of people crowd around the bed staring at her, perhaps poking and feeling. She is supposed to be silent unless she is asked a question, and at times she is used as the basis for the ritual humiliation of a student. She becomes a thing, a disease, as the doctors are not interested in anything else about her. (Except, of course, the TV doctor-hero who always sees and understands the real person lying there.)
**A** ll of this, the teaching hospital and the notion of clinical medicine as the best method of treating patients and of training doctors, at the same time, is what Foucault refers to by
One big element in its creation was, once again:
#### There were two great medical dreams of the Revolution:
A nationalized, almost religious order of doctors, who would care for the body as the priests had formerly cared for the soul.
a perfected social order, with no more disease at all!
The diseases of the poor are products of the horrible conditions in which they live, and the diseases of the rich are the result of their dissipation.
#### But how do you put such policies into place?
In the Revolution, the first move was to get rid of the old ways. The Universities were seen as the bastions of the elite, so they were done away with. The hospitals were seen as a waste of money—people could be cared for more efficiently at home, within the family. So no more hospitals. Hospital funds were seized, and sometimes saved, sometimes used to fund public charity, and sometimes turned into ready cash.
So certainly doctors were needed. Medical officers were needed, and pretty much anyone was accepted and given a little bit of training. These people would return to civilian life as doctors and, unsupervised, could do a lot of damage.
#### Something had to be done.
University-trained doctors began teaching students in secret.
After the Revolution, the whole system was rebuilt from scratch. Hospitals had to be rebuilt, and they were usually connected to the rebuilt universities.
#### So what is important about the Clinic?
Teaching is united with practice.
The Clinic becomes a basis for the licensing of doctors, which gradually became much more restricted.
THE PROFESSOR OF MEDICINE becomes a very powerful figure. He examines the patient, and then "examines" the students. At the same time, the professor is always taking a risk. If he makes a blunder, it may be seen by all the students.
Patients accept the clinical rounds as part of their necessary service to the state. Yes, they may die, but nobly, since they will add to human knowledge.
As the place of medical learning, the clinic offers up a series of diseases. All examples of a particular disease may be located in a single ward. The disease is what is important, the individual patient is just an accident. The more unusual the disease, the more interesting the patient. So the diseases are laid out spatially, and the professor walks from one to another, turning his all-powerful eye on each one.
A kind of active vision, what Foucault calls
**A** desire develops for a complete nosology (a system of classifying all disease) that would be like Linnaeus' taxonomy of plants and animals.
But not enough is known about disease—too much is hidden from the eye. Suddenly there is a new focus:
**D** issecting corpses was not actually so new, but deciding that it was central was very different. Suddenly the eye can see inside the body, and all of disease is visible to the Gaze.
Death and disease change from purely negative ideas to crucial elements in the process of life.
**S** cience focuses on general principles, not on individual circumstances. Newton did not stop his thought at the particular apple that fell on his individual head; he developed a principle that would account for all apples, all objects, falling.
**B** ut such science has a great deal of difficulty dealing with human beings. For some reason, we can be very abstract about apples, but when humans are concerned, we tend to care very much about the actual individual.
**A** round the end of the 18th and the beginning of the 19th centuries, many sciences began to focus on humans, namely the Human Sciences: economics, anthropology, linguistics, psychology and so on.
Medicine is more like **HARD SCIENCE** than the others, but it has always focused on humans. Opening up the corpses, Foucault maintained, gave medicine the opportunity to subject all of the Body to the scientific Gaze.
and his power came from his way of seeing rather than from his abstract theories.
Oddly enough, this enormously complex and difficult book became an immediate hit in France. Suddenly everybody had to have one, and Foucault was famous. He liked the recognition, but suspected that not everyone who bought the book really read and understood it.
As a matter of fact, he always felt that his work was not for everyone. He thought you needed to have a very good background in philosophy and history or his work would just be misunderstood. He wouldn't have approved of this book at all.
Foucault starts **The Order of Things** by quoting a passage from the Argentine writer Jorge Luis Borges:
This passage quotes " **a certain Chinese encyclopedia** " in which it is written that " **animals are divided into:**
**(a) belonging to the Emperor,**
**(b) embalmed,**
**(c) tame,**
**(d) suckling pigs,**
**(e) sirens,**
**(f) fabulous,**
**(g) stray dogs,**
**(h) included in the present classification,**
**(i) frenzied,**
**(j) innumerable,**
**(k) drawn with a very fine camelhair brush,**
**(l) et cetera,**
**(m) having just broken the water pitcher,**
**(n) that from a long way off took like flies."**
This impossible collection of kinds of animals is so funny to us less because these kinds of animals are all that funny in themselves than because this ridiculous way of categorizing things violates all our sense of order, indeed of the order of things.
We all know when categories make sense and when they don't. Foucault wanted to see what it **is** "we all know," what that knowledge of how to form categories is, and how it would have been different in earlier times.
In **The Order of Things** he examines three major areas of the human sciences,
He looks at the structure of knowledge of a time, its way of establishing order. But he starts long before the existence of the human sciences, and examines the development of the fields known in the 17th and 18th centuries as
## What marks the shift into the modern world?
## Before the 18th century, Man did not exist.
Of course human beings existed before that, and may even have looked at themselves as the center of the universe.
But they were central because God had made them that way. God was necessarily more central, and was the source of all knowledge. Human knowledge was limited, God's was infinite. In the 18th and 19th centuries, God lost his place as the firm center of all, who made all knowledge possible. Man was left with only himself at the center, as the source of knowing, and thus turned to intense examination of what this knowing being was.
The Human Sciences sprang up as old fields were reexamined with a new notion of Man as both the object and the subject of study.
But this modern age will not last forever.
## "Man is neither the oldest nor the most constant problem that has been posed for human knowledge."
As Nietzsche had heralded the death of God, Foucault now predicted a death of Man.
These huge new claims, that Man was an invention, and that he might die, catapulted Foucault
into the highly visible forefront of French thought.
As I said at the beginning, every intellectual of Foucault's generation had to see himself as coming **after Sartre.**
**What was Foucault challenging?**
Sartre's famous dictum, "Existence precedes essence," established the idea that the essence, or meaning of things, was not predetermined by any outside force. Instead, meaning is constructed by **men**. (As Beauvoir would say, "Yes that's right. By men. That's the whole problem.") The world does not contain any transcendent meaning, we make up the meaning as we go along, filtering the world through language.
So far so good. Foucault built on these ideas, as did everyone else around him.
But the problem comes in with Sartre's notion of Existential freedom. **Because** no meaning is predetermined, each person is free to create his own meaning through his own actions. But that freedom itself is a given, something we either have to accept or try to deny or hide from. Any time we do not accept our essential freedom, we are acting in **bad faith**.
**Simone de Beauvoir (1908-1986) started to question whether the role of social conditions in limiting freedom might not be more severe than Sartre said it was. Later thinkers agreed with her questions and amplified this doubt.**
They started by resurrecting the work of **Ferdinand de Saussure** (1857-1913), a theorist in the emerging field of linguistics, who had been largely ignored until the 50's and 60's.
In any language, the relationship of **signifier** to **signified** is arbitrary.
The collection of sounds and letters that make up the word "horse" (the signifier) do not in themselves have any connection to the animal we see cantering about a field (the signified). A "horse" is called, around the world, "cheval" in French, "pferd" in German, "farasi" in Swahili, "hest" in Norwegian, "konj" in SerboCroatian, "ceffyl" in Welsh, "at" in Turkish, "caballo" in Spanish, and could just as easily be called a "glymph" in any of these languages (and it still would smell as sweet). The answers to how meaning works lies not in these sounds and letters, but in the whole system of language.
**Saussure looked at language ae a whole, to see how it worked, rather than focusing on the details of individual languages.**
Foucault wrote about such ideas most directly in his short, playful book on the painter Rene Magritte, "C'eci n'est pas une pipe" **(This Is Not a Pipe)**.
**"The picture of the pipe is saying, 'You see me so clearly that it would be ridiculous for me to arrange myself so as to write: This is a pipe. To be sure, words would draw me less adequately than I reprsent myself.' The text in turn prescribes, 'Take me for what I manifestly am—letters placed beside one another, arranged and shaped so as to facilitate reading, assure recognition, and open themselves to even the most stammering schoolboy. I am no more than the words you are now reading.' "**
##### Lévi-Strauss and the Structuralists believed that:
* Binary oppositions are paramount.
* The rules binding binary oppositions can best be studied by freezing time and looking at a single moment.
* The structure of language is the dominant one, and that people come into existence through language. Thus one is not "free" to think anything outside the rules of one's language.
So was Michel Foucault a Structuralist? Well, on the one hand, no: he was an historian, and was particularly interested in change over time.
But in other ways, yes. In examining change over time, he hardly avoided structure. His next book, **The Archaeology of Knowledge** , was an explanation of his own aims and methods.
He named his method Archaeology because of the idea of uncovering layers of civilization. He posits that stability in systems of thought and discourse could exist for relatively long periods, and then change could happen quite suddenly. **The Birth of the Clinic** , for instance, is centered on a change in medical thought and practice at the end of the eighteenth century.
But Foucault spends most, of that book discussing the medical system that had existed for quite a time earlier, and the clinical system that continues today.
##### Is Foucault a Marxist?
But let's go back to an earlier point, to another thinker who discerns systems that structure society. Sartre told us he was a Marxist. Foucault's whole generation was rebelling against Sartre. Were they therefore rebelling against Marx too'? Was Foucault a Marxist or an anti-Marxist'?
**1.)** An adhesion to Marx's vision of the future, the revolution of the proletariat, and the formation of a new, Marxist state.
**2.)** An analysis of history based on Marx's economic materialism. History seen as a progression from one economic system, one mode of production, to the next, with all of society and culture determined by the details of the economic structure.
Nearly every intellectual of Foucault's generation joined Communist party, embracing the Marxist revolutionary ideal. Structuralists also found Marx's historical analysis congenial because it deemphasized the power of the individual, whom it saw as created by the dominant ideology of the day, which was itself created by the economic system. However, where Marx would claim the economic structure as dominant above all others, the Structuralists would have given language the greater dominance.
Michel Foucault joined the Communist Party later than most of his friends, and dropped out earlier (he was probably an official party member from 1950 to 1953).
Foucault didn't believe in economics as the basis for history. In **Archaeology** , discourse is the source,
Foucault also has a very specific meaning: writings in an area of technical knowledge—that is, areas in which there are specialists, specialized or technical knowledge, and specialized or technical vocabulary.
Each era will define its own discourses, and these definitions may vary radically over time. Take the difference between the field named "Natural History" and the field named "Biology."
For instance, the discourse on madness, produced by psychiatrists, psychologists, social workers and other Experts define the roles of craziness, and thus also the roles of normalcy that we all take on.
Foucault's model of history shifted after rereading Nietzsche's **Genealogy of Morals**.
**Friedrich Nietzsche** (1844-1900) was a deep and abiding influence on Foucault, who was particularly interested in Nietzsche's rejection of the notions of rational man and absolute truth, and his founding of history in irrationalityand accident.
From the layered model suggested by the term "archaeology," Foucault moved to what he would call "genealogy," which he conceived as a series of infinitely proliferating branches. He began to stress that many branches led nowhere, and that looking for a logic to the progression was misguided.
"To follow the complex course of descent is to identify the accidents, the errors, the false appraisals, and the faulty calculations that gave birth to those things that continue to exist and have value for us; it is to discover that truth or being do not lie at the root of what we know and what we are, but the exteriority of accidents."
Traditional history's search for origins in great moral truths is entirely misguided; everything is subject to history's disintegrating gaze. There are no absolutes.
"We belive that feelings are immutable, but every sentiment, particularly the noblest and most disinterested, has a history. We believe, in any event, that the body obeys the exclusive laws of physiology and that it escapes the influence of history, but this too is false.
Where was Foucault in all this uproar?
#### In Tunisia actually.
From 1954 on, Foucauit had taken a series of teaching jobs away from France – in Sweden, Poland, and Germany. In 1960 he returned to France to teach philosophy and psychology at the University of Clermont-Ferrand.
He may have missed the May student revolt in Paris, but Tunisia had its own student protest. Communist students rebelled against the repressive, anti-Communist, pro-American government that was trying to modernize Tunisia as rapidly as possible. These protests, unlike those in France, were life-and-death affairs. Students regularly received jail sentences of eight, ten, fourteen years.
When Foucault returned to France in late '68, he was ready for political action. He was named to head the philosophy department in a new campus of the University of Paris. He chose the most radical philosophers he could think of, and tried to hold his whirlwind of a department together until '70.
Then he got one of the most prestigious appointments in the French intellectual world: he was elected to the College de France. The only duties were to give a series of public lectures on his work-inprogress each year.
He used the freedom and prestige of this position to become politically active in a way that merged his politics and his scholarship.
Together, Daniel Detert and Foucault started a group to investigate and protest prison conditions. But Foucault was also working on a new version of the intellectual as protester.
Sartre had formed the old model:
bringing his philosophy to bear on important political and moral issues.
Foucault wanted the intellectual to be far less the center of attention. He knew his prestige could get reporters and TV cameras to the prisons, and then he wanted to
In '71 and '72 there were a series of prison riots in France. Foucault helped prisoners publish the details of the excessively harsh conditions of their lives.
Foucault was now hard at work researching the history of prisons. Together with his research group of graduate students, he published a collection of documents on a French murder case of 1835. **I, Pierre Riviere, having Slaughtered my mother, my sieter, and my brother...: A Case of Parricide in the 19th Century** contains all the court documents, including a most extraordinary confession, along with brief essays by Foucault and his students in the seminar. Many of the documents address the question of whether Pierre Riviere was crazy, and thus form a bridge between Foucault's work on madness, and his next work.
Foucault's next book ( **Diecipline and punish** ) moves away from **Archaeology's** abstract Structuralism, and tells a tale of power relations and oppression. His interest in prisons becomes an inquiry into the origins of prisons as a form of punishment. In general his focus will now be on discourse's role in power relations, and how the seeming abstractions of discourse have very concrete material effects on people's bodies.
**Before:**
2 March 1757
Damiens the regicide was condemned "to make the amende honorable before the main door of the Church of Paris, conveyed in a cart, wearing nothing but a shirt, holding a torch of burning wax weighing two pounds, then to the Place de Greve, where, on a scaffold that will be erected there, the flesh will be torn from his breasts, arms, thighs and calves with red hot pincers, his right hand, holding the knife with which he committed the said parricide, burnt with sulphur, and, on those places where the flesh will be torn away, poured molten lead, boiling oil, burning resin, wax and sulphur melted together and then his body drawn and quartered by four horses and his limbs and body consumed by fire, reduced to ashes, and his ashes thrown to the winds."
(Now I know that sounds gross enough, but the story told by eyewitnesses is far messier. It turns out to be not at all easy to tear flesh off a body with red-hot pincers. The horses which were supposed to pull his body apart by the limbs could not do so, never having had a chance to practice. The executioner's men had to cut the body to pieces, but Damiens' limbless body was still alive when it was thrown on the fire. Ooh, I know, gross, yucchh, did I have to tell you all this? The point is that the intensity of your reaction shows how far we have moved away from the culture that thought this appropriate punishment.)
**After:**
1837
Léon Faucher sets up a schedule for a prison in Paris: "The prisoners' day will begin at six in the morning in winter and at five in summer. They will work for nine hours a day throughout the year. Two hours a day will be devoted to instruction. Work and the day will end at nine o'clock in winter and at eight in summer.
"Rising. At the first drum-roll, the prisoners must rise and dress in silence, as the supervisor opens the cell doors. At the second drum-roll, they must be dressed and make their beds. At the third, they must line up and proceed to the chapel for morning prayer. There is a five-minute interval between each drum roll."
And on and on, so that every second is carefully planned.
No, these two punishments do not apply to the same crime or to the same kind of criminal. But each is the epitome of a method of punishment, and one seems very familiar, while the other is extremely foreign. So what caused the change? You could look at it as the birth of modern culture, or you could say that society had simply become more humane in the intervening years.
Or you could, as Foucault does, look at it as a change in the systematic use of power and authority in a society, and note that the second punishment might not indicate a lesser use of power. Careful control of every aspect of a life can represent a more complete exercise of power than the massive display of a death.
When we do execute someone now, we take care that it be quick and painless.
**Sure, society might kill people. but it wouldn't intentionally cause**
Before, pain was very much a normal part, perhaps the definition, of punishment.
Torture was a crucial part of the trial, & torture during the trial was also part of the punishment.
What? How could the punishment begin before the trial was over? The guy wasn't even guilty yet!
Guilt wasn't viewed then as all or nothing. People weren't simply innocent or guilty, and they certainly weren't innocent until proven guilty. A little proof made a man a little guilty, which might justify a little torture to get a little more evidence. One could not be the object of suspicion and be completely innocent.
After the trial was over, the element of public display was added. Any criminal was a threat to the authority of the king, and the full public regalia of the king's power could be used in a display of vengeance and of order restored.
But during the 18th century, just as philosophers were deciding that the desire to cause pain was not a seemly one for governments, the crowds that came to the spectacles of torture and death became more and more unruly. Something had to be done.
Now we have to switch the scene to outside the penal system, where, meanwhile, a new science of changing—engineering really—the individual develops in the army, schools, hospitals, madhouses, poorhouses, and factories.
A place for everyone, and everyone in his place. Where someone is indicates who and what he is, as in the wards here, or in schools where the best student moves to the head of the class.
8 to 8:20 will be reading. 8:20 to 8:40, handwriting. 8:40 to 9, spelling; and at 9 there will be a test. Recess is from 9:30 to 9:45, and during that time you will all go outside and you will **play.**
## REPETITIVE EXERCISES.
Must be both standardized and individualized according to rate of progress. Sufficient repetition creates automatic reactions to stimuli...
Backs straight, hands held high, fingers curved. C. E. G. C. G. E. C. Again, and again, and again. No, Josie, you are not lifting your fingers high enough. Do the exercise 20 more times.
That is, a continual analysis of whether the disciplined one deviates in any way from normality. Laws are traditionally set out only in negative terms. They put limits on behavior and decide what is unacceptable. But laws rarely talk about what behavior is desired. As a form of power, the law prevents, but does not specify. Disciplinary power is very different: it not only punishes, it rewards. It gives gold stars for good behavior. And the tendency is for that which transgresses its dictates to be defined not only as bad but as abnormal. It is a more subtle use of power that works on the transgressor from the inside, and consolidates the ranks of the "normal" against all others.
Nowhere is the institutionalized use of a concept of normality used as a technique more fully than in a madhouse. Today's madhouses are a series of gradated wards through which the inmate can move only by good, appropriate, sane behavior, as defined by the authorities of the institution.
While Discipline was being developed in all these different modes, Punishment was changing as well.
The system centered on pain and spectacle was coming under attack from social theorists, but more important, the spectacles were getting out of hand, becoming a site for political unrest and riots (like the Rodney King riots), and, especially after the French Revolution, great pains were taken to avoid political unrest and riots.
An entire system of carefully articulated and gradated punishments became reduced to a single punishment for all crimes: imprisonment. We are so used to this idea today, it is hard to imagine it as new. But prisons had not been used for punishment, they were simply meant for holding those whose trials were pending, and detaining debtors until they paid off their debts. Many people did not understand the new notion.
These criticisms were heard from the beginning, and they have been heard ever since.
If the prison does succeed in remaking the individual through this process, what kind of person will be made?
A docile worker who does as ordered without question. An automaton, the perfect fodder for the Capitalist factory.
And what about the ones the prison doesn't remake?
They come back again and again. Everyone knows that prisons make recidivists.
But suppose we take as a premise that if prisons have always had a large number of return inmates, perhaps this very fact is of some advantage to society. What advantage could there possibly be?
Well, the people who become devoted to a life of crime might otherwise be causing worse problems. They might, for instance, go into politics. The prisons are full of petty thieves who steal, again and again, from someone most likely as poor as themselves. Without the prison system as an education in this life, some of these people might generalize about their problems, and theorize on the validity of the very notion of private property. Some of them might organize unions, or riots, or political parties. Instead, those who will not accept the prevailing ideology are systematically channeled into a life story that every penologist knows by heart: the hopeless recidivist, the permanent delinquent.
Franee in the 19th century and Nevada today are special cases, or are they? The police always decide which prostitutes to arrest, and which to leave alone. They know who has been in prison, and why. They determine the conditions under which prostitution operates, and in many perhaps most cases, paying the police off is the tax a prostitute pays on her tax-free income.
Prostitution is potentially a rebellion against woman's economic, social, and sexual roles. As it mostly works out, however, prostitution is a system run very strictly by men, for men. Female prostitutes are subject to brutal male dominance at every turn.
(Whoa. Did Mr. Foucault say all that? Almost. Almost all of it. He says very clearly that the whole business of prostitution is a direct profit to the state. He didn't quite get around to saying that this potential threat to gender roles is contained by an overemphasis on gender roles. But I'm sure he was just about to. After all, his next book is the one where he really does look at women's issues.)
## THE REPRESSIVE HYPOTHESIS
Foucault identifies a conventional "enlightened" view of sexuality:
Publicly they were superprudes, pretended sex didn't exist, that people didn't have bodies. This was part, by the way, of their campaign against women. They taught the "proper" women that sex wasn't any fun, and that they should think of something else, like cleaning the kitchen, when their husbands did want to try to procreate.
So what we've needed since then is to be able to talk about sex openly—that's the only way to cure the sickness. Papa Freud was the first person to explain all this, and ever since we've been trying as hard as we can to be honest and open and healthy about sex, to throw away the evil restrictions of the dirty-minded men who control the world. Every time we talk about sex we are heroically throwing off our chains, and the sexual revolution is the first step towards any other revolution.
But once again, Foucault claims there is something wrong with this picture that we are all so ready to accept.
"Briefly, my aim is to examine the case of a society which has been loudly castigating itself for its hypocrisy for more than a century, which speaks verbosely of its own silence, takes great pains to relate in detail the things it does not say, denounces the powers it exercises, and promises to liberate itself from the very laws that have made it function."
He does not doubt that in "everyday speech," talk about sex was restricted. What he primarily maintains is that discourses about sex proliferated. Suddenly sex became an object of scientific study, and of careful regulation by many institutions—schools, barracks, prisons, hospitals, and madhouses, among others. All of these discourses are part of the major Western procedure for producing the truth of sex, for defining sex and its cultural meanings, which he calls a scientia sexualis.
Scientific discourse on human sexuality lagged far behind what was known about plant and animal reproduction. Two distinct ways of understanding sex existed simultaneously: a biology of reproduction, which developed in parallel with the other sciences, and a medicine of sexuality, which diverged from all other science, went nowhere, nursed bizarre fears, and was distinctly non-rational.
A concrete example of the strangeness of the scientia sexualis is Charcot's work at Salpetriere, the center of French treatment of hysteria in the late 19th century, where Freud got his training. The primarily female patients were put on display for visitors. As Charcot explained each case, the patient would "spontaneously" strike odd, often very sexual poses, which Charcot would describe as "passionate" symptoms of hysteria. A patient's attack could be provoked by a doctor's touching "the region of her ovaries" with a "baton". Perpetually incited to symbolic sexual display, the patients were whisked out of sight if their poses got too specific.
Freud greatly admired all this, and did not completely leave it behind.
These are just two examples of the medical, scientific knowledge of sex, that already looks to us not just misguided and wrong, but absolutely crazy and perverse. How will our own sexual science look in fifty years?
Such a science of sex developed as a form of power—a psychiatrist somehow has power over a patient simply by sitting and listening.
"The new methods of power are not ensured by right but by technique, not by law but by normalization, not by punishment but by control, methods that are employed on all levels and in forms that go beyond the state and its apparatus."
As we began to see in **Discipline & Punish,** right and wrong, good and sin, get translated, but only too directly, into normal and pathological.
This new form of power is much more subtle than our traditional notion. It is thus much easier to overlook, and much harder to resist.
"In the Renaissance, sodomy was a category of forbidden acts... The 19th century homosexual became a personage, a past, a case history, and a childhood, in addition to being a type of life, a life form, and a morphology, with an indiscreet anatomy and possibly a mysterious physiology.... The sodomite had been a temporary aberration; the homosexual was now a species." From this idea we get this book's most striking claim—that the homosexual and homosexuality were invented in the 19th century.
**LOCALIZED POWER**. Power is not hierarchical, flowing from the top down, but everywhere local. The president cannot dictate family values (though some of them do try) instead, patterns of power established within families interact with patterns of power in institutions and throughout the social body.
But this idea of power is objected to by many scholars, particularly some historians. They insist that we have to look for "agency." Who are the people exercising this power, creating this system of power? Why are they doing it? Grand schemes are all very well, but history always boils down to individual people doing things. Foucault describes some enormous conspiracy theory, but never tells us who the conspirators could possibly be, or what they got out of it.
I believe this is a very fundamental misinterpretation, but Foucault makes it easy to misinterpret.
That certainly sounds like someone is carefully plotting and scheming to gain control of people's sexuality.
"But this does not mean that it results from the choice or decision of an individual subject; let us not look for the head-quarters that presides over its rationality; neither the cast which governs; nor the groups which control the state apparatus, nor those who make the most important economic decisions direct the entire network of power that functions in a society (and makes it function)."
oucault does not in any way explain his way out of this paradox; he merely asserts it. He is not interested in the individual and individual will. He would say that our society became focused on the individual at the same time that it became a normalizing society, and perhaps the individual, individual rights, is the alibi of power.
**If there is no one in charge of power, no one to blame, is there any way to resist power?**
Yes, but resistance does not exist outside of the system of power relations. lt is, instead, inherently part of the relation. In modern-day normalizing power relations, this tends very much to isolate and individuate resistance into a series of "special cases" which do not allow generalization.
To understand this notion, think of the patients in the back ward of a modern-day mental institution. These people's lives are very tightly controlled. Can they resist? Of course, and they do all the time. But does anyone they see acknowledge that resistance as a rebellion against a power system that has defined them as abnormal and taken control of their lives, that lets them go only if they will live up to society's idea of normality?
Doctors and nurses will hear all of these statements not as political resistance, but as "uncooperative behavior," part of what justifies locking these people up in the first place. Only acceptance of the power system and its terms will get them defined as normal, and thus get them released.
But Foucault did not see the system as always operating the same way everywhere. The scientia sexualis might reign supreme in Europe and the U.S., but Foucault sees a very different procedure, an ars erotica, in China, Japan, India, Rome, the Arab-Muslim societies.
Foucault turns to such alternatives to the scientia sexualis in his next few years. The first volume of **The History of Sexuality** talks mostly about the last two centuries. Volumes II and III, **The Use of Pleasure** and **The Care of the Self** are quite unexpectedly about Greece and Rome.
There has also been some controversy surounding Foucault's involvement in sadomasochism. He enjoyed the leather-bar scene In San Francisco, where some clubs specialize in ritualized forms of sadomasochism known to the community simply as S/M.
Foucault did not believe that involvement in S/M revealed deep subconscious tendencies towards cruelty and violence. Instead he saw S/M as a game, a way of playing and experimenting with the nature of power.
"On this point the S/M game is very interesting because it is a strategic relation, but it is always fluid. Of course there are roles, but everybody knows very well that those roles can be reversed. Sometimes the scene begins with the master and slave, and at the end the slave has become the master. It is an acting out of power structures by a strategic game that is able to give sexual pleasure or bodily pleasure."
S/M was about pleasure for Foucault, but pleasure and politics were never fully separable. This concept of play and transformation helps him solve the trap of being always inside power relations. Scientific discourse may have defined us in terms of our sexuality, and we may be unable to unthink these definitions, to step outside them. Our world may be a back ward we cannot escape. But that does not mean we are simply powerless.
Large political parties and organizations for reform do more to stabilize power relations than to change them. Play, whether sexual or overtly political, challenges society's rules on a deeper and less predictable level, opening up greater possibilities of change.
In 1971 Foucault reflected on the political turmoil of the '60a in terms that reflected his personal life, his politics, and his scholarly work, bringing all these strands together: "We must see our rituals for what they are: completely arbitrary things, tired of games and irony, it is good to be dirty and bearded, to have long hair, to look like a girl when one is a boy (and vice versa); one must put 'in play.' show up, transform, and reverse the systems which quietly order us about. As far as I am concerned, that is what I try to do in my work."
### Further Reading
**By Foucault:**
_Mental Illness and Psychology_. Alan Sheridan, trans. New York: Harper & Row, 1976. In French: _Maladie mentale et personnalité_ , 1954.
_Madness and Civilization: A History of Insanity in the Age of Reason_. Richard Howard, trans. New York: Random House, 1965. Abridged version of _Folie et déraison_ , 1961.
_The Birth of the Clinic: An Archaeology of Medical Perception_. A. M. Sheridan Smith, trans. New York: Pantheon, 1973. In French: _Naissance de la clinique: une archéologie du regard médical_ , 1963.
_Death and the Labyrinth: The World of Raymond Roussel_. Charles Raus, trans. Garden City: Doubleday, 1986. In French: _Raymond Roussel_ , 1963.
_The Order of Things: An Archaeology of the Human Sciences_. Alan Sheridan, trans. New York: Pantheon, 1970. In French: Les Mots et les choses: _un archéologie des sciences humaines_ , 1966.
_The Archaeology of Knowledge_. A. M. Sheridan Smith, trans. New York: Pantheon, 1972. In French: _L'archéologie du savior_ , 1969.
_This is Not a Pipe_. James Harkness, trans. Berkeley: University of California Press, 1981. In French: _Ceci n'est pas une pipe: deux lettres et quatre dessins de René Magritte_ , 1973.
_I, Pierre Riviére, having slaughtered my mother, my sister, and my brother ... : A Case of Parricide in the 19th Century_. Frank Jellinek, trans. Lincoln: University of Nebraska Press, 1975. In French: _Moi, Pierre Rivière, ayant égorgé ma mère, ma soeur et mon frère ... : un cas de parricide au XIXe siècle_ , 1973.
_Discipline and Punish: The Birth of the Prison._ Alan Sheridan, trans. New York: Pantheon, 1977. In French: _Surveillir et punir: naissance de la prison_ , 1975.
_The History of Sexuality, Volume 1: An Introduction_. Robert Hurley, trans. New York: Pantheon, 1977. In French: _Histoire de la sexualité, 1: la volonté de savoir_ , 1976.
Language, Counter-Memory, Practice: _Selected Essays and Interviews_. Donald F. Bouchard and Sherry Simon, trans. Ithaca, N.Y.: Cornell University Press, 1977.
_Power/Knowledge: Selected Interviews and Other Writings 1972-1977_. Colin Gordon, et al., trans. New York: Pantheon, 1980.
_The Use of Pleasure, vol. 2 of The History of Sexuality_. Robert Hurley, trans. New York: Pantheon, 1985. In French: _Histoire de la sexualité, II: l'usage des plaisirs_ , 1984.
_The Care of the Self, vol. 3 of The History of Sexuality_. Robert Hurley, trans. New York: Pantheon, 1986. In French: _Histoire de la sexualité, III: le souci de soi_ , 1984.
_The Foucault Reader_. Paul Rabinow, ed. New York: Pantheon, 1984.
_The Final Foucault_. James Bernauer and David Rasmussen, eds. Cambridge, Mass.: MIT Press, 1987.
_Selections. Politics, Philosophy, Culture: Interviews and Other Writings_ , 1977-1984. Lawrence D. Kritzman, ed.; Alan Sheridan et al., trans. New York: Routledge, 1988 .
_Foucault Live: Interviews_ , 1966-84. Sylvère Lotringer, ed.; John Johnston, trans. New York: Semiotext(e), 1989.
_Remarks on Marx: Conversations with Duccio Trombadori_. R. James Goldstein and James Cascaito, eds. New York: Semiotext(e), 1991.
**About Foucault:**
Baudrillard, Jean. _Forget Foucault_. New York: Semiotext(e), 1987.
Cooper, Barry. _Michel Foucault, an Introduction to the Study of his Thought_. New York: Edwin Mellen Press, 1981.
Cousins, Mark. _Michel Foucault_. New York: St. Martin's Press, 1984.
Deleuze, Gilles. _Foucault_. Sean Hand, trans. Minneapolis: University of Minnesota Press, 1988.
Dreyfus, Hubert L. and Paul Rabinow. _Michel Foucault: Beyond Structuralism and Hermeneutics._ With an afterword by and an interview with Michel Foucault. 2nd ed. Chicago: University of Chicago Press, 1983.
During, Simon. _Foucault and Literature:_ _Towards a Genealogy of Writing_. London: Routledge, 1992.
McNay, Lois. _Foucault and Feminism: Power, Gender and the Self._ Cambridge: Polity Press, 1992.
Poster, Mark. F _oucault, Marxism and History: Mode of Production versus Mode of Information._ Cambridge: Polity Press, 1984.
Sawicki, Jana, _Disciplining Foucault: Feminism, Power, and the Body._ New York: Routledge, 1991.
Sheridan, Alan. _Michel Foucault: The Will to Truth._ London: Tavistock, 1980.
Shumway, David R. _Michel Foucault._ Charlottesville: University Press of Virginia, 1992.
Smart, Barry, _Michel Foucault._ London: Routledge, 1988.
**Biographies:**
Eribon, Didier. _Michel Foucault._ Betsy Wing, trans. Cambridge, Mass.: Harvard University Press, 1991. A comprehensive biography.
Miller, James. _The Passion of Michel Foucault._ New York: Simon & Schuster, 1993. A biography focusing on the interaction of Foucault's thought and his sexuality.
**Collections of Essays:**
Arac, Jonathan, ed. _After Foucault: Humanistic Knowledge, Postmodern Challenges._ New Brunswick: Rutgers University Press, 1991.
Caputo, John and Mark Yount, eds. _Foucault and the Critique of Institutions._ University Park, Pa.: Pennsylvania State University Press, 1993.
Diamond, Irene, and Lee Quinby, eds. _Feminism & Foucault: Reflections on Resistance._ Baston: Northeastern University Press, 1988.
Gane, Mike and Terry Johnson, eds. _Foucault's New Domains._ London: Routledge, 1993.
Hoy, David Couzens, ed. _Foucault: A Critical Reader._ Oxford: B. Blackwell, 1986.
Marris, Meaghan and Paul Patton, eds. _Michel Foucault: Power, Truth, Strategy._ Sydney, Australia: Feral Publications, 1979.
Ramazanoglu, Caroline, ed. Up Against _Foucault: Explorations of Some Tensions between Foucault and Feminism._ Landon: Routledge, 1993.
### Index
abnormality, and normality, distinguished, -, , , -
absolute truth, , -
AIDS,
Archaeology of Knowledge, The (Foucault), -
ars erotica,
autopsy, -, -
bad faith,
Barthes, Roland,
Beauvoir, Simone de, , -
The Second Sex,
Bentham, Jeremy,
Bichat, Marie-Francois-Xavier,
binary oppositions, -
biology,
Birth of the Clinic, The (Naissance de la clinique) (Foucault), , -,
body/mind/soul question, -,
Borges, Jorge Luis,
capitalism,
Care of the Self, The (Foucault),
catatonia,
categories,
categorization of people, -
"C'est n'est pas une pipe" (Foucault),
Charcot, Jean Martin,
clinics, -, -
Collége de France,
Communist Party, ,
confinement, -
of criminals,
history of, -
of the leprous, -
of the mad, ,-,
conspiracy theory of history,
control of activity, ,
criminals
confinement of,
definition of, , ,
reform of, -
culture, human,
Damiens (regicide), -
Darwin, Charles,
death, -
Defert, Daniel, ,
discipline, -
Discipline and Punish (Foucault), -,
discourse, -, 136-137
disease, classification of,
doctors
as moral authorities,
and patients, -
training of, -
Ecole Normale Supérieure, -
economics, , -
Erasmus, The Praise of Folly (Moriae Encomium), 36
erotic arts,
exclusion, , -
executions, -, ,
existential freedom, -
experts, ,
Faucher, Léon,
Fliess, Dr.,
force, physical, -,
Foucault, Michel, -
biography, -
homosexuality of, -
schooling, -
suicide attempt,
teaching positions, , -
freedom, existential, -
French academic system, -
French intellectuals, , ,
French Revolution, -, -
Freud, Sigmund, , , ,
games, -
Gaze, the, , , -
gender roles,
genealogy, -
God,
Death of,
guilt/innocence,
hierarchies,
historical thinking, -, -
History of Sexuality (Foucault), -
homosexuality, ,
hospitals, , , -
See also madhouses
human sciences, , , -
hysteria, -,
illness, , , ,
imprisonment, as punishment, -
See also confinement; prisons
individuals, in history, -
intellectuals, French, , ,
internalization,
judgments, normalizing,
knowledge, -, , -, ,
Lacan, Jacques,
language, , -, -
laws,
lepers, -
Lévi-Strauss, Claude, , -
linguistics, ,
madhouses, -,
madmen
confinement of, , -,
liberation of, -
madness
as abnormal, ,
definitions and categories of, -, -
in literature and imagination, -
and reason, contrasted, -
scientific study of, -
treatment of, historically, , -
Madness and Civilization (Folie et déraison)
(Foucault), , -
Magritte, René, "C'est n'est pas une pipe," 93
man
concept of, -
Death of, -
Maoism,
MarX, Karl, -
Marxism,
masturbation,
medicine, . See also doctors; hospitals
middle-class morality,
Mirabeau, Count de, -
moral authority, -
morality,
Nietzsche, Friedrich, ,
Genealogy of Morals, 102
normality/abnormality, distinguishing between, -, , , -
normalizing judgments,
nosology,
Order of Things, The (Les Mots et les choses) (Foucault), -
pain, role of, in punishment, -
Panopticon, ,
patients, -, ,
physical force, -,
Pinel, Philippe, , -
play, -
politics, , -
poor, confinement of, -
power, -, -, -
and normal/abnormal categories,
and punishment, ,
prisons, , -, , - . See also imprisonment
prostitutes, -,
psychiatrists,
psychology,
punishment
history of, -, -
public, ,
rational man,
reason, and madness, contrasted, -
recidivism, -
repetitive exercises,
repression, -
resistance, -,
riots,
Riviére, Pierre, ,
Rorschach tests,
Sade, Marquis de,
sadomasochism,
Salpetriere clinic,
Sartre, Jean-Paul, , -, ,
Les Mots ("Worde"),
Saussure, Ferdinand de, ,
science, -. See also human sciences
scientia sexualis, 136-139,
secrets,
sexuality
discourse On, -
illicit,
perverted, ,
repressed, -
science of, -,
sexual revolution,
Shakespeare, William, King Lear, -
Ship of Fools allegory, -
sick, confinement of,
signifier and signified,
sixties politics, -,
social sciences. See human sciences
sodomy,
spatialization,
specialists, ,
structuralism, -
student revolt of May 1968,
timetables,
torture,
trials, -
Tuke, Samuel, -,
truth, absolute, , -
Tunisia, -
universities, -
University of Paris,
Use of Pleasure, The (Foucault),
Victorian sexuality,
war,
women
control of, -,
and hysteria, -,
|
<filename>src/git/commit/parseCommitsFromLog.ts
import type { GitCommit } from '../types';
import { parseCommitFromLogEntry } from './parseCommitFromLogEntry';
export function parseCommitsFromLog(commitLog: string): GitCommit[] {
if (!commitLog) {
return [];
}
return commitLog
.split('\n')
.filter((logEntry) => logEntry) // filter out empty entries
.map((logEntry) => parseCommitFromLogEntry(logEntry));
}
|
pub(crate) fn generate(
mut writer: impl std::io::Write,
type_name: &str,
generics: super::Generics<'_>,
vis: &str,
fields: &[super::Property<'_>],
is_watch: bool,
operation_feature: Option<&str>,
map_namespace: &impl crate::MapNamespace,
) -> Result<(), crate::Error> {
let local = crate::map_namespace_local_to_string(map_namespace)?;
let type_generics_impl = generics.type_part.map(|part| format!("<{part}>")).unwrap_or_default();
let type_generics_type = generics.type_part.map(|part| format!("<{part}>")).unwrap_or_default();
let type_generics_where = generics.where_part.map(|part| format!(" where {part}")).unwrap_or_default();
let operation_feature_attribute: std::borrow::Cow<'static, str> =
operation_feature.map_or("".into(), |operation_feature| format!("#[cfg(feature = {operation_feature:?})]\n").into());
let mut fields_append_pair = String::new();
for super::Property { name, field_name, field_type_name, .. } in fields {
use std::fmt::Write;
writeln!(fields_append_pair, " if let Some(value) = self.{field_name} {{")?;
match &**field_type_name {
"Option<&'a str>" => writeln!(fields_append_pair, r#" __query_pairs.append_pair({name:?}, value);"#)?,
"Option<bool>" => writeln!(fields_append_pair, r#" __query_pairs.append_pair({name:?}, if value {{ "true" }} else {{ "false" }});"#)?,
_ => writeln!(fields_append_pair, r#" __query_pairs.append_pair({name:?}, &value.to_string());"#)?,
}
writeln!(fields_append_pair, " }}")?;
}
let watch_append_pair =
if is_watch {
" __query_pairs.append_pair(\"watch\", \"true\");\n"
} else {
""
};
writeln!(
writer,
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/query_string_optional.rs")),
local = local,
type_name = type_name,
type_generics_impl = type_generics_impl,
type_generics_type = type_generics_type,
type_generics_where = type_generics_where,
operation_feature_attribute = operation_feature_attribute,
vis = vis,
fields_append_pair = fields_append_pair,
watch_append_pair = watch_append_pair,
)?;
Ok(())
}
|
Justice Department lawyers representing President Trump Donald John TrumpHouse committee believes it has evidence Trump requested putting ally in charge of Cohen probe: report Vietnamese airline takes steps to open flights to US on sidelines of Trump-Kim summit Manafort's attorneys say he should get less than 10 years in prison MORE say the Trump Organization's decision to walk away from its Trump SoHo hotel supports the argument for dismissing a lawsuit alleging the president is in violation of the Emoluments Clause of the Constitution.
In a letter to U.S. District Judge George Daniels in Manhattan, N.Y., on Friday, the Justice Department said that the exit from the SoHo location "undermines" a lawsuit from competing hotels and restaurants and watchdog groups arguing that Trump's business empire, including his hotels, amount to an illegal receipt of money from foreign governments, Reuters reported.
“This development undermines the hospitality plaintiffs’ reliance on alleged competition with the Trump SoHo to demonstrate standing,” the letter reportedly reads.
ADVERTISEMENT
The lawsuit claims that Trump is in violation of the Emoluments Clause, which prohibits elected leaders from receiving gifts or benefits from foreign officials, because he retains ownership of his businesses while in the White House.
Trump has passed control of day-to-day operations of the company to his two elder sons, Donald Trump Jr. and Eric Trump. Still, he has long faced criticism for not fully divesting from his business empire after he took office in January, particularly his hotel in Washington, D.C.
The Justice Department has countered that the plaintiffs in the lawsuit cannot prove damages from the allegations. |
<filename>nautobot/extras/tests/dummy_jobs/test_object_var_required.py<gh_stars>0
from nautobot.extras.jobs import Job, ObjectVar
from nautobot.dcim.models import Region
class TestRequiredObjectVar(Job):
region = ObjectVar(
description="Region (required)",
model=Region,
required=True,
)
def run(self, data, commit):
self.log_info(obj=data["region"], message="The Region that the user provided.")
return "Nice Region!"
|
<filename>lib/prettyPrint/forObjects/prettyPrintObject.ts<gh_stars>10-100
import { formatNestedArray } from '../utils/formatNestedArray';
import { maximumFormattingDepth } from '../../constants/maximumFormattingDepth';
import { prepareSimple } from '../utils/prepareSimple';
import { prettyPrint } from '../typeAware/prettyPrint';
const prettyPrintObject = function (object: object, depth = 0): string {
if (Object.keys(object).length === 0) {
return '{}';
}
const content: string[][] = [];
for (const [ key, value ] of Object.entries(object)) {
content.push(prepareSimple(
`${key}: ${prettyPrint(value, depth + 1)}`,
depth
));
}
if (depth >= maximumFormattingDepth) {
return formatNestedArray`{ ${content} }`;
}
return formatNestedArray`
{
${content}
}
`;
};
export {
prettyPrintObject
};
|
<reponame>CodingSquire/go-courses
package main
import "fmt"
const size uint = 3
func main() {
// инициализируется значениями по-умолчанию
var a1 [3]int
fmt.Println("массив", a1, "длина", len(a1))
return
// можно использовать типизированную беззнаковую константу
var a2 [2 * size]bool
fmt.Println(a2, "длина", len(a2))
a3 := [...]int{1, 2, 3}
fmt.Println("длина при инициализации", a3, "длина", len(a3))
a3[1] = 12
fmt.Println("после изменения", a3)
// нельзя, проверка при компиляции
// a3[4] = 12
// invalid array index 4 (out of bounds for 3-element array)
var aa [3][3]int
aa[1][1] = 1
fmt.Println("массив массивов", aa)
}
|
Intercultural Conflict Mediation
Conflict mediation refers to the dialogue-based process by which a third person supports two or more parties, constructively managing their conflict. In North America and Europe, the term “conflict mediation” is usually associated with procedural principles that originate from the US-based “alternative dispute resolution” (ADR) movement. Originally, conflict mediation in the United States had been introduced as an alternative to court-based conflict resolution. Mediation was meant to produce results that were more sustainable and more satisfying for all concerned parties. From the 1980s onward, conflict mediation has increasingly been considered to be particularly suitable for the management of conflicts in intercultural settings; its inherent high procedural flexibility may help in adapting the concept to other cultural contexts, as well as taking cultural aspects of the parties concerned into consideration. The dialogue orientation of the tool was expected to give equal voices to all participants, balancing hidden power inequalities resulting from different cultural affiliations. This general and basic assumption has laid a very fruitful groundwork for the emergence of a highly diverse landscape of approaches to the idea of intercultural conflict mediation since the late 20th century. Researchers on intercultural communication (see also the separate Oxford Bibliographies in Communication article “Intercultural Communication”) and intercultural competence took mediation as a long-expected hands-on tool to finally manage problems resulting from interculturality. This transfer from an alternative to courts to a tool promoting intercultural understanding, however, will leave some gaps open for research, since the tool does not match perfectly: research on intercultural communication and intercultural competence has so far seen its main challenges in rather subtle irritations and everyday interactions instead of focusing on escalated disputes. Parallel to this, although numerous different notions of culture have existed in research for ages, academia concerning interculturality has started to include a wider variety of paradigms since the late 20th century, resulting in widely different notions of culture and its effects. Depending on what paradigm authors adhere to, they will produce widely different understandings on what intercultural conflict mediation is supposed to be. This article will illuminate the range of these understandings. It will also focus on concepts of mediation, taking single individuals into consideration and leaving aside the mediation of large ethnic groups as a different scenario to be located in international politics. |
/**
* <b>Title:</b> ParameterChangeEvent
* <p>
*
* <b>Description:</b> Any time a Parameter value is changed via the GUI editor
* JPanel, this event is triggered and recieved by all listeners
* <p>
*
* @author Steven W. Rock
* @created February 21, 2002
* @version 1.0
*/
public class ParameterChangeEvent extends EventObject {
/** Name of Parameter being changed. */
private String parameterName;
/** New value for the Parameter. */
private Object newValue;
/** Old value for the Parameter. */
private Object oldValue;
/**
* Constructor for the ParameterChangeEvent object.
*
* @param reference
* Object which created this event
* @param parameterName
* Name of Parameter being changed
* @param oldValue
* Old value for the Parameter
* @param newValue
* New value for the Parameter
*/
public ParameterChangeEvent(Object reference, String parameterName,
Object oldValue, Object newValue) {
super(reference);
this.parameterName = parameterName;
this.newValue = newValue;
this.oldValue = oldValue;
}
/**
* Gets the name of Parameter being changed.
*
* @return Name of Parameter being changed
*/
public String getParameterName() {
return parameterName;
}
/**
* Gets the new value for the Parameter.
*
* @return New value for the Parameter
*/
public Object getNewValue() {
return newValue;
}
/**
* Gets the old value for the Parameter.
*
* @return Old value for the Parameter
*/
public Object getOldValue() {
return oldValue;
}
/**
* Returns the Parameter Object that caused the Event to be fired.
*
* @return ParameterAPI
*/
public ParameterAPI getParameter() {
return (ParameterAPI) this.getSource();
}
} |
The imperial goatee on King Tutankhamun's golden burial mask is back in business after scientists reattached it with beeswax, according to the Egyptian Ministry of Antiquities.
The more than 3,300-year-old mask was damaged in August 2014 when the beard accidentally fell off during a routine cleaning. Staff workers at Cairo's Egyptian Museum mistakenly reattached it with epoxy glue, leaving scratch marks on the famous artifact after they used a spatula to wipe off the excess glue, Live Science reported in January.
But now, after a nine-week restoration, the mask has returned to public display at the museum, Antiquities Minister Mamdouh Eldamaty said at a news conference yesterday (Dec. 17) at the museum. [In Photos: The Life and Death of King Tut]
The restoration revealed newfound secrets about the mask, Eldamaty said. Researchers noticed a gold tube inside the royal beard, an intriguing structure that ancient Egyptians likely used to attach the beard to the rest of the mask, he said.
Officials transport the restored mask. Credit: Copyright Egyptian Ministry of Antiquities
What's more, ancient Egyptians also used beeswax to fasten the beard to the mask, a technique replicated by the researchers during the restoration, Eldamaty said in a statement on Facebook.
King Tut, who ruled Egypt from 1332 B.C. to 1323 B.C., has fascinated the public since British archaeologists Howard Carter and George Herbert discovered the boy king's nearly intact tomb in 1922. However, the beard on the funerary mask — a symbol that kings used to identify themselves to Osiris, the god of the underworld — was detached at the time it was found inside the tomb, according to National Geographic.
"The 2014 damage was exaggerated, since the beard was previously detached as the examination showed," said Friederike Fless, the president of the German Archaeological Institute in Cairo, one of the German and Egyptian bodies that cooperated in the restoration process, according to National Geographic.
The beard remained detached until 1946, when it was reconnected using a soft solder, National Geographic reported.
The researchers began the new restoration in October 2015, starting with a 3D scan to document the mask. Then, over a four-week period, they heated the metal mask and carefully removed the epoxy glue with wooden tools, National Geographic said.
Now that the mask is back on display, the scientists are preparing a scientific study that describes the entire restoration process, Eldamaty said in the statement.
Follow Laura Geggel on Twitter @LauraGeggel. Follow Live Science @livescience, Facebook & Google+. Original article on Live Science. |
Effect of Mineral Fertilization on the Essential Oil Composition of Tagetes patula L. from Bulgaria
Abstract The effect of mineral fertilization on the composition of the essential oil from the leaves and flowers of Tagetes patula from Bulgaria during the flowering period (July-September) was investigated by GC/MS. The highest oil yield was obtained from leaves in July for N4P2K4 (0.63%) and the basic components were piperitenone (29.4%) and piperitone (13.5%). The mineral fertilization had no effect on the oil yield from the flowers. Regardless of the variant, it was found that the flower oils in July were rich in caryophyllene oxide (12.0-48.4%) and piperitenone (3.0-7.0%), while the oil composition in September was different. |
/**
* @author Uma Shankar
*
* <pre>
* ======================================================================
*
* Write a function that takes in a Binary Search tree(BST) and returns a list of its branch sums
* ordered from leftmost branch sum to rightmost branch sum.
*
* <b>A branch sum is the sum of all the values in a Binary Tree branch, A Binary tree branch is a path
* of nodes in a tree that starts at the root node and ends at any leaf Node.<b>
*
* Example:
* 1
* / \
* 2 3
* / \ / \
* 4 5 6 7
* / \ /
* 8 9 10
* Sample Output :
* [15,16,18,10,11]
*
* 15 == 1+2+4+8
* 16 == 1+2+4+9
* 18 == 1+2+5+10
* 10 == 1+3+6
* 11 == 1+3+7
* ======================================================================
*
*/
public class BranchSum {
public static class BinaryTree {
int value;
BinaryTree left;
BinaryTree right;
BinaryTree(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
public static List<Integer> branchSums(BinaryTree root) {
List<Integer> result = new ArrayList<Integer>();
calculateBranchSum(root, 0, result);
return result;
}
public static void calculateBranchSum(BinaryTree tree, int runningSum, List<Integer> sums) {
if (tree == null)
return;
int newRunningSum = runningSum + tree.value;
if (tree.left == null && tree.right == null) {
sums.add(newRunningSum);
return;
}
calculateBranchSum(tree.left, newRunningSum, sums);
calculateBranchSum(tree.right, newRunningSum, sums);
}
} |
class AttachmentCategoriesContainer: CollapsibleContainer
{
protected ref map<int, ref Widget> m_inventory_slots;
protected EntityAI m_Entity;
void AttachmentCategoriesContainer( ContainerBase parent )
{
m_inventory_slots = new ref map<int, ref Widget>;
}
void SetEntity( EntityAI entity )
{
m_Entity = entity;
InitGhostSlots( entity );
( Container.Cast( m_Parent ) ).m_Body.Insert( this );
m_Parent.Refresh();
SetHeaderName( entity );
}
void SetHeaderName( EntityAI entity )
{
Header h = Header.Cast( m_Body.Get(0) );
h.SetName( entity.GetDisplayName() );
}
override void UpdateInterval()
{
if( m_Entity )
{
InitGhostSlots( m_Entity );
}
}
/*void SetLastActive()
{
Container cont = Container.Cast( m_Body[m_Body.Count() - 1] );
cont.SetActive( true );
}*/
void LoadAttachmentCategoriesIcon( IconsContainer items_cont, string icon_name, int slot_number )
{
ItemPreviewWidget item_preview = ItemPreviewWidget.Cast( items_cont.GetMainPanel().FindAnyWidget( "Icon"+ slot_number ) );
ImageWidget image_widget = ImageWidget.Cast( item_preview.FindAnyWidget( "GhostSlot" + slot_number ) );
image_widget.Show( true );
image_widget.LoadImageFile( 0, "set:dayz_inventory image:" + icon_name );
if( m_Body.Count() > ( slot_number + 2 ) )
{
ClosableContainer c = ClosableContainer.Cast( m_Body.Get( slot_number + 2 ) );
if( c.IsOpened() )
item_preview.FindAnyWidget( "RadialIcon" + slot_number ).Show( true );
else
item_preview.FindAnyWidget( "RadialIcon" + slot_number ).Show( false );
}
}
int GetAttachmentCategoriesCount( string config_path )
{
return GetGame().ConfigGetChildrenCount( config_path );
}
private IconsContainer GetIconsContainer()
{
AttachmentCategoriesIconsContainer items_cont;
if(m_Body.Count() == 1)
{
items_cont = new AttachmentCategoriesIconsContainer(this);
m_Body.Insert(items_cont);
}
else
{
items_cont = AttachmentCategoriesIconsContainer.Cast( m_Body.Get(1) );
}
return items_cont.GetIconsContainer();
}
string GetAttachmentCategory( string config_path_attachment_categories, int i )
{
string attachment_category;
GetGame().ConfigGetChildName(config_path_attachment_categories, i, attachment_category);
return attachment_category;
}
string GetIconName( string config_path_attachment_categories, string attachment_category )
{
string icon_path = config_path_attachment_categories+ " " + attachment_category + " icon";
string icon_name;
GetGame().ConfigGetText(icon_path, icon_name);
return icon_name;
}
void MouseClick( Widget w )
{
ClosableContainer c = ClosableContainer.Cast( m_Body.Get( w.GetUserID() + 2 ) );
if(c.IsOpened())
{
c.Close();
}
else
{
c.Open();
}
if(m_Body.Count() > ( w.GetUserID() + 2))
{
if(c.IsOpened())
w.GetParent().FindAnyWidget( "RadialIcon" + w.GetUserID() ).Show( true );
else
w.GetParent().FindAnyWidget( "RadialIcon" + w.GetUserID() ).Show( false );
}
}
void InitGhostSlots( EntityAI entity )
{
string type = entity.GetType();
string config_path_attachment_categories = "CfgVehicles " + type + " GUIInventoryAttachmentsProps";
int attachments_categories_count = GetAttachmentCategoriesCount( config_path_attachment_categories );
ref IconsContainer items_cont = GetIconsContainer();
for (int i = 0; i < attachments_categories_count; i++)
{
string attachment_category = GetAttachmentCategory( config_path_attachment_categories, i );
string icon_name = GetIconName( config_path_attachment_categories, attachment_category);
if(items_cont)
{
int slot_number = i;
ItemPreviewWidget item_preview = ItemPreviewWidget.Cast( items_cont.GetMainPanel().FindAnyWidget( "Icon"+ slot_number ) );
//WidgetEventHandler.GetInstance().RegisterOnDrag( item_preview.GetParent(), this, "OnIconDrag" );
ImageWidget image_widget = ImageWidget.Cast( item_preview.FindAnyWidget( "GhostSlot" + slot_number ) );
image_widget.Show( true );
image_widget.LoadImageFile( 0, "set:dayz_inventory image:" + icon_name );
if( m_Body.Count() > ( slot_number + 2 ) )
{
ClosableContainer c = ClosableContainer.Cast( m_Body.Get( slot_number + 2 ) );
if( c.IsOpened() )
item_preview.FindAnyWidget( "RadialIcon" + slot_number ).Show( true );
else
item_preview.FindAnyWidget( "RadialIcon" + slot_number ).Show( false );
}
WidgetEventHandler.GetInstance().RegisterOnMouseButtonDown( items_cont.GetMainPanel().FindAnyWidget( "PanelWidget"+i ), this, "MouseClick" );
WidgetEventHandler.GetInstance().RegisterOnMouseButtonDown( items_cont.GetMainPanel().FindAnyWidget( "GhostSlot"+i ), this, "MouseClick" );
items_cont.GetMainPanel().FindAnyWidget( "PanelWidget"+i ).SetUserID( i );
items_cont.GetMainPanel().FindAnyWidget( "GhostSlot"+i ).SetUserID( i );
AttRow ar;
if( m_Body.Count() < attachments_categories_count + 2 )
{
ar = new AttRow(this);
}
else
{
ar = AttRow.Cast( m_Body.Get(i+2) );
}
ar.Init(attachments_categories_count, i, attachment_category, config_path_attachment_categories, entity,m_Body.Count() );
if( m_Body.Count() < attachments_categories_count + 2 )
{
this.Insert(ar);
}
}
}
if( m_Body.Count() < attachments_categories_count + 3 )
{
if( entity.GetInventory().GetCargo() )
{
ItemWithCargo iwc = new ItemWithCargo( this );
iwc.SetEntity( entity );
ref IconsContainer items_cont2 = GetIconsContainer();
if(items_cont2)
{
int slot_number2 = i;
ItemPreviewWidget item_preview2 = ItemPreviewWidget.Cast( items_cont2.GetMainPanel().FindAnyWidget( "Icon"+ slot_number2 ) );
ImageWidget image_widget2 = ImageWidget.Cast( item_preview2.FindAnyWidget( "GhostSlot" + slot_number2 ) );
WidgetEventHandler.GetInstance().RegisterOnDrag( item_preview2.FindAnyWidget( "PanelWidget"+ slot_number2 ), this, "OnIconDrag" );
//Print(item_preview2.GetParent().GetName());
image_widget2.Show( true );
image_widget2.LoadImageFile( 0, "set:dayz_inventory image:" + icon_name );
if( m_Body.Count() > ( slot_number2 + 2 ) )
{
ClosableContainer c2 = ClosableContainer.Cast( m_Body.Get( slot_number2 + 2 ) );
if( c2.IsOpened() )
item_preview2.FindAnyWidget( "RadialIcon" + slot_number2 ).Show( true );
else
item_preview2.FindAnyWidget( "RadialIcon" + slot_number2 ).Show( false );
}
WidgetEventHandler.GetInstance().RegisterOnMouseButtonDown( items_cont2.GetMainPanel().FindAnyWidget( "PanelWidget"+i ), this, "MouseClick" );
WidgetEventHandler.GetInstance().RegisterOnMouseButtonDown( items_cont2.GetMainPanel().FindAnyWidget( "GhostSlot"+i ), this, "MouseClick" );
items_cont2.GetMainPanel().FindAnyWidget( "PanelWidget"+i ).SetUserID( i );
items_cont2.GetMainPanel().FindAnyWidget( "GhostSlot"+i ).SetUserID( i );
}
}
}
else
{
ItemWithCargo iwc2 = ItemWithCargo.Cast( m_Body.Get(attachments_categories_count + 2 ) );
//iwc2.SetEntity( entity );
iwc2.UpdateInterval();
}
//m_Parent.Refresh();
}
void OnIconDrag( Widget w )
{
string name = w.GetName();
name.Replace( "PanelWidget", "RadialIcon" );
ClosableContainer c = ClosableContainer.Cast( m_Body.Get( w.GetUserID() + 2 ) );
w.GetParent().FindAnyWidget( name ).Show( false );
}
void OnIconDrop( Widget w )
{
ItemManager.GetInstance().HideDropzones();
string name = w.GetName();
name.Replace( "PanelWidget", "RadialIcon" );
ClosableContainer c = ClosableContainer.Cast( m_Body.Get( w.GetUserID() + 2 ) );
w.GetParent().FindAnyWidget( name ).Show( c.IsOpened() );
}
override void OnDropReceivedFromHeader( Widget w, int x, int y, Widget receiver )
{
ItemPreviewWidget iw = ItemPreviewWidget.Cast( w.FindAnyWidget("Render") );
if(!iw)
{
string name = w.GetName();
name.Replace("PanelWidget", "Render");
iw = ItemPreviewWidget.Cast( w.FindAnyWidget(name) );
}
if(!iw)
{
iw = ItemPreviewWidget.Cast( w );
}
if( !iw.GetItem() )
return;
if( m_Entity.GetInventory().CanAddAttachment( iw.GetItem() ) )
{
GetGame().GetPlayer().PredictiveTakeEntityToTargetAttachment( m_Entity, iw.GetItem() );
}
else if ( m_Entity.GetInventory().CanAddEntityToInventory( iw.GetItem() ))
{
GetGame().GetPlayer().PredictiveTakeEntityToTargetInventory( m_Entity, FindInventoryLocationType.ANY, iw.GetItem() );
}
}
override void DraggingOverHeader( Widget w, int x, int y, Widget receiver )
{
if( w == NULL )
{
return;
}
ItemPreviewWidget iw = ItemPreviewWidget.Cast( w.FindAnyWidget("Render") );
if(!iw)
{
string name = w.GetName();
name.Replace("PanelWidget", "Render");
iw = ItemPreviewWidget.Cast( w.FindAnyWidget(name) );
}
if(!iw)
{
iw = ItemPreviewWidget.Cast( w );
}
if( !iw || !iw.GetItem() )
{
return;
}
if( m_Entity.GetInventory().CanAddAttachment( iw.GetItem() ) || m_Entity.GetInventory().CanAddEntityToInventory( iw.GetItem() ) )
{
ItemManager.GetInstance().HideDropzones();
ItemManager.GetInstance().GetRootWidget().FindAnyWidget( "LeftPanel" ).FindAnyWidget( "DropzoneX" ).Show( true );
ColorManager.GetInstance().SetColor( w, ColorManager.GREEN_COLOR );
}
else
{
ItemManager.GetInstance().ShowSourceDropzone( iw.GetItem() );
ColorManager.GetInstance().SetColor( w, ColorManager.RED_COLOR );
}
}
override void CollapseButtonOnMouseButtonDown(Widget w)
{
super.CollapseButtonOnMouseButtonDown(w);
m_RootSpacer.Update();
(LeftArea.Cast( m_Parent ) ).UpdateSpacer();
}
}
|
Yesterday, Anonymous declared digital war on ISIS. Now, Britain seems to be joining the fight, with an elite cyber offensive force that plans to strike Islamic State fighters.
Reuters reports that the UK Chancellor George Osborne wants the country to “strike at Islamic State fighters, hackers and hostile powers” with plans to “bolster spending on cyber defences, simplify its state cyber structures and build its own offensive cyber capability to attack adversaries.”
Advertisement
The news comes in response to British intelligence which suggests ISIS is trying to develop ways to digitally attack the UK’s hospitals, power networks and air traffic control systems, according to Osborne. Speaking to staff at Britain’s GCHQ—the British version of the NSA—he explained:
“We will defend ourselves. But we will also take the fight to [ISIS]... When we talk about tackling [ISIS], that means tackling their cyber threat as well as their guns, bombs and knives... They have not been able to use it to kill people yet by attacking our infrastructure through cyber attack. But we know they want it and are doing their best to build it.”
Britain’s attempts to defeat any digital ISIS threats will be shared between GCHQ and the military, with a doubling of spending to $2.9 billion on cyber security between now and 2020. Osborne says that it will target hackers, criminal gangs, militant groups and hostile powers.
Advertisement
It’s not clear how quickly the UK can mobilize such resources. In the meantime, Anonymous has pledged to “unleash waves of attacks on ISIS.”
[Reuters]
Image by Brian Klug under Creative Commons license |
/**
* remove violations, if any
* @param py
*/
private void deleteFix(RbNode py){
while(py!=root && py.color == COLOR.BLACK) {
if(py == py.parent.left) {
RbNode v = py.parent.right;
if(v.color == COLOR.RED) {
v.color = COLOR.BLACK;
py.parent.color = COLOR.RED;
leftRotate(py.parent);
v = py.parent.right;
}
if(v.left.color == COLOR.BLACK && v.right.color == COLOR.BLACK) {
v.color = COLOR.RED;
py = py.parent;
continue;
}
else if(v.right.color == COLOR.BLACK) {
v.left.color = COLOR.BLACK;
v.color = COLOR.RED;
rightRotate(v);
v = py.parent.right;
}
if(v.right.color == COLOR.RED) {
v.color = py.parent.color;
py.parent.color = COLOR.BLACK;
v.right.color = COLOR.BLACK;
leftRotate(py.parent);
py = root;
}
} else {
RbNode v = py.parent.left;
if(v.color == COLOR.RED) {
v.color = COLOR.BLACK;
py.parent.color = COLOR.RED;
rightRotate(py.parent);
v = py.parent.left;
}
if(v.right.color == COLOR.BLACK && v.left.color == COLOR.BLACK) {
v.color = COLOR.RED;
py = py.parent;
continue;
}
else if(v.left.color == COLOR.BLACK) {
v.right.color = COLOR.BLACK;
v.color = COLOR.RED;
leftRotate(v);
v = py.parent.left;
}
if(v.left.color == COLOR.RED) {
v.color = py.parent.color;
py.parent.color = COLOR.BLACK;
v.left.color = COLOR.BLACK;
rightRotate(py.parent);
py = root;
}
}
}
py.color = COLOR.BLACK;
} |
/**
* Object to control value generation. A FieldCase has a value and a Flag. The Flag determines
* whether allowed or also forbidden characters are part of the value. The integer value mainly
* determines where within the allowed range the generated value is located. Depending on the field
* type this value can also show the field length or - for fields with fixed values - the index of
* the value to be chosen.
*
*/
public class FieldCase {
public static final int JUST_ABOVE_MAX = -41;
public static final int JUST_BELOW_MIN = -42;
/**
* Generates a field shorter than allowed
*/
public static final FieldCase LT_MIN = new FieldCase(-1000, 0, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
Range r = ctrl.getRange();
MathRandom random = GeneratorState.currentState().getMathRandom();
int min = r.getMin();
int rnd = random.getInt(min);
if (min > 0 && rnd < 1) {
rnd = 1;
}
return new FieldCase(min - rnd, true);
}
};
/**
* Generates a field shorter by one point than allowed. If min = 0 a false character will be
* generated.
*/
public static final FieldCase ONE_LT_MIN = new FieldCase(-1000, 0, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(JUST_BELOW_MIN, true);
}
};
/**
* Generates a field longer than allowed
*/
public static final FieldCase GT_MAX = new FieldCase(-1500, 0, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
Range r = ctrl.getRange();
MathRandom random = GeneratorState.currentState().getMathRandom();
int rnd = random.getInt(r.getRange());
// at least one more than the maximum
if (rnd < 1) {
rnd = 1;
}
return new FieldCase(r.getMax() + rnd, true);
}
};
/**
* Generates a field longer by one point than allowed.
*/
public static final FieldCase ONE_GT_MAX = new FieldCase(JUST_ABOVE_MAX, 0, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(JUST_ABOVE_MAX, true);
}
};
/**
* Generates a field with average length containing - depending on the setting of the control
* object for the field - allowed or also forbidden characters.
*/
public static final FieldCase AVG = new FieldCase(-2000) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(getRandomSize(ctrl));
}
};
/**
* Generates a field with average length containing only allowed characters.
*/
public static final FieldCase AVG_GOOD = new FieldCase(-2000) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(getRandomSize(ctrl));
}
};
/**
* Generates a field with average length also containing forbidden characters.
*/
public static final FieldCase AVG_BAD = new FieldCase(-2000, -1, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(getRandomSize(ctrl), -1, true);
}
};
/**
* Generates a field with average length containing exactly one forbidden character.
*/
public static final FieldCase ONE_BAD = new FieldCase(-2000, 1, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(getRandomSize(ctrl), 1, true);
}
};
/**
* Generates a fiel with length 1 with a forbidden character
*/
public static final FieldCase ONE_BAD_CHAR = new FieldCase(-2000, 1, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(1, 1, true);
}
};
/**
* Generates a field with maximal length containing only forbidden characters.
*/
public static final FieldCase ALL_BAD = new FieldCase(-2000, -2, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(ctrl.getRange().getMax(), -2, true);
}
};
/**
* Generates a field with minimum length containing only forbidden characters
*/
public static final FieldCase MIN_BAD = new FieldCase(-2500, 1, true) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(ctrl.getRange().getMin(), -2, true);
}
};
/**
* Generates a field with minimum length
*/
public static final FieldCase MIN = new FieldCase(-2500) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(ctrl.getRange().getMin());
}
};
/**
* Generates a field with maximum length
*/
public static final FieldCase MAX = new FieldCase(-3000) {
@Override
public FieldCase getInstance(final FieldControl ctrl) {
return new FieldCase(ctrl.getRange().getMax());
}
};
/**
* Generates a field that is empty (null)
*/
public static final FieldCase NULL = new FieldCase(-5000);
/**
* Generates a character string consisting only of spaces
*/
public static final FieldCase BLANK = new FieldCase(-6000);
private final int bad;
private final int size;
private final boolean negative;
public FieldCase(final int size) {
this(size, 0, false);
}
public FieldCase(final int size, final boolean negative) {
this(size, 0, negative);
}
public FieldCase(final int size, final int bad) {
this(size, bad, false);
}
/**
* @param bad
* Number of forbidden characters. If the value is 0 no bad values are generated
* @param negative
* shows whether it is a FieldCase that generates valid {@code false} or invalid
* {@code true} Data
*/
public FieldCase(final int size, final int bad, final boolean negative) {
this.size = size;
this.bad = bad;
this.negative = negative;
}
/**
* Returns a FieldCase instance depending on the specified range. The standard implementation
* just returns {@code this}. Special implementations have to override this method to initialize
* the respective FieldCase object.
*
* @param fieldControl
* the FieldControl object, requesting the FieldCase.
*/
public FieldCase getInstance(final FieldControl fieldControl) {
return this;
}
private static int getRandomSize(final FieldControl fieldControl) {
MathRandom rnd = GeneratorState.currentState().getMathRandom();
Range range = fieldControl.getRange();
int c = range.getRange();
return range.getMin() + (c > 1 ? 1 + rnd.getInt(c - 2) : rnd.getInt(c));
}
public boolean isBad() {
return bad != 0;
}
public int getBad() {
return bad;
}
public int getSize() {
return size;
}
public boolean isNegative() {
return negative;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FieldCase other = (FieldCase) obj;
if (bad != other.bad) {
return false;
}
if (negative != other.negative) {
return false;
}
if (size != other.size) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + bad;
result = prime * result + (negative ? 1231 : 1237);
result = prime * result + size;
return result;
}
} |
<filename>include/mathtoolbox/gaussian-process-regression.hpp<gh_stars>100-1000
#ifndef MATHTOOLBOX_GAUSSIAN_PROCESS_REGRESSION_HPP
#define MATHTOOLBOX_GAUSSIAN_PROCESS_REGRESSION_HPP
#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <mathtoolbox/kernel-functions.hpp>
namespace mathtoolbox
{
class GaussianProcessRegressor
{
public:
enum class KernelType
{
ArdSquaredExp,
ArdMatern52
};
/// \brief Construct an instance with input data
GaussianProcessRegressor(const Eigen::MatrixXd& X,
const Eigen::VectorXd& y,
const KernelType kernel_type = KernelType::ArdMatern52,
const bool use_data_normalization = true);
/// \brief Calculate the mean of the predicted distribution
double PredictMean(const Eigen::VectorXd& x) const;
/// \brief Calculate the standard deviation of the predicted distribution
double PredictStdev(const Eigen::VectorXd& x) const;
/// \brief Calculate the derivative of the mean of the predicted distribution
Eigen::VectorXd PredictMeanDeriv(const Eigen::VectorXd& x) const;
/// \brief Calculate the derivative of the standard deviation of the predicted distribution
Eigen::VectorXd PredictStdevDeriv(const Eigen::VectorXd& x) const;
/// \brief Set hyperparameters directly
///
/// \details Covariance matrix calculation will run within this method.
void SetHyperparams(const Eigen::VectorXd& kernel_hyperparams, const double noise_hyperparam);
/// \brief Perform maximum likelihood estimation of the hyperparameters
void PerformMaximumLikelihood(const Eigen::VectorXd& kernel_hyperparams_initial,
const double noise_hyperparam_initial);
/// \brief Get the input data points
const Eigen::MatrixXd& GetDataPoints() const { return m_X; }
/// \brief Get the input data values
const Eigen::VectorXd& GetDataValues() const { return m_y; }
private:
// Data points
Eigen::MatrixXd m_X;
Eigen::VectorXd m_y;
// Derivative data
Eigen::MatrixXd m_K_y;
Eigen::LLT<Eigen::MatrixXd> m_K_y_llt;
Eigen::VectorXd m_K_y_inv_y;
// Normalization parameters
double m_data_mu;
double m_data_sigma;
double m_data_scale;
// Hyperparameters
Eigen::VectorXd m_kernel_hyperparams;
double m_noise_hyperparam;
// Kernel functions
Kernel m_kernel;
KernelThetaIDerivative m_kernel_deriv_theta_i;
KernelFirstArgDerivative m_kernel_deriv_first_arg;
};
} // namespace mathtoolbox
#endif // MATHTOOLBOX_GAUSSIAN_PROCESS_REGRESSION_HPP
|
/// Advance `t` to the next signal or trap according to `constraints.command`.
///
/// Default `resume_how` is ResumeSysemu for error checking:
/// since the next event is supposed to be a signal, entering a syscall here
/// means divergence. There shouldn't be any straight-line execution overhead
/// for SYSEMU vs. CONT, so the difference in cost should be negligible.
///
/// Some callers pass ResumeCont because they want to execute any syscalls
/// encountered.
///
/// If we return Incomplete, callers need to recalculate the constraints and
/// tick_request and try again. We may return Incomplete because we successfully
/// processed a CPUID trap.
fn continue_or_step(
&self,
t: &ReplayTask,
constraints: &StepConstraints,
tick_request: TicksRequest,
maybe_resume_how: Option<ResumeRequest>,
) -> Completion {
let resume_how = maybe_resume_how.unwrap_or(ResumeRequest::Sysemu);
if constraints.command == RunCommand::Singlestep {
t.resume_execution(
ResumeRequest::Singlestep,
WaitRequest::ResumeWait,
tick_request,
None,
);
self.handle_unrecorded_cpuid_fault(t, constraints);
} else if constraints.command == RunCommand::SinglestepFastForward {
self.fast_forward_status.set(
self.fast_forward_status.get()
| fast_forward_through_instruction(
t,
ResumeRequest::Singlestep,
&constraints.stop_before_states,
),
);
self.handle_unrecorded_cpuid_fault(t, constraints);
} else {
t.resume_execution(resume_how, WaitRequest::ResumeWait, tick_request, None);
if t.maybe_stop_sig().is_not_sig() {
let maybe_type = AddressSpace::rd_page_syscall_from_exit_point(t.ip());
match maybe_type {
Some(type_) if type_.traced == Traced::Untraced => {
// If we recorded an rd replay of an application doing a
// syscall-buffered 'mprotect', the replay's `flush_syscallbuf`
// PTRACE_CONT'ed to execute the mprotect syscall and nothing was
// recorded for that until we hit the replay's breakpoint, when we
// record a SIGTRAP. However, when we replay that SIGTRAP via
// `emulate_deterministic_signal`, we call `continue_or_step`
// with `ResumeRequest::ResumeSysemu` (to detect bugs when we reach a stray
// syscall instead of the SIGTRAP). So, we'll stop for the
// `mprotect` syscall here. We need to execute it and continue
// as if it wasn't hit.
// (Alternatively we could just replay with ResumeRequest::ResumeCont, but that
// would make it harder to track down bugs. There is a performance hit
// to stopping for each mprotect, but replaying recordings of replays
// is not fast anyway.)
perform_interrupted_syscall(t);
return Completion::Incomplete;
}
_ => (),
}
} else if self.handle_unrecorded_cpuid_fault(t, constraints) {
return Completion::Incomplete;
}
}
self.check_pending_sig(t);
Completion::Complete
} |
Electrochemical evaluation of self-disassociation of PKA upon activation by cAMP.
The allosteric reaction of protein kinase A (PKA) upon binding of cyclic AMP (cAMP) is revealed with an electrochemical technique through the redox current change of an electrochemically active marker. The different effect of cAMP's regulation at a distinct concentration level is obtained in this system. The influence of structural analogues is also examined with respect to the affinity and special selectivity. This study presents an electrochemical approach to the rapid and sensitive investigation of the protein-ligand interaction in the signal transduction networks. |
Comparative Genome Analysis of 2 Mycobacterium Tuberculosis Strains from Pakistan: Insights Globally Into Drug Resistance, Virulence, and Niche Adaptation
Multidrug-resistant Mycobacterium tuberculosis is a global threat particularly in developing countries like Pakistan. In this study, we identified 2 M tuberculosis strains, mnpk and swlpk, by 16S RNA genes, sequenced their draft genome, and compared the 2 genomes with reference strain H37Rv and gene expression analysis of selected virulent genes. Phylogenetic analysis of M tuberculosis strains, mnpk and swlpk, using 16S RNA genes revealed that the strains are closely related with reference strain H37Rv. The draft genome sequence of mnpk and swlpk contains 4305 and 4295 protein-coding genes, respectively, having 99.9% with high collinearity when compared with H37Rv. Although some important drug-resistant genes such as fabG, faDE24, and iniA were missing, genome mining also revealed key drug-resistant genes such as katG, inhA, rpoA, rpoB, and rpoC against first-line isoniazid and rifampicin drug. The strain mnpk and swlpk encodes 257 putative and 86 verified virulent genes including type 7 secretion system (T7SS) key genes. The variation in the expression profile of selected T7SS genes, particularly low expression level of EspK, raised concern that the mechanism of virulence of mnpk and swlpk might be different from H37Rv strains as espK is associated with ATPase EccC1a and EccC1b which showed high expression level. Briefly, this study shows that the strains mnpk and swlpk are linked with H37Rv having 99% similarity in genomes, but the absence of drug-resistant genes and variation in key genes’ expression profile espK, EccE1, PPE41, and espC provide a rationale for the future investigation of M tuberculosis mnpk and swlpk pathogenesis via RNA sequencing, single-nucleotide polymorphisms, as well as gene manipulation.
Introduction
Tuberculosis (TB) is a widespread infectious disease caused by a pathogen known as Mycobacterium tuberculosis. Mycobacterium tuberculosis is a gram-positive bacteria belonging to the Mycobacteriaceae family. 1 Tuberculosis, a chronic disease, is the primary source of lower respiratory tract illness and causes 10.4 million ill cases and 1.7 million deaths every year 2 (World Health Organization report 2017). Unfortunately, in Pakistan, TB has remained ignored in the past and its prevalence has made a severe challenge for medical industry to deal with this disease. 3,4 More seriously, half of the TB cases in Pakistan are diagnosed in Punjab which is known as the most populous province of Pakistan. 4 Among many factors that contribute to TB prevalence and transmission in Pakistan, the predominant factors are incorrect treatment regimes, poverty, unawareness, poor sanitation, and default treatment. 5 The development of multidrug-resistant TB (MDR-TB) is the result of a number of mutational events, most of which are due to the phenomenon known as epistasis that leads to the formation of resistance to anti-TB drugs. 6 Like all bacteria, M tuberculosis accumulates genetics changes over time. For a long time, M tuberculosis has been known as highly conserved, having high sequence homology as well as low antigenic diversity. 7 The reason is that in M tuberculosis, unlike to other bacterial pathogens, horizontal gene transfer and resistance plasmids did not take part in the acquisition of drug resistance. 7 The advancement in next-generation sequencing technologies are proving promising methods to analysis and explore the entire genetic makeup of the bacteria. 8 These technologies have improved the diagnostics efficacy to scrutinize M tuberculosis strains as they move through space and time. 9 The genome sequencing, genetics, and physiological studies in TB, particularly the research on M tuberculosis, have largely been ignored in Pakistan, possibly due to insufficient funding. The aims of this study include genome sequencing, comparative genomics analysis, drugs 2 Evolutionary Bioinformatics resistance, and virulence genes analysis following gene expression analyses of T7SS. Results from this study will help to understand and to measure the M tuberculosis disease severity in Pakistan by deciphering the sequence biology of M tuberculosis.
Materials and Methods
Culturing and identification of M tuberculosis by 16S rRNA gene sequencing Mycobacterium tuberculosis isolates mnpk and swlpk were identified using 16S rRNA gene as described by El Amin et al 10 and Lawn et al. 11 Briefly, isolates of M tuberculosis cells were taken from Löwenstein-Jensen media and killed by adding ciprofloxacin (100 μg/mL) into the culture media before lysis and following incubation for an hour at 30°C. Lysozyme (20 μL) added into Eppendorf tube and stored for 2 hours at 37°C. After adding 30 μL sodium dodecyl sulfate (10%) and 3 μL proteinase K (0.2 mg/mL), tubes were gently vortexed and incubated for 20 minutes at 65°C. About 80 μL of 100 μL NaCl (0.1 M) and N-acetyl-N, N, N-trimethyl ammonium bromide (40 mM) was added. The Eppendorf tubes were vortexed till the whole solution turned milky and stored at 65°C for 15 minutes. About 750 μL of chloroform-isoamyl alcohol (24:1) was added following vortex and centrifugation till 5 minutes at room temperature at 13 000 rpm. It was followed by ethanol precipitation and collection of DNA in 110 μL TE buffer.
The 16S rRNA gene amplification was performed with universal primer set F-285 5ʹ-AGAGTTTGATCCTGGC TCAG-3ʹ and Myc-264 3ʹ-TGCACACAGGCCACAAG GGA-5ʹ as described by Gholoobi et al. 12 Total polymerase chain reaction (PCR) reaction mixture was set in a final volume of 25 µL using 12.5 µL of Taq Master Mix, 9.5 µL water, and 1 µL of DNA template, and forward and reverse primers were used. Negative control used in this experiment was the sample having no DNA template. The PCR conditions used for this reaction were as follows: 94°C for 1 minute, 60°C for 1 minute and 72°C for 1 minute for 35 cycles, and final elongation cycle at 72°C for 10 minutes. The PCR amplification was run at 1.5 % agarose gel electrophoresis and PCR product was eluted using DNA elution kit (Tiagin, TIANGEN Biotech, Beijing, China) and sent for sequencing (Macrogen Seoul, Korea) and obtained sequence were analyzed at NCBI (National Center for Biotechnology Information) using BLAST tool 13 with default parameters. To reveal evolutionary association of drug resistance proteins of M tuberculosis strains mnpk and swlpk, a phylogenetic analysis based on 16S rRNA genes was conducted through MEGA 7 using maximum likelihood methods with default parameters. 14
Genome sequencing, assembly, and annotation
The whole genome sequence of M tuberculosis strains mnpk and swlpk from Pakistani patients was done using Illumina MiSeq 300PE throughput 2M which produced, on average, more than 20× coverage with a total of 140 127 reads for strain mnpk and more than 20× coverage with a total of 139 989 reads for strain swlpk. The de novo genomic assembly was conducted using Geneious pro V10. 15 Assembled genome sequences of strains were annotated using Rapid Annotation Subsystem Technology (RAST) server, 16 tRNAscan-SE 1.21, 17 and RNAamer V1.2 18 which provide high-quality functional annotation.
Genome alignment, similarity, and visualization
The genome alignment of M tuberculosis swlpk and mnpk was conducted using Mauve software package, 19 which is employed for conducting an alignment of multiple genomes to look at the highly similar subsequences, evolutionary events such as inversions, rearrangement, and likely to reveal the correct global alignment. The multiple genome alignment in the form of graphical map of genome sequence provides a means to quickly view the characteristics of specific genomic regions and study of genomic level evolutionary dynamics. The 2 genomes were also further compared using CGView tool. 20 A circular genomic map of M tuberculosis strains was generated using CGView that represent circular genomes into graphical map resulting base composition plots, sequence features, and analysis such as GC skew, GC content, and number of RNAs.
Drug-resistant gene prediction and characterizations
In a previous study, Ze-Jia et al 21 reported various drug resistance genes in M tuberculosis strain H37Rv. The sequences of drug-resistant genes were retrieved from M tuberculosis strain H37Rv via UniProt and NCBI databases and were used as reference. Using these genes as query, a BLAST search was conducted against M tuberculosis strains mnpk and swlpk at RAST server with following parameters, cut-off value 10, ie, 1e−30, and filter size 0.
The drug resistance proteins identified in mnpk and swlpk using reference strain H37Rv were further in silico characterized by performing protein domain, protein family search analysis using NCBI's Conserved Domain Database 22 and InterPro. 23 Protein family search was conducted in drug resistance genes of both strains using Pfam database. 24
Virulence factors distribution and analysis
The Virulence Factors Database (VFDB) 25 was used for retrieving virulence genes and all the virulent genes used in this study were from M tuberculosis H37Rv. The FASTA sequences of encoded virulent genes of H37Rv were used as query sequences to search each matching gene in the 2 M tuberculosis strains, mnpk and swlpk, genomes using BLAST too at RAST server (50% coverage and 90% identity thresholds).
RNA extraction and quantitative real-time PCR
ESX-1 to ESX-5 are the 5 T7SS present in M tuberculosis. Three out of these 5 systems are necessary for mycobacterial virulence and/or viability. 26 To understand the molecular Yar et al 3 mechanisms of resistance pathogenicity based on the available genomics data, in this study, we further evaluated M tuberculosis mnpk and swlpk strains and gene expression profiles of selected and previously verified T7SS. 27 Culture was prepared for RNA extraction as described by Wang et al, 28 using RNA extraction kit according to the manufacturer's instructions (Qiagen, Germantown, MD, USA). About 1.5 μg of RNA was reverse transcribed according to the manufacturer's instructions (Qiagen, USA) with following thermal cycling conditions: 25°C for 10 minutes, 42°C for 60 minutes, and 85°C for 5 minutes. The complementary DNA (cDNA) was kept at −20°C. Two cDNA preparations were made. The assay was conducted using cDNA directly as a template for quantitative reverse transcription PCR (qRT-PCR) on PikoReal Real-Time PCR System (Thermo Scientific). Comparative gene analysis for normalized expression of target transcripts profile was determined using the ΔΔCT method, where CT is the threshold cycle.
Genomic DNA extraction and 16S rRNA gene identification
The PCR reaction was performed using 16S rRNA gene primers and results showed the amplification of 16S rRNA genes at size approximately 1400 bp (base pairs) when compared with 100 bp markers ( Figure 1) which lead to the confirmation of isolate as M tuberculosis at molecular level. Amplified products were sequenced which give the size of 1.4 kb gene sequence. Global alignment and comparative analysis were conducted at NCBI BLAST analyses using NCBI BLASTn for evolutionary analysis. The results showed that M tuberculosis strain has 100% identity with reference strain H37Rv, whereas other close neighbors are M tuberculosis strain MTB1 another drugresistant strain ( Figure 2). The partial sequences were submitted to the NCBI and the accession numbers obtained based on 16S rRNA gene of M tuberculosis strains mnpk and swlpk are KY271751 and KY287640, respectively. Evolutionary relationships among various biological species or other entities are shown in the form of evolutionary tree ( Figure 2) and those strains are out of the cluster of M tuberculosis endorsing that the partial sequence of M tuberculosis strains is conserved within M tuberculosis species.
Genome data acquisition and analysis
The sequenced and assembled genomes of 2 M tuberculosis strains mnpk and swlpk consisting of 20 and 12 contigs, respectively, were used in this study using H37Rv as reference. The estimated assembled genome size of strain mnpk is 4.4 Mb and swlpk 4.39 Mb with GC contents of 65.6% (Table 1). The size of strain mnpk as well as swlpk is smaller than M tuberculosis strain H37Rv whose total estimated size is 4.41 Mb. The strains mnpk and swlpk encode total 4295 protein-coding sequence (CDS) and 4305 CDS, respectively. Genome comparative analysis at RAST reveals that the closest neighbor of mnpk and swlpk is M tuberculosis strain H37Rv which belongs to the Beijing genotypes.
Comparative genomics features analysis
We investigated the overall genome similarities as well as differences between M tuberculosis strains mnpk and swlpk with reference strain H37Rv by alignment using Mauve 2.3.1, CGView, and RAST tools. The M tuberculosis strains mnpk and swlpk were highly syntenic when compared with H37Rv Mauve results showed that colored blocks represent the individual locally collinear blocks (LCBs), and the homologous LCBs among the 3 strains are connected. Overall, the syntenic regions are shown as colored rounded boxes and unique regions in the genomes are shown as white/gray areas in Figure 3. The regions mutual with a subset of 3 genomes or segments seem to be conserved among all the genomes. Because M tuberculosis genomes of strains mnpk and swlpk are unfinished, these results only include the genomic rearrangement that occurred within contigs and the actual number of rearrangements is probably higher.
A circular genome map of strains mnpk and swlpk was generated using CGView using assembled contigs. The circular genome of strains mnpk and swlpk displays the CDS, open reading frame, GC content, number of RNAs, and GC skew (Figure 4) where the first 2 rings represent the CDS and the number of RNAs (tRNA, rRNA, and sRNA), on the forward and reverse strands. The GC contents which M tuberculosis encode and are above the genome average (65.6%) are shown by black plot with the peaks extending toward the outside of the circle, whereas those GC contents which are lower than the genome average are extending toward the center mark segments. The innermost plot represents GC skew. Green color shows the positive G+C mean excess of guanine over cytosine, whereas purple color shows negative G−C mean excess of cytosine over guanine ( Figure 4).
The predicted protein sequences were annotated to various clusters of orthologous groups (COG) categories. Some differences in protein numbers among COG categories of M tuberculosis strains mnpk and swlpk and H37Rv genomes were identified (including those listed as protein numbers for M tuberculosis strains mnpk and swlpk and H37Rv genomes ( Figure 5). This list contains all genes associated with various key function of M tuberculosis such as virulence, disease and defense genes, membrane transport genes stress responses genes, drug resistance genes and regulation, and cell signaling genes. The details of these genes are shown and described in Figure 5. It showed several new insights such as the better understanding of the M tuberculosis strains', swlpk and mnpk, origin as an obligate pathogen and population genetic characteristics and its molecular evolution both within and between hosts following many features related to antibiotic resistance.
Drug resistance gene prediction and analysis
Mycobacterium tuberculosis strains mnpk and swlpk encode several drug-resistant genes ( Table 2) against key drugs such as isoniazid, rifampicin, capreomycin, ethambutol (EMB), ethionamide, and ofloxacin. The uptake of drug resistance genes listed in Table 2 not only reveals the association of these strains with Beijing family genotype of M tuberculosis but is also vital for development of drug resistance genes-based markers for Pakistan-resourced strains of M tuberculosis. Apart from the drug-resistant genes present in strains mnpk and swlpk (Table 2), several drug-resistant genes of M tuberculosis already reported in reference strain H37Rv were not found such as faDE24 and iniA which are associated with isoniazid genes; rpoB which is associated with rifampicin gene; embR, iniA, and rmlD, which are ethambutol-associated genes; and rpsL and rrs which are associated with streptomycin (SM) ( Table 2). Moreover, the missing genes may therefore have impact on the efficacy of antimicrobial agents, particularly when their presence has not been diagnosed. Table 3 enlists the protein domains and families associated with drug-resistant genes present in mnpk and swlpk. Our results showed that all the drug resistance genes of M tuberculosis strains mnpk and swlpk against first-line or second-line drugs encode similar domain as well as family. No differences were noted among their family-based functional analysis. The rpoA and rpoC genes of strains mnpk and swlpk that participate in RIF resistance belong to DNA-directed RNA polymerase, and the subunit beta prime family encodes the same family. Moreover, gene paralogs were seen such as all the genes, embA, embB, and embC, retrieved from strains mnpk as well as swlpk genomes associated with ethambutol drug resistance belong to the same family Arabinose_trans_C.
Genome-wide analysis of virulent genes
Despite the high conservation in genome of M tuberculosis, the various lineages have diverse degrees of virulence. In our study, we looked into the genome of M tuberculosis strains mnpk and swlpk for virulence factors using 257 virulence factor obtained from VFDB as bait (Table S1). Among these, about 86 are experimentally verified as described by Jia et al 27 and VFDB database, 25 whereas the rests are putative ones. The results showed that all the verified virulence factors existed not only in strain mnpk but also in swlpk except hspR (Rv0353), fbpD (Rv 3803c), and devS (Rv3132c) described in Table S1. Moreover, all these verified encoded genes are conserved in 3 strains. We also found that several virulent factors were absent in strains mnpk and swlpk such as mce2E and mce1E putative virulent genes. This may be important to note that these strains may be not highly virulent and verification of these missing drug resistances via RNA sequencing will be highly vital for the ecology of these strains and its association with global strains.
Quantitative expression of T7SS genes
The quantification results of the expression levels of 25 T7SS genes in 2 strains are shown in Table 4 and the detailed set of primers for all target genes for qRT-PCR are listed in Table S3. In strain mnpk as well as in swlpk, genes espk, eccE1, eccE5, eccD5 showed the lowest expression levels from 0.177 to 0.004. The T7SS genes esxA, esxB, eccB1, eccCa1, eccb1, PE35, eccD1, espK, eccE1, eccCb5, and eccCa5 showed higher than 5.0. The genes espB, eccB1, and eccCa1 were exceptional which showed the highest expression levels from 21.265 to 33.06. We also examined the expressional differences between 2 strains such as the expression levels of espA and Rv1794 genes which were significantly higher in mnpk and (P < .05) than in swlpk (Table 4). We also found that the expression of 3 genes (espC, esxM, and PPE41) was significantly lower (P < .05) in mnpk isolates than in swlpk isolates.
Discussion
Although many research works had been conducted and still continue with several efforts to get insight into the nature and origin of MDR-TB, dilemma remains obscure. In our study, we have conducted the extensive genomics study to reveal the multidrug resistance as well as the virulence features. By this study, we wished to get closer in the understanding of multidrug-resistant tuberculosis. Moreover, we believe that understanding the molecular basis of TB drug resistance using next-generation sequencing technologies could pave the way to fight against this old foe by developing of new diagnosis approaches. The prevalence and rapid dissemination of Mycobacterium tuberculosis Beijing strains are reported around the globe and makes it an important issue of public health. By this study, we could not draw any concrete conclusion that about the close association of M tuberculosis strains mnpk and swlpk with Beijing genotypes but presence of drug resistance and virulent genes has been shown in many settings of strains mnpk and swlpk such as Beijing genotypes. It showed that these strains could have high level of virulence and multidrug resistance, resulting in rapid progression from infection to active disease and increased transmissibility in M tuberculosis H37Rv which is highly virulent, drug resistant, and endemic over Asia. 28 The difference in genome size with reference strain H37Rv may lead to the prediction that strains mnpk and swlpk may have some missing genes or could be an overestimation due to the incomplete nature of genomes and scaffolds quality could be lower with stretches of N's. The high GC contents in these strains depict the stability of the genome as characteristically high GC% age also verifies the hypothesis that horizontal gene transfer events are nearly missing in M tuberculosis which is consistent as described by Šmarda et al. 28 The M tuberculosis strains mnpk and swlpk were highly syntenic with H37Rv genomes verifying their close relationship when compared using Mauve 2.3.1. The composition of bacterial genomes is highly polarized nucleotide in the 2 replichores and this asymmetry of genomic strand could be visualized by GC skew graph. Most prokaryotes and archaea contain only 1 DNA replication origin. 29,30 There will be a GC skew when composition of guanine and cytosine nucleotides is over-or underabundant in a particular region of DNA. The GC skew in strain mnpk and swlpk represents that nucleotide composition is asymmetric between the lagging strand and leading strand which is consistent to Escherichia coli. 31 The presence of key drug-resistant genes and their belonging to PPE and PE family protein indicate that patterns of these drug resistances may differ widely not only in transmissibility of drug resistance but also from single-drug to multiple-drug resistance and which are allied with numerous genetic
Evolutionary Bioinformatics
mutations. 32 RpoB gene identified in mnpk as well as swlpk is notorious to drug resistance by mutation such as 95% of RIF resistance in M tuberculosis strains which is caused by mutation in rpoB genes. It is known that most of the mutations took place in the 81-bp core region of the rpoB gene which encodes the β-subunit of the RNA polymerase and is known as RIFresistance-determining region. 33 Similarly, other RIFassociated genes also go to various mutations and developing drug resistance such as rpoC and rpoA in mnpk and swlpk strains may provide preliminary data for RIF-resistant patterns and more importantly these are also known as a surrogate marker of multidrug-resistant genes in M tuberculosis. 34 Similarly, resistance to isoniazid has been linked not only with mutations in genes such as inhA and KatG but also with 2 different genes such as ahpC, and oxyR. 7 The development of resistance against SM drugs in M tuberculosis is known as linked with mutations rpsL which code for ribosomal protein S12 and in rrs gene which codes for 16S rRNA. 35 The data regarding these mutations are in a limited proportion for SM-resistant M tuberculosis clinically isolated. Both of these genes are not retrieved in M tuberculosis strains mnpk and swlpk. It shows that these strains may depend on gidB which has been reported that development of resistance is caused by mutations within the gidB gene at conserved 7-methylguanosine (m7G) methyltransferase position. 36 The embA, embB, and embC genes were identified in both strains and it has been reported that the cause of resistance to EMB drugs is mutation in these genes which is consequently making M tuberculosis more drug resistant. 37 The existence of these well-known drug-resistant genes in Pakistani strains will be beneficial for further analysis on identification and characterizations and will enrich the TB genetic data sources. The missing of faDE24, iniA, rpoR, rpsL, rrs genes indicates that further analyses are required and these genes may not be used as a marker when identifying samples from Pakistan-resourced strains. In silico identification of protein family significantly highlights the functional characterizations of proteins or interaction contributing to the overall role of a protein. 38 The results of our study showed that all proteins identified in strain mnpk as well as swlpk encode similar proteins which either is not new and showed the close relation of these proteins with Beijing genotype.
Several studies have identified components of T7SS in M tuberculosis and their role in pathogenicity. 39 Although very important proteins such as EccD1 (Rv3877), EccCb1 (Rv3871), and EccCa1 (Rv3870) which are indispensable for secretion of ESX-1 in M tuberculosis expression level were significantly better among both strains, but EccE1 (Rv3882c) is the core membrane protein and espK is an ESX-1 secretion-associated protein. In our study, expression of espK is very low and EccC1a and EccC1b showed higher gene expression. The ESX-1 which is a part of T7SS is the most important virulent component in M tuberculosis, but the role of espK in this system is not clear. Similarly, McLaughlin et al 40 reported that espB interacts with espK (which showed low level of expression); the interaction of these proteins leads to the interaction of membrane-associated ATPases EccC 1a and EccC 1b . It is well-documented that virulence features of Beijing strains such as H37Rv are more than the modern isolates. There were no appreciable differences except the absence of few genes mentioned above between Beijing genotype strain (H37Rv) and other strains such as mnpk and swlpk (Table S1). We may infer that these missing genes might have been lost through IS6110.
Similarly, some differential gene expression among strain to strain were also noted such as espA, Rv1794 were highly expressed in mnpk and low expressed in swlpk, esxM, espC, PPE41 were highly expressed in swlpk and low expressed in mnpk. The findings of gene expression profile lead toward 2 major key information in gene expression profile such as lowexpression espK and eccE1, and the possible effect of these variations could impact on mechanism of virulence which needs to be disclosed and is conceivable that these various differences noted in our study might have a functional impact.
Conclusions
This study of comparative genomics analysis of 2 Mycobacterium strains resourced from Pakistan allowed in-depth genomewide comparison and covered important genetic heterogeneity. The high similarity with H37Rv but still missing of key drug resistance genes, variation in the expression profile of already verified T7SS proteins, particularly low expression level of espK, which is one of the important virulent factors and associated with membrane-associated ATPase EccC 1a -EccC 1b , raises concern that the mechanism of virulence of mnpk and swlpk strains via RNA sequence as well as gene manipulation will be important future prospective. |
/**
* Check and return corresponding TokenType of given UTF-8 codePoint.
*
* @param codePoint codePoint calculated by {@link Character#codePointAt(char[], int)}
* @return {@link TokenType} of given codePoint
* @see com.yahoo.language.simple.SimpleTokenType
*/
public static TokenType valueOf(int codePoint) {
switch (Character.getType(codePoint)) {
case Character.NON_SPACING_MARK:
case Character.COMBINING_SPACING_MARK:
case Character.LETTER_NUMBER:
case Character.UPPERCASE_LETTER:
case Character.LOWERCASE_LETTER:
case Character.TITLECASE_LETTER:
case Character.MODIFIER_LETTER:
case Character.OTHER_LETTER:
return TokenType.ALPHABETIC;
case Character.ENCLOSING_MARK:
case Character.MATH_SYMBOL:
case Character.CURRENCY_SYMBOL:
case Character.MODIFIER_SYMBOL:
case Character.OTHER_SYMBOL:
return TokenType.SYMBOL;
case Character.OTHER_NUMBER:
case Character.DECIMAL_DIGIT_NUMBER:
return TokenType.NUMERIC;
case Character.SPACE_SEPARATOR:
case Character.LINE_SEPARATOR:
case Character.PARAGRAPH_SEPARATOR:
return TokenType.SPACE;
case Character.DASH_PUNCTUATION:
case Character.START_PUNCTUATION:
case Character.END_PUNCTUATION:
case Character.CONNECTOR_PUNCTUATION:
case Character.OTHER_PUNCTUATION:
case Character.INITIAL_QUOTE_PUNCTUATION:
case Character.FINAL_QUOTE_PUNCTUATION:
return TokenType.PUNCTUATION;
default:
return TokenType.UNKNOWN;
}
} |
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_event_loop.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "wifi.h"
#define TAG "wifi:"
#define STA_CONNECTED_BIT BIT0
#define STA_GOTIP_BIT BIT1
static EventGroupHandle_t station_event_group;//24bit
static wifi_config_t sta_config;
static esp_err_t net_event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:// station start
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_DISCONNECTED: //station disconnect from ap
esp_wifi_connect();
xEventGroupClearBits(station_event_group, STA_CONNECTED_BIT);
xEventGroupClearBits(station_event_group, STA_GOTIP_BIT);
break;
case SYSTEM_EVENT_STA_CONNECTED: //station connect to ap
xEventGroupSetBits(station_event_group, STA_CONNECTED_BIT);
break;
case SYSTEM_EVENT_STA_GOT_IP: //station get ip
ESP_LOGI(TAG, "got ip:%s\n",
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
xEventGroupSetBits(station_event_group, STA_GOTIP_BIT);
break;
case SYSTEM_EVENT_SCAN_DONE:
// uint16_t apCount = 0;
// esp_wifi_scan_get_ap_num(&apCount);
// if (apCount == 0) {
// BLUFI_INFO("Nothing AP found");
// break;
// }
// wifi_ap_record_t *ap_list = (wifi_ap_record_t *)malloc(sizeof(wifi_ap_record_t) * apCount);
// if (!ap_list) {
// BLUFI_ERROR("malloc error, ap_list is NULL");
// break;
// }
// ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&apCount, ap_list));
// esp_blufi_ap_record_t * blufi_ap_list = (esp_blufi_ap_record_t *)malloc(apCount * sizeof(esp_blufi_ap_record_t));
// if (!blufi_ap_list) {
// if (ap_list) {
// free(ap_list);
// }
// BLUFI_ERROR("malloc error, blufi_ap_list is NULL");
// break;
// }
// for (int i = 0; i < apCount; ++i)
// {
// blufi_ap_list[i].rssi = ap_list[i].rssi;
// memcpy(blufi_ap_list[i].ssid, ap_list[i].ssid, sizeof(ap_list[i].ssid));
// }
// esp_blufi_send_wifi_list(apCount, blufi_ap_list);
// esp_wifi_scan_stop();
// free(ap_list);
// free(blufi_ap_list);
break;
default:
break;
}
return ESP_OK;
}
void wifi_sta_init()
{
tcpip_adapter_init();
station_event_group = xEventGroupCreate();
ESP_ERROR_CHECK( esp_event_loop_init(net_event_handler, NULL));
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK(esp_wifi_start() );
}
void wifi_sta_deinit()
{
ESP_ERROR_CHECK(esp_wifi_stop());
ESP_ERROR_CHECK(esp_wifi_deinit());
}
void wifi_set_config(const char* cfg_ssid, const char* cfg_pwd)
{
strcpy((char *)sta_config.sta.ssid, cfg_ssid);
strcpy((char *)sta_config.sta.password, cfg_pwd);
esp_wifi_disconnect();
esp_wifi_set_config(ESP_IF_WIFI_STA, &sta_config);
esp_wifi_connect();
}
bool wifi_isConnected()
{
EventBits_t uxBits = xEventGroupGetBits(station_event_group);
return ((uxBits&STA_GOTIP_BIT) == STA_GOTIP_BIT);
}
tcpip_adapter_ip_info_t wifi_waitConnect()
{
xEventGroupWaitBits(station_event_group, STA_GOTIP_BIT, pdFALSE, pdTRUE, portMAX_DELAY);
tcpip_adapter_ip_info_t ip;
memset(&ip, 0, sizeof(tcpip_adapter_ip_info_t));
if (tcpip_adapter_get_ip_info(ESP_IF_WIFI_STA, &ip) == 0) {
ESP_LOGI(TAG, "~~~~~~~~~~~");
ESP_LOGI(TAG, "ETHIP:"IPSTR, IP2STR(&ip.ip));
ESP_LOGI(TAG, "ETHPMASK:"IPSTR, IP2STR(&ip.netmask));
ESP_LOGI(TAG, "ETHPGW:"IPSTR, IP2STR(&ip.gw));
ESP_LOGI(TAG, "~~~~~~~~~~~");
}
return ip;
}
|
<reponame>eliahburns/yugabyte-db<filename>ent/src/yb/tserver/remote_bootstrap_service_ent.cc
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
#include "yb/tserver/remote_bootstrap_service.h"
#include "yb/tserver/remote_bootstrap_session.h"
namespace yb {
namespace tserver {
namespace enterprise {
using std::string;
RemoteBootstrapServiceImpl::RemoteBootstrapServiceImpl(
FsManager* fs_manager,
TabletPeerLookupIf* tablet_peer_lookup,
const scoped_refptr<MetricEntity>& metric_entity)
: super(fs_manager, tablet_peer_lookup, metric_entity) {
}
Status RemoteBootstrapServiceImpl::GetDataFilePiece(
const DataIdPB& data_id,
const scoped_refptr<RemoteBootstrapSessionClass>& session,
uint64_t offset,
int64_t client_maxlen,
string* data,
int64_t* total_data_length,
RemoteBootstrapErrorPB::Code* error_code) {
if (data_id.type() == DataIdPB::SNAPSHOT_FILE) {
// Fetching a snapshot file chunk.
const string file_name = data_id.file_name();
const string snapshot_id = data_id.snapshot_id();
RETURN_NOT_OK_PREPEND(
session->GetSnapshotFilePiece(
snapshot_id, file_name, offset, client_maxlen, data, total_data_length, error_code),
"Unable to get piece of snapshot file");
return Status::OK();
}
return super::GetDataFilePiece(
data_id, session, offset, client_maxlen, data, total_data_length, error_code);
}
Status RemoteBootstrapServiceImpl::ValidateSnapshotFetchRequestDataId(
const DataIdPB& data_id) const {
if (data_id.snapshot_id().empty()) {
return STATUS(InvalidArgument,
"snapshot id must be specified for type == SNAPSHOT_FILE",
data_id.ShortDebugString());
}
if (data_id.file_name().empty()) {
return STATUS(InvalidArgument,
"file name must be specified for type == SNAPSHOT_FILE",
data_id.ShortDebugString());
}
return Status::OK();
}
} // namespace enterprise
} // namespace tserver
} // namespace yb
|
// ListContains will check if a string array contains a substring
func ListContains(list []string, substring string) bool {
var contains bool
for _, s := range list {
if strings.Contains(s, substring) {
contains = true
break
}
}
return contains
} |
Gamers in Japan can download their Famicom ambassador titles a day early.
The Famicom titles for the Nintendo Ambassador program are currently available for download in Japan. Originally set to be released on September 1, the titles have made a surprise appearance on the eShop a day early.
There are ten classic Famicom titles available in Japan including the likes of Super Mario Bros., Mario Open Golf, The Legend of Zelda, Metroid, and others. Also included in the update was an "Ambassador Certificate" which is a movie explaining the Ambassador program with the option to opt in to future notifications about the service, assumedly the GBA games to come at a later date.
The process of downloading the titles is not immediately obvious, users must go to the settings menu within the eShop and click "previously downloaded titles" where all 10 game have been added to the list. |
Versatile retroviral vectors for potential use in gene therapy.
A set of retroviral vectors is described whose capacity for high efficiency transduction of functional genes into undifferentiated murine embryonic and haematopoietic cells makes them ideally suited for preclinical studies with murine models. Multiple unique cloning sites permit insertion of genes into the vectors such that no selectable marker exists or either the neomycin phosphotransferase (neo) gene, the hygromycin B phosphotransferase (hph) gene or the puromycin N-acetyl transferase (pac) gene is included as a dominantly acting selectable marker. Because the sequences in the viral gag region shown to improve the encapsidation of viral RNA have been modified to prevent viral protein synthesis and all env sequences have been removed to eliminate helper virus production by homologous recombination with packaging DNA, these vectors might prove useful in human gene therapy protocols. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.