content
stringlengths
10
4.9M
/** Configuration for Lint in Eclipse projects */ class ProjectLintConfiguration extends DefaultConfiguration { private boolean mFatalOnly; private final static QualifiedName CONFIGURATION_NAME = new QualifiedName(AdtPlugin.PLUGIN_ID, "lintconfig"); //$NON-NLS-1$ @VisibleForTesting ProjectLintConfiguration(LintClient client, Project project, Configuration parent, boolean fatalOnly) { super(client, project, parent); mFatalOnly = fatalOnly; } private static ProjectLintConfiguration create(LintClient client, IProject project, Configuration parent, boolean fatalOnly) { File dir = AdtUtils.getAbsolutePath(project).toFile(); Project lintProject = client.getProject(dir, dir); return new ProjectLintConfiguration(client, lintProject, parent, fatalOnly); } public static ProjectLintConfiguration get(LintClient client, IProject project, boolean fatalOnly) { // Don't cache fatal-only configurations: they're only used occasionally and typically // not repeatedly if (fatalOnly) { return create(client, project, GlobalLintConfiguration.get(), true); } ProjectLintConfiguration configuration = null; try { Object value = project.getSessionProperty(CONFIGURATION_NAME); configuration = (ProjectLintConfiguration) value; } catch (CoreException e) { // Not a problem; we will just create a new one } if (configuration == null) { configuration = create(client, project, GlobalLintConfiguration.get(), false); try { project.setSessionProperty(CONFIGURATION_NAME, configuration); } catch (CoreException e) { AdtPlugin.log(e, "Can't store lint configuration"); } } return configuration; } @Override public @NonNull Severity getSeverity(@NonNull Issue issue) { Severity severity = super.getSeverity(issue); if (mFatalOnly && severity != Severity.FATAL) { return Severity.IGNORE; } return severity; } }
import { InventarioService, FarmaciaService } from './inventario.service'; import { InventarioDto, FarmaciaDto } from './dto/inventario-dto'; export declare class InventarioController { private readonly inventarioService; constructor(inventarioService: InventarioService); createInve(createInveDto: InventarioDto): Promise<import("./interfaces/inventario.interface").Inventario>; getInveAll(): Promise<import("./interfaces/inventario.interface").Inventario[]>; getInventarios(id: string): Promise<import("./interfaces/inventario.interface").Inventario[]>; getInveMed(id: string): Promise<import("./interfaces/inventario.interface").Inventario[]>; deleteInve(id: any): Promise<any>; } export declare class FarmController { private readonly farmaciaService; constructor(farmaciaService: FarmaciaService); createFarm(createFarmDto: FarmaciaDto): Promise<import("./interfaces/inventario.interface").Farmacia>; getFarmAll(): Promise<import("./interfaces/inventario.interface").Farmacia[]>; listarFarmParent(id: any): Promise<import("./interfaces/inventario.interface").Farmacia[]>; updateFarm(updateFarmDto: FarmaciaDto): Promise<import("./interfaces/inventario.interface").Farmacia>; deleteFarm(id: any): Promise<any>; }
import { Module } from '@nestjs/common'; import { CounterService } from './counter.service'; import { CounterController } from './counter.controller'; @Module({ controllers: [CounterController], providers: [CounterService] }) export class CounterModule {}
T cells in pregnancy. Maternal tolerance of the fetal allograft could be the result of the integration of numerous mechanisms promoted by different cells present in the decidua. Decidual macrophages and dendritic cells, which are found in close association with T lymphocytes are the most potent activators of T lymphocyte responses and could play a sentinel function for the immune system, initiating antigen-specific T cell responses to fetal antigens. T cell cytokines produced in response to fetal molecules could have a role in the maintenance or in the failure of pregnancy. The levels of LIF, IL-4, IL-10 and M-CSF produced by decidual T cells of women suffering from unexplained spontaneous abortion are lower than those of normal pregnant women indicating that these cytokines may contribute to the maintenance of pregnancy. T cells from the cumulus oophorus surrounding the preimplantation embryo produce LIF and IL-4. These findings suggest that cytokines produced by maternal T cells create a suitable microenvironment for preimplantation embryo development and maintenance of pregnancy. T cell cytokine profile could be modulated by the hormones present in the microenvironment of T cells: high doses of progesterone present at fetomaternal interface and in the cumulus induce the production of IL-4 and LIF, whereas relaxin induces IFN-gamma production.
/********************************************************************************* ** ** Copyright (c) 2017 The Regents of the University of California ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, this ** list of conditions and the following disclaimer. ** ** 2. 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. ** ** 3. Neither the name of the copyright holder 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 HOLDER 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. ** ***********************************************************************************/ // Contributors: // Written by <NAME>, for the Natural Hazard Modeling Laboratory, director: <NAME>, at Notre Dame #include "CFDcaseInstance.h" #include "CFDanalysisType.h" //#include "../AgaveExplorer/remoteFileOps/fileoperator.h" //#include "../AgaveExplorer/remoteFileOps/filetreenode.h" //#include "../AgaveExplorer/remoteFileOps/joboperator.h" //#include "../AgaveExplorer/remoteFileOps/joblistnode.h" //#include "../AgaveClientInterface/filemetadata.h" //#include "../AgaveClientInterface/remotedatainterface.h" //#include "../AgaveClientInterface/remotejobdata.h" //#include "cwe_interfacedriver.h" //#include "cwe_globals.h" #include "cfd_globals.h" /* CFDcaseInstance::CFDcaseInstance(const FileNodeRef &newCaseFolder): QObject((QObject *) cwe_globals::get_CWE_Driver()) { caseFolder = newCaseFolder; connectCaseSignals(); computeInitState(); } */ CFDcaseInstance::CFDcaseInstance(CFDanalysisType * caseType) //: QObject((QObject *) cwe_globals::get_CWE_Driver()) { myType = caseType; //connectCaseSignals(); computeInitState(); } CFDcaseInstance::CFDcaseInstance() //: QObject((QObject *) cwe_globals::get_CWE_Driver()) { //connectCaseSignals(); computeInitState(); } bool CFDcaseInstance::isDefunct() { return defunct; } CaseState CFDcaseInstance::getCaseState() { if (defunct) return CaseState::DEFUNCT; switch (myState) { case InternalCaseState::DEFUNCT : return CaseState::DEFUNCT; case InternalCaseState::DOWNLOAD : return CaseState::DOWNLOAD; case InternalCaseState::ERROR : return CaseState::ERROR; case InternalCaseState::OFFLINE : return CaseState::OFFLINE; case InternalCaseState::READY : return CaseState::READY; case InternalCaseState::INVALID : return CaseState::INVALID; case InternalCaseState::READY_ERROR : return CaseState::READY_ERROR; case InternalCaseState::EXTERN_FILE_OP : return CaseState::EXTERN_OP; case InternalCaseState::EMPTY_CASE : case InternalCaseState::RE_DATA_LOAD : case InternalCaseState::TYPE_SELECTED : return CaseState::LOADING; case InternalCaseState::PARAM_SAVE : case InternalCaseState::PARAM_SAVE_RUN : return CaseState::PARAM_SAVE; case InternalCaseState::COPYING_FOLDER : case InternalCaseState::INIT_PARAM_UPLOAD : case InternalCaseState::MAKING_FOLDER : case InternalCaseState::STARTING_JOB : case InternalCaseState::STOPPING_JOB : case InternalCaseState::WAITING_FOLDER_DEL : return CaseState::OP_INVOKE; case InternalCaseState::RUNNING_JOB : return CaseState::RUNNING; default: return CaseState::ERROR; } return CaseState::ERROR; } #if 0 const FileNodeRef CFDcaseInstance::getCaseFolder() { return caseFolder; } QString CFDcaseInstance::getCaseName() { QString ret; if (caseFolder.isNil()) return ret; return caseFolder.getFileName(); } #endif QString CFDcaseInstance::getCaseName() { QString ret ="Flow around a 3D building"; return ret; } CFDanalysisType * CFDcaseInstance::getMyType() { if (defunct) return NULL; return myType; } QMap<QString, QString> CFDcaseInstance::getCurrentParams() { QMap<QString, QString> ret; if (defunct) return ret; return storedParamList; } QMap<QString, StageState> CFDcaseInstance::getStageStates() { QMap<QString, StageState> ret; if (defunct) return ret; return storedStageStates; } #if 0 bool CFDcaseInstance::createCase(QString newName, const FileNodeRef &containingFolder) { if (defunct) return false; if (myState != InternalCaseState::TYPE_SELECTED) return false; if (cwe_globals::get_file_handle()->operationIsPending()) return false; if (!caseFolder.isNil()) return false; if (!expectedNewCaseFolder.isEmpty()) return false; newName = newName.replace(' ', '_'); expectedNewCaseFolder = containingFolder.getFullPath(); expectedNewCaseFolder = expectedNewCaseFolder.append("/"); expectedNewCaseFolder = expectedNewCaseFolder.append(newName); cwe_globals::get_file_handle()->sendCreateFolderReq(containingFolder, newName); if (!cwe_globals::get_file_handle()->operationIsPending()) { return false; } emitNewState(InternalCaseState::MAKING_FOLDER); return true; } #endif #if 0 bool CFDcaseInstance::duplicateCase(QString newName, const FileNodeRef &containingFolder, const FileNodeRef &oldCase) { if (defunct) return false; if (myState != InternalCaseState::EMPTY_CASE) return false; if (!containingFolder.fileNodeExtant()) return false; if (!oldCase.fileNodeExtant()) return false; if (cwe_globals::get_file_handle()->operationIsPending()) return false; if (!caseFolder.isNil()) return false; if (!expectedNewCaseFolder.isEmpty()) return false; expectedNewCaseFolder = containingFolder.getFullPath(); expectedNewCaseFolder = expectedNewCaseFolder.append("/"); expectedNewCaseFolder = expectedNewCaseFolder.append(newName); cwe_globals::get_file_handle()->sendCopyReq(oldCase, expectedNewCaseFolder); if (!cwe_globals::get_file_handle()->operationIsPending()) { return false; } emitNewState(InternalCaseState::COPYING_FOLDER); return true; } #endif bool CFDcaseInstance::startStageApp(QString stageID) { if (defunct) return false; //if (!caseFolder.fileNodeExtant()) return false; if (myType == NULL) return false; if ((myState != InternalCaseState::READY) && (myState != InternalCaseState::PARAM_SAVE_RUN))return false; if (storedStageStates.value(stageID, StageState::ERROR) != StageState::UNRUN) return false; QString appName = myType->getStageApp(stageID); QMultiMap<QString, QString> rawParams; rawParams.insert("stage",stageID); QString extraInput = myType->getExtraInput(stageID); if (!extraInput.isEmpty()) { QString addedInputVal = getCurrentParams().value(extraInput); if (!addedInputVal.isEmpty()) { rawParams.insert("file_input", addedInputVal); } } //RemoteDataThread * remoteConnect = cwe_globals::get_Driver()->getDataConnection(); //QString jobName = appName; //jobName = jobName.append("-"); //jobName = jobName.append(stageID); //RemoteDataReply * jobHandle = remoteConnect->runRemoteJob(appName, rawParams, caseFolder.getFullPath(), jobName); //if (jobHandle == NULL) { return false; } //runningStage = stageID; //runningID.clear(); //QObject::connect(jobHandle, SIGNAL(haveJobReply(RequestState,QJsonDocument)), // this, SLOT(jobInvoked(RequestState,QJsonDocument))); //emitNewState(InternalCaseState::STARTING_JOB); return true; } void CFDcaseInstance::computeInitState() { myState = InternalCaseState::OFFLINE; recomputeStageStates(); computeIdleState(); } void CFDcaseInstance::emitNewState(InternalCaseState newState) { if (defunct) return; if (newState == InternalCaseState::DEFUNCT) { defunct = true; } if (myState == InternalCaseState::ERROR) { return; } if (newState != myState) { myState = newState; recomputeStageStates(); emit haveNewState(getCaseState()); return; } if (recomputeStageStates()) { emit haveNewState(getCaseState()); } } void CFDcaseInstance::computeCaseType() { /* if (myType != NULL) return; const FileNodeRef varFile = caseFolder.getChildWithName(caseParamFileName); if (varFile.isNil()) return; if (!varFile.fileBufferLoaded()) return; QByteArray varStore = varFile.getFileBuffer(); QJsonDocument varDoc = QJsonDocument::fromJson(varStore); QString templateName = varDoc.object().value("type").toString(); if (templateName.isEmpty()) { return; } for (CFDanalysisType * aTemplate : *(cwe_globals::get_CWE_Driver()->getTemplateList())) { if (templateName == aTemplate->getInternalName()) { myType = aTemplate; return; } } */ } bool CFDcaseInstance::stageStatesEqual(QMap<QString, StageState> *list1, QMap<QString, StageState> *list2) { if (list1->size() != list2->size()) { return false; } for (auto itr = list1->cbegin(); itr != list1->cend(); itr++) { if (!list2->contains(itr.key())) { return false; } if (*itr != list2->value(itr.key())) { return false; } } return true; } bool CFDcaseInstance::updateStageStatesIfNew(QMap<QString, StageState> * newStageStates) { if (stageStatesEqual(newStageStates, &storedStageStates)) { return false; } storedStageStates = *newStageStates; return true; } bool CFDcaseInstance::recomputeStageStates() { //Return true if stage states have changed if (defunct) return false; if (myType == NULL) return false; QMap<QString, StageState> newStageStates; QStringList stageList = myType->getStageSequence(); CaseState currentState = getCaseState(); if ((currentState == CaseState::DOWNLOAD) || (currentState == CaseState::ERROR) || (currentState == CaseState::INVALID) || (currentState == CaseState::LOADING) || (currentState == CaseState::OFFLINE)) { StageState allStagesState = StageState::ERROR; if (currentState == CaseState::DOWNLOAD) { allStagesState = StageState::DOWNLOADING; } else if (currentState == CaseState::LOADING) { allStagesState = StageState::LOADING; } else if (currentState == CaseState::OFFLINE) { allStagesState = StageState::OFFLINE; } for (auto itr = stageList.begin(); itr != stageList.cend(); itr++) { newStageStates.insert((*itr), allStagesState); } return updateStageStatesIfNew(&newStageStates); } for (auto itr = stageList.begin(); itr != stageList.cend(); itr++) { newStageStates.insert((*itr), StageState::LOADING); } /* if ((caseFolder.isNil()) || (!caseFolder.folderContentsLoaded()) || (myState == InternalCaseState::STOPPING_JOB) || (myState == InternalCaseState::MAKING_FOLDER) || (myState == InternalCaseState::INIT_PARAM_UPLOAD) || (myState == InternalCaseState::COPYING_FOLDER) || (myState == InternalCaseState::WAITING_FOLDER_DEL)) { return updateStageStatesIfNew(&newStageStates); } */ if ((myState == InternalCaseState::STARTING_JOB) || (myState == InternalCaseState::RUNNING_JOB)) { if (runningStage.isEmpty()) { return updateStageStatesIfNew(&newStageStates); } if (newStageStates.contains(runningStage)) { newStageStates[runningStage] = StageState::RUNNING; } } //Check known files for expected result files for (auto itr = stageList.begin(); itr != stageList.cend(); itr++) { if (newStageStates[*itr] != StageState::LOADING) { continue; } /* FileNodeRef checkNode = caseFolder.getChildWithName(*itr); if (checkNode.isNil()) { newStageStates[*itr] = StageState::UNRUN; continue; } const FileNodeRef exitFile = checkNode.getChildWithName(exitFileName); if (exitFile.isNil()) { newStageStates[*itr] = StageState::ERROR; continue; } if (!exitFile.fileBufferLoaded()) { newStageStates[*itr] = StageState::ERROR; continue; } const QByteArray exitBytes = exitFile.getFileBuffer(); if (QString::fromLatin1(exitBytes) != "0\n") { newStageStates[*itr] = StageState::ERROR; continue; } newStageStates[*itr] = StageState::FINISHED; */ } for (int i = 0; i < stageList.length(); i++) { StageState prevState = StageState::FINISHED; StageState nextState = StageState::UNRUN; if (i != 0) { prevState = newStageStates[stageList[i-1]]; } if (i + 1 < stageList.length()) { nextState = newStageStates[stageList[i+1]]; } StageState nowState = newStageStates[stageList[i]]; if (nowState == StageState::UNRUN) { if ((prevState != StageState::FINISHED) && (prevState != StageState::FINISHED_PREREQ)) { newStageStates[stageList[i]] = StageState::UNREADY; } } else if (nowState == StageState::FINISHED) { if ((nextState == StageState::FINISHED) || (nextState == StageState::ERROR)) { newStageStates[stageList[i]] = StageState::FINISHED_PREREQ; } } } return updateStageStatesIfNew(&newStageStates); } void CFDcaseInstance::computeParamList() { //QJsonDocument varDoc = QJsonDocument::fromJson(varStore); QJsonDocument * varDoc = myType->getRawConfig(); QJsonObject varsList = varDoc->object().value("vars").toObject(); storedParamList.clear(); prospectiveNewParamList.clear(); for (auto itr = varsList.constBegin(); itr != varsList.constEnd(); itr++) { storedParamList.insert(itr.key(),(*itr).toString()); } } QByteArray CFDcaseInstance::produceJSONparams(QMap<QString, QString> paramList) { QJsonDocument ret; QJsonObject mainObject; ret.setObject(mainObject); QJsonValue typeStr(myType->getInternalName()); mainObject.insert("type",typeStr); QJsonObject params; for (auto itr = paramList.begin(); itr != paramList.end(); itr++) { params.insert(itr.key(), (*itr)); } mainObject.insert("vars",params); ret.setObject(mainObject); return ret.toJson(); } void CFDcaseInstance::computeIdleState() { //if (defunct) return; //if (caseDataInvalid()) //{ // emitNewState(InternalCaseState::INVALID); // return; //} //computeCaseType(); //emitNewState(InternalCaseState::RE_DATA_LOAD); //return; computeParamList(); runningStage.clear(); runningID.clear(); for (QString aStage : myType->getStageNames()) { /* const FileNodeRef childFolder = caseFolder.getChildWithName(aStage); if (childFolder.isNil()) continue; const FileNodeRef exitFile = childFolder.getChildWithName(exitFileName); if (exitFile.isNil()) { emitNewState(InternalCaseState::READY_ERROR); return; } if (!exitFile.fileBufferLoaded()) { emitNewState(InternalCaseState::READY_ERROR); return; } const QByteArray exitBytes = exitFile.getFileBuffer(); if (QString::fromLatin1(exitBytes) != "0\n") { emitNewState(InternalCaseState::READY_ERROR); return; } */ } emitNewState(InternalCaseState::READY); }
// +build go1.9 package apmsql import "database/sql/driver" type stmtGo19 struct { namedValueChecker driver.NamedValueChecker } func (s *stmtGo19) init(in driver.Stmt) { s.namedValueChecker, _ = in.(driver.NamedValueChecker) } func (s *stmt) CheckNamedValue(nv *driver.NamedValue) error { if s.namedValueChecker != nil { return s.namedValueChecker.CheckNamedValue(nv) } return driver.ErrSkip }
Federico Fellini Profile * Titles in Bold Type Will Air on TCM "There is no end. There is no beginning. There is only the infinite passion of life." -Federico Fellini No director captured "the infinite passion of life" as flamboyantly as Federico Fellini, the Italian director whose career spanned the birth of neorealism in the '40s and the rise of a more personal approach to filmmaking in the '60s. Indeed, his personal vision was so emphatic that critics created the term "Felliniesque" to describe his trademark mixture of decadence and eccentricity. Yet under all the Felliniesque glitter lay the passionate heart of a confirmed humanist, which may explain why his films have survived the test of time while others who merely exploited the changing values of the '50s and '60s have faded from memory. Fellini was a small-town boy, born to middle-class parents in Rimini, Italy, who ran away to join the circus at an early age. As a young adult, he set off for a different circus, Rome, in 1938, hoping to become a journalist. But his writing and the cartoon caricatures he created led him in a different direction, first to the theatre and radio and then into film. A friendship with actor Aldo Fabrizi brought him the chance to tour with his troupe in a variety of odd jobs, an experience he would draw on for his first directorial effort, Variety Lights (1950). When some of his short stories were adapted for the radio, he met the radio plays' leading lady, Giulietta Masina, whom he would marry and groom to be one of his greatest stars. Although Fellini had contributed gags to some films made in the early '40s, he first became seriously involved in film-making when director Roberto Rossellini approached him to help write the script for Open City, the 1945 film that would make Italian neorealism an international sensation. While Rossellini took ill while directing his next film, Paisan (1946), Fellini directed some scenes for him. That experience convinced him to move into directing. His first film was a collaboration with director Alberto Lattuada, who liked Fellini's script for Variety Lights enough to let him direct the actors while Lattuada handled the camera work. From the beginning, Fellini drew heavily on his own life and dreams, using his experience touring with Fabrizi's troupe as the basis for his first directorial effort. He became sole director with his second film, The White Sheik (1952), after refusing to let anyone else direct his script about a honeymooning couple whose relationship is complicated by the wife's infatuation with a comic-strip character. For this film, he drew on his early experiences writing for "fotoromanzi," which used photos of actors instead of drawings for its comic-book like narratives. Fellini had featured his wife in supporting roles in his first two films. For La Strada (1954), he promoted her to leading lady and scored an international sensation. As Gelsomina, a childlike waif sold into marriage with a traveling strong man (Anthony Quinn), she became the perfect embodiment of the innocence of the human spirit. With a popular score by Nino Rota, who would work with Fellini through the rest of his career, La Strada was an international hit that brought Fellini the first of his four Oscars® for Best Foreign Language Film. He repeated that success a year later with Le Notti de Cabiria, in which Masina played a romantic prostitute. That film would also inspire the hit Broadway musical Sweet Charity. The director moved into truly Felliniesque territory with his next film, La Dolce Vita (1960). In their first of several films together, Marcello Mastroianni served as Fellini's on-screen representation, a journalist both repelled and attracted by the decadence of Roman life. The identification between actor and character would deepen with Fellini's masterpiece, 8 1/2 (1963). This time, Mastroianni was a film director desperately trying to come up with an idea for his next movie while juggling relations with his wife (Anouk Aimee), his mistress (Sandro Milo) and an innocent young actress (Claudia Cardinale). The film brought Fellini his third Oscar® and inspired another hit Broadway musical, Nine, along with imitations by U.S. directors Woody Allen (Stardust Memories, 1980), Paul Mazursky (Alex in Wonderland, 1970) and Bob Fosse (All That Jazz, 1979). Fellini then presented the flip side of 8 1/2 with Juliet of the Spirits (1965), with Masina starring as a housewife at a loss over how to deal with her husband's infidelity. It was to be his last unqualified critical success. With later films (Fellini Satyricon in 1969, The Clowns in 1971, Fellini's Roma in 1972), critics thought he had allowed his personal vision to overpower his ability to reach an audience. Only Amarcord (1974), a series of reminiscences based on his youth in Rimini, brought a return to his earlier successes. The picture brought him his fourth Academy Award®. After that, his films scored a series of mixed successes. His last, La Voce della Luna (1989), has yet to find a U.S. distributor. Nonetheless, Fellini had one final triumph -- a special Oscar® presented to him in 1992. by Frank Miller
A Nation Engaged: Is This Still A Land Of Economic Opportunity? Enlarge this image toggle caption Maddie McGarvey for NPR Maddie McGarvey for NPR Americans who endured the brutal 2007-2009 recession and slow recovery now are seeing an economic sunrise: Wages are up, jobs are growing and more families are lifting themselves up out of poverty. And yet, dark clouds are still hanging over millions of Americans. No set of sunny statistics can help an unemployed coal miner in Kentucky pay the mortgage. Upbeat wage data won't reassure a Michigan factory worker who is nervously watching robots replace his co-workers. In this election cycle, candidates are responding to voters' anger and anxiety about an economy that — yes, has improved dramatically — but still feels uneven and unfair to many. In this week's installment of an election-year series, A Nation Engaged, NPR reporters will be talking to people about what they are experiencing in this 21st century economy. Are opportunities drying up for middle-class Americans? What policies can help build sturdier ladders for those who want to climb up? Enlarge this image toggle caption Maddie McGarvey for NPR Maddie McGarvey for NPR Much of the coverage will involve two cities in Ohio, a key swing state. There, Columbus and Springfield sit near the state's center, roughly 45 miles apart. Despite that proximity, their prospects have moved in opposite directions. Since 1970, Springfield's population has declined about 27 percent, while Columbus' has grown by about 57 percent. Springfield's paychecks have withered too. Between 1999 and 2014, median incomes fell an astounding 27 percent in Springfield, according to a recent study by the Pew Research Center. That study also found that in this century, the share of lower-income adults rose from 21 percent to 32 percent in Springfield. In contrast, Columbus has been booming. Last year, for example, it recorded the highest average hourly earnings gain — 6.2 percent — in the entire country, beating out even San Francisco. toggle caption Maddie McGarvey for NPR Before focusing on those two Ohio cities, let's get ourselves oriented. Here's the scene nationwide: In such an immense economy with 324 million people, you can always find a mix of hard times and good times. This year for example, farm incomes have been plunging and tech paychecks soaring. But overall, the economy is improving. A new U.S. Census Bureau report, released last week, showed that in 2015, U.S. incomes surged, rising 5.2 percent from a year earlier. After adjusting for inflation, median household incomes were up $2,800, to $56,500. That was the single biggest one-year jump since the Census Bureau started collecting that data in 1967. That's great news, but median household incomes are still 1.6 percent below the 2007 pre-recession level. And they remain 2.4 percent below the all-time high reached in 1999. The poverty rate in 2000 was just 11.3 percent. In 2015, it was 13.5 percent — meaning millions of people who used to be middle class are now poor. In fact, the wage squeeze has been so sustained that a Pew study done earlier this year found middle-income Americans are no longer in the majority. In 1971, about 2 out of 3 Americans lived in middle-income households. Today, less than 50 percent of households can be called middle income; a slight majority are either upper income or lower income. All of these numbers may leave you feeling confused, and that's understandable because much of it is conflicting. So here's what you can take away: The U.S. economy is in far better shape than during the Great Recession. Today, it has a record 5.9 million jobs open, a stable 4.9 percent unemployment rate and rising wages. But large swaths of Americans no longer are secure in the middle class. What about the future? Perhaps if the economy stays on track for a few more years, those insecure Americans will see better times. Optimists note that in the last two years, middle-wage jobs — at least those outside of coal country and the oil patch — have improved as employers have added carpenters, truck drivers, installers and such. Also, many state and local minimum wage laws have pushed up paychecks in the last couple of years. But pessimists fear the middle class is about to shrink much further. They point to employers' growing use of robots, artificial intelligence and other types of automation. Among the vulnerable workers may be truck drivers, bank tellers, cab drivers, secretaries, paralegals and assembly line workers. Join NPR and member station reporters as they explore questions about economic opportunities — and the policies that may help as new technologies and global trends continue to reshape the American workplace. Here are examples of efforts to help workers: More will be coming, but these are stories NPR already has offered. They help illustrate constructive approaches to increasing economic opportunities. Here's a sampling:
/** Create a componentOf between whole and part types */ public static componentOf createComponentOf (Classifier whole, int wholeLower, int wholeUpper, String name, Classifier part, int partLower, int partUpper, RefOntoUML.Package container) { componentOf compOf = factory.createcomponentOf(); List<Property> ends = createAssociationEnds(compOf, whole, part); setMultiplicity(ends.get(0), wholeLower, wholeUpper); setMultiplicity(ends.get(1), partLower, partUpper); if(name!=null) compOf.setName(name); else compOf.setName(""); if(container!=null)container.getPackagedElement().add(compOf); return compOf; }
/** * Top-level Item that can have child SubItems. */ private static class TopItem extends Item { private final TopComponent tc; private final Item[] subItems; private final Item activeSubItem; public TopItem( TopComponent tc ) { super( extractDisplayName( tc ), tc.getToolTipText(), extractIcon( tc ), false ); this.tc = tc; Item[] subItems = null; Item activeSubItem = null; TopComponent.SubComponent[] subs = tc.getSubComponents(); if( null != subs && subs.length > 0 ) { for( TopComponent.SubComponent sc : subs ) { if( sc.isActive() ) { activeSubItem = new SubItem( tc, sc ); break; } } subItems = new Item[null == activeSubItem ? subs.length : subs.length-1]; int index = 0; for( TopComponent.SubComponent sc : subs ) { if( sc.isActive() ) continue; subItems[index++] = new SubItem( tc, sc ); } } this.subItems = subItems; this.activeSubItem = activeSubItem; } @Override public void activate() { tc.requestActive(); } @Override public boolean hasSubItems() { return null != subItems; } @Override public Item[] getActivatableSubItems() { return subItems; } @Override public boolean isTopItem() { return true; } @Override public Item getActiveSubItem() { return activeSubItem; } @Override public boolean isParentOf( Item child ) { if( null != subItems ) { for( Item sub : subItems ) { if( sub == child ) return true; } } return null != child && child == activeSubItem; } }
A causal and continuous interpretation of the quantum theory: About an original manuscript by David Bohm sent to Louis de Broglie in 1951 The aim of this article is reproduce and analyze an original article of David Bohm sent to Louis de Broglie in 1951. This article is the older document of David Bohm about his well known hidden variable theory based on the pilot wave interpretation of Louis de Broglie. We analyse the chronology and the history of this fascinating document. The present article reproduces and studies an undated and apparently non analyzed manuscript untitled 'A causal and continuous interpretation of the quantum theory' sent to Louis de Broglie by David Bohm in the year 1951 and concerning a pilot-wave quantum theory nowadays universally called de Broglie-Bohm interpretation or 'Bohmian mechanics'. This text (referred here as ACCIQT) was found by us in the Archive Louis de Broglie at the French Academy of Science and has gone unnoticed until now . From its content we believe this short text to be a primitive version of the two famous articles 'A suggested interpretation of the quantum theory in terms of hidden variables. I and II' submitted together to the Physical Review the 5 th of July 1951 and published the 15 th of January 1952 in the same volume . The paper is organized as follows: First, in section II we reproduce the manuscript (a pdf version will be available XXXX). In section III we discuss the chronology of this manuscript and in section IV we analyse the physical contents and implications of ACCIQT for the understanding of Bohm work on hidden variables published in 1952 . Finally, we conclude by relating and connecting ACCIQT with the more general work done by Bohm in order to understand and grasp the mystery of quantum mechanics II. A CAUSAL AND CONTINUOUS INTERPRETATION OF THE QUANTUM THEORY: (ACCIQT) David Bohm Faculdade de Filosofia, Ciencias e Letras, Universidade de São Paulo, Sao Paulo, Brasil The usual interpretation of the quantum theory is based on the assumption that at the atomic level, the laws of nature are intrinsically statistical, in the sense that no more fundamental theory is possible that could causally and continuously account for quantum fluctuations in terms of at present "hidden" variables or parameters. This assumption leads to an extremely far-reaching change in our concepts concerning the nature of matter; for it requires us to renounce the possibility of even conceiving in precise terms of the behavior of an individual system at a quantum level of accuracy Ref. (1). This change in our con-cepts is justified in part by its success in accounting for a very wide range of experimental phenomena, at least in the domain of distances larger than 10 −13 cm., and in part by the widely accepted belief that no consistent causal and continuous interpretation of the mathematical equations of the quantum theory can possibly lead to the same results as those of the usual interpretation. In this note, however, the author wishes to call attention to an alternative interpretation of the quantum theory, which leads to all, of the experimental results predicted by the usual interpretation, but which permits us to retain the concept of a precise causal and continuous description of the motion of an individual material system, even at a quantum level of accuracy. This interpretation, which is reported in detail elsewhere Ref. We begin by regarding the electron as a particle having a precisely defined position and momentum at each instant of time. This particle is always accompanied, however, by a wave field, which we call the Ψ-field, and which satisfies Schrödinger's equation. This field exerts a force on the particle, which is derivable from a "quantum-mechanical" potential, The equations of motion of the particle are then given by: where V is the usual classical potential. It is the above "quantum-mechanical" potential that leads to all the characteristically new quantum-mechanical effects, and the classical limit is obtained when the effects of this potential on the particle can be neglected. The above equations of motion must, however, be supplemented by two mutually consistent assumptions. First, if we write Ψ = R(x)e iS(x)/ , where R and S are real, then the momentum of the particle is restricted to p = ∇S(x). This assumption is consistent in the sense that if it holds at a given time then the equations of motion 2.2 guarantee that it will hold for all time. Thus it it essentially a subsidiary condition. Secondly, we must assume that we do not in practice predict or control the exact location of the particle, but that we have a statistical ensemble with a probability density of P = |Ψ| 2 . The assumption of this ensemble is also consistent, in the sense that if it holds initially, then the equations of motion guarantee that it will hold for all time. The need for a statistical ensemble originates in the chaotic character of the particle motion (resembling Brownian motion), which arises whenever the particle interacts with other systems. Even if the initial position and momentum were known with perfect accuracy, the particle would soon diffuse over the entire region in which |Ψ| was appreciable. Moreover, its motion would be so complicated that in practice we would be able to predict only the probability of a given location. It can be shown that after sufficient interactions have taken place, the probability density will tend to approach P = |Ψ| 2 . Thus, the use of a statistical ensemble is here very similar to its use in classical statistical mechanics, where the statistical treatment is likewise made valid by the chaotic character of molecular motions brought about by collisions. It is shown that with these assumptions, we can describe in a causal and continuous way all of the results obtained from the usual interpretation. For example, in the photoelectric effect, the transfer of a full quantum of energy to an atom in a short time by a very weak electromagnetic wave is made possible by the "quantum-mechanical" potential, which is not necessarily small when the wave amplitude is small (because this amplitude appears in the denominator of the potential). As a result, even in a wave of low amplitude, rapid and violent fluctuations of the potential occur, which can transfer a full quantum of energy in a time so short that the process appears in the usual observations to be discontinuous. The actual course of this transfer is in principle determined by the precise values of all the potentials at each point in space and time, but these potentials vary in such a chaotic way that in practice we can predict only the probability that a transfer will take place. As long as the equation governing the Ψ field (Schrödinger's equation) is linear and homogeneous, then our alternative interpretation leads to precisely the same results for all experiments as are given by the usual interpretation. However, in our interpretation, it is consistent to contemplate modifications in the mathematical theory which could not consistently be made in the usual interpretation. For example, we can consider equations governing Ψ which are non-linear and inhomogeneous, and which depend on the actual location of the particle. Moreover, the above modifications can be so chosen that they produce negligible changes in the atomic domain, where the present theory is known to be a good approximation, but significant changes in the domain of distances of the order of 10 −13 cm, where present theories do not seem to be adequate. It is thus entirely possible that a correct theory of elementary particles will require the introduction of a causal and continuous interpretation of the quantum theory, such as the one described here. no mathematical modifications of the types described above are made, the uncertainty principle is obtained as a practical limitation on the precision with which complementary variables such as position and momentum can be measured. However, if the mathematical formulation neeeds to be changed in almost any conceivable way in any domain (for example, at small distances), then measurements of unlimited precision can be shown to be possible in every domain, including even those domains in which the present form of quantum theory is a good approximation. Our interpretation introduces what are essentially "hidden" causal parameters; namely, the precisely definable particle positions and momenta which do not appear ia the usual interpretation, but which along with the Ψ field Ref. (3) determine in principle the actual results of each individual measurement process. At first sight, the existence of such "hidden" causal parameter would appear to contradict von Neumann's proof that no single statistical distribution of "hidden" causal parameters could possibly account for all of the results of the usual interpretation of the quantum theory Ref. (4). Von Neumann's proof is based, however, on the implicit assumption that the 'hidden" parameters are all in the observed system and not in the measuring apparatus. But in our interpretation, the "hidden" parameters are also in the measuring apparatus. Since different kinds of apparatus are needed in different kinds of measurements, the hidden parameters that determine the results of a momentum measurement differ from those which determine the results of a position measurement. Von Neumann's theorem therefore does not apply to our interpretation. After the work reported here had been completed, the author's attention was called to a similar interpretation suggested by de Broglie in 1926, but given up by him because of certain difficulties in the interpretation of a superposition of stationary state wave function Ref. (5). De Broglie, however, did not carry his ideas to their logical conclusion Ref. (6). The essential new steps needed were to improve the treatment of the problem of two bodies, and to construct a theory of measurements with the aid of the new interpretation. When these two steps are made then it can be shown that this interpretation leads to precisely the same results as are obtained with the usual interpretation. To sum up, we have developed a causal and continuous interpretation of the quantum theory. Such an interpretation is not only of general philosophical interest, but also has a possible significance for the development of new theories in those domains in which the present theory is inadequate. , the story is also recounted in Bohm's biography written by David Peat (see also and which include other recollections of the whole story by Bohm, and finally Max Jammer book and article ). The main subject of the discussion concerned the EPR paradox which was analyzed in Bohm's Book. Einstein felt unconvinced by the 'orthodox' analyzes made by Bohm who at that time still accepted the orthodox view taught by Niels Bohr and others concerning the general interpretation of quantum mechanics. In particular, Einstein's 'objections were that the theory was conceptually incomplete, that this wave function was not a complete description of the reality and there was more to it than that' . After the discussion Bohm changed his mind and started thinking about an alternative description of quantum mechanics which would preserve the classical credo of realism and causality advocated by Einstein . The results of his work was a version of the pilot-wave theory already discovered by de Broglie in 1927. However, at that time Bohm apparently ignored the priority of de Broglie. In a letter to astrophysicistÉvry Schatzman (who was in touch with Jean Pierre Vigier and de Broglie) Bohm summarized: 'Finally, I decided for a causal interpretation within few weeks, I hit upon the idea which I published not knowing about de Broglie's work until later ' . In the same letter Bohm also confirmed the importance of the EPR paradox in the whole affair. We now remind that in 1925 after completing his doctorate thesis de Broglie sought deeper for a mechanical deterministic model able to explain the wave-particle dualism of quantum matter. He then proposed an approach known as the 'double-solution program' in which the quantum particle is a point-like object generating an extended u-wave which subsequently guides and affects its motion during propagation around obstacles and external potentials . The model was mathematically too ambitious at that time (the issue is still unsolved nowadays, for recent reviews see ). Therefore, in 1927 at the 5 th Solvay Congress in Brussels he instead presented the simpler pilot-wave model in which the point-like particles are guided by the Ψ-wave solution of Schrodinger's equation in the many-particle configuration space (see also Kennard contribution ). However, due to several technical reasons (some of them being discussed later) de Broglie abandoned his theory after 1928-30. He went back to it (i.e., within the context of the double-solution theory) only 25 years later after the publication of Bohm's articles and the strong implication of Vigier in the collaboration to the double-solution program. Moreover, we stress that de Broglie was already prepared to change his mind as visible for instance in the evolution of his university-lecture notes during the period 1950-1951 which were later published in a book as a historical legacy . Interestingly this book contains some early negative reactions to a version of Bohm manuscript sent to de Broglie during the summer 1951 and a brief criticism of the pilot-wave theory . Back in 1951, Bohm's wrote a draft summarizing his ideas and during the summer sent a version to several known physicists including Einstein, Pauli and de Broglie . Following the draft contained only a treatment of the single particle case. As Bohm wrote his preliminary theory was complete 'at least in a one particle system which is as far as I got at that time' , p.36. Pauli answered very quickly criticizing the full hidden variable approach and commenting to Bohm that: 'It was old nonsense that de Broglie had done in 1927. They'd had the Solvay Congress there and that he had demolished de Broglie there' . One of the famous objection given by Pauli concerned the interaction between an incident particle non-elastically scattered by a Fermi rotator. De Broglie had already sketched the good answer in 1927 based on the limited extension of wavepackets in the configuration space But in his letter to Bohm Pauli probably presented it as a fatal objection to de Broglie 'which sort of really knocked him out' . De Broglie also answered to Bohm explaining that he already developed the idea in 1927 and abandoned it in part due to Pauli's objections and mostly for others more fundamental reasons related to the measurement theory and the notion of wave-function collapse in quantum mechanics. The objections of de Broglie (recollected in ) are interesting and are already given in his 1930 review of the pilot-wave theory . First, there is the question concerning the interpretation of 'empty branches' of the Ψ-wave after scattering processes. Indeed, in the usual interpretation these empty waves collapse and have no subsequent physical effect. De Broglie wrote: 'it is difficult to conclude otherwhise that the wave is not a physical phenomenon in the old sense of the word ' . We stress that de Broglie's reasoning is a direct consequence of a discussion made by Einstein at Brussels in 1927 when he objected that: 'But the interpretation, according to which |Ψ| 2 expresses the probability that this particle is found at a given point, assumes an entirely peculiar mechanism of action at a distance, which prevents the wave continuously distributed in space from producing an action in two places on the screen' , p. 441. Here, is clearly seen an issue with non-locality which rebutted both Einstein and de Broglie. As a second reason given by de Broglie for criticizing the pilot-wave theory, there is the problem of the energy conservation during scattering since in general the quantum potential responsible for the quantum effects is time dependent. The source of this quantum energy is thus questionable. However, de Broglie emphasized that as soon as the scattering ends up one will find one and only one of the energy allowed by the standard quantum interpretation. Still, he doubted about this picture and wrote: 'herein lies one of the essential differences between the pilot-wave theory and the point of view of Bohr and Heisenberg' . In the 1950's he added that the EPR paradox is not completely solved within the pilot-wave framework because the collapse of the empty branches corresponding to alternatives which are not realized assume nonlocality which de Broglie, like Einstein, abhorred as mentioned before. It is probable that de Broglie shared some of his doubts and frustrations with Bohm in his letter (as revealed in the Bohm-Pauli correspondence ). After receiving these letters of de Broglie and Pauli Bohm talked once again to Einstein who also confirmed de Broglie priority: Einstein like Pauli was present at the 1927 Solvay Congress and he was one of the few, with Brillouin, not to oppose directly to the pilot-wave interpretation contrarily to Pauli who gave detailed objections . Einstein had his own objection to Bohm's theory also discussed in a slightly different form at the Solvay Congress: two letters of Bohm to Einstein of 1951 mention this issue which concerned the interpretation of stationary states for the single-electron motion in a one dimensional box. Indeed, Bohm's theory implies a single-particle resting in the box with null velocity v = ∇S/m = 0 and this even for high energy levels in mere contradiction with the classical intuition and the correspondence principle. This issue became the subject of section 5 in (mirroring the two Bohm's letters of 1951 ) and was subsequently discussed by Einstein, Bohm and de Broglie in at the invitation of Einstein. From that moment we know that Bohm strategy was to complete his first draft in order to reply to the objections made by Pauli at Brussels (and subsequently by de Broglie in a book published in 1930 ) and therefore to carry some new elements to the discussion for the many-body problem . This was clearly one of the main subject of the Bohm-Pauli correspondence during this period . The second issue focused on the paternity of the pilot-wave theory. The final version in particular contained a theory of quantum measurements for the many-particle system which allowed Bohm to answer most of the questions raised by Pauli and de Broglie. We further know from a reply of Pauli written in December 1951 that Pauli urged Bohm to recognize the priority of de Broglie concerning the pilot-wave theory . Pauli wrote: 'It should be also stated that de Broglie had formulated already the quantumpotential energy ' . This letter was one of the last of a long correspondence between Pauli and Bohm concerning this manuscript. We stress that while several of Bohm's letters were recovered only one of Pauli survived and the annotated manuscript by Pauli was lost. While Bohm resisted for a while to admit it he finally acknowledged the priority of de Broglie but only after emphasizing that: 'If one man finds a diamond and then throws it away because he falsely concludes that it is a valueless stone, and if this stone is later found by another man who recognize its true value, would you not say that the stone belongs to the second man? ' Letter 1290 from October 1951 in . It is interesting to note that the same 'diamond' parabolic saying was also sent by Bohm gives full references to previous publications by de Broglie and Madelung (but not by Rosen which will be added in the final version ). This added notes result probably from the interaction between Bohm and Pauli and Bohm and Einstein. It should be emphasized that ACCIQT starts with a single-particle analysis like in the first version sent to Pauli and de Broglie (as explained by Bohm himself ). This shows that the ACCIQT draft was combining some elements of the first paper with new ideas to be developed in a subsequent manuscript . Moreover, Bohm underlined some words in order to emphasize their importance (we go back to this issue in Section IV). Similar words are also employed in the letter of Bohm to Schatzman and they clearly refer to answers of criticisms made by Pauli and de Broglie . We now go back to the chronology issue. From our inquiry we thus know that the paper ACCIQT sent to de Broglie at least after the start of August was written after Bohm's letter ii) Where did Bohm submit this work? We will try to propose answers to this difficult question afterward. Clearly, to answer the first question it is important to remind that the interactions between Bohm and de Broglie at that time were complicated by this priority issue. In Bohm comments that: 'I have heard also that de Broglie has recently published an article on the subject, which I have no yet time to read. I recently received a letter from de Broglie in which he took great pains to claim credit for the ideas. My answer to him was to admit that he suggested the method in 1926, but to point out that because he did not carry it to its logical conclusion he came to the erroneous conclusion that the idea does not work ' . The paper of de Broglie was the note to the Academy of Science of September 1951 in which de Broglie after thanking Bohm for sending him a draft of his work subsequently recalled his unarguable priority and at the same time criticized the pilot-wave theory for being too abstract to be realistic. In a English edition of his book 'Physics and Microphysics' de Broglie added that he just received the work of Bohm and that he still found the pilotwave theory too crude and abstract since: 'Reflecting de novo on these problems, it always appears to me that this last form of my ideas of 1927 is impossible to accept; if we return to the objectivistic point of view of classical physics, we could not, in effect, admit that a corpuscle would be guided in its movement by a Ψ-wave of wave mechanics since this Ψ-wave is only a representation of probabilities.' . De Broglie subsequently explained that the double-solution theory, i.e., with u-waves propagating in the 3D space, is more physical and therefore closer to a realistic and causal description of nature than the pilot-wave model involving 'fictitious' Ψ-fields. The approach followed by de Broglie was certainly closer in spirit to the one made by Einstein and this clearly appeared in subsequent works done together with Vigier where the analogy with general relativity played a fundamental role in the attempts to develop the double solution program in the 1950's (for recollections concerning these issues see . Unfortunately, the paper never appeared in Nature and this is perhaps related to the ambiguous reception by Massey. This is as far as we were able to go concerning the chronology and history of ACCIQT. In the next section we will consider and analyze more in details the physical content of this manuscript. IV. CONTENTS OF THE MANUSCRIPT The manuscript ACCIQT starts with a condensed description of the pilot-wave theory for a single electron. The Newtonian (i.e., second-order) law of motion for a quantum point-like electron reads is the famous quantum potential. Bohm's stresses the role of the additional assumption p = m d dt x = ∇S(x(t), t) which will be more detailed in the longer work in preparation cited as reference 2 in the manuscript ACCIQT. Moreover, Bohm emphasizes in several places in ACCIQT that the new theory 'leads to precisely the same results for all experiments as are given by the usual interpretation'. This was clearly a point of disagreement with Pauli and de Broglie at that time and the same response was enlighten in the letter of Bohm to Schatsman concerning the longer manuscript announced in December 1951. The fact that the new theory is empirically equivalent to the orthodox one relies on a description of many-body interactions like for the photo-electric effect which is mentioned in the manuscript. While this is very sketchy in ACCIQT more detailed analysis is promised by Bohm in the longer work announced for December 1951 (i.e., as reference 2 in ACCIQT). It is remarkable that no single word is devoted to Pauli's famous objection made during the Solvay Congress and concerning the Fermi rotator interacting with a second particle. Neither the manuscript discusses the EPR paradox which will be analyzed in . In place there is a discussion of the famous von Neumman no-go theorem which conflicts with the mere existence of Bohm's theory. Bohm affirms that in his theory hidden variables must also be assigned to measurement apparatus and that this provides a loophole in von Neumann's proof. This naturally means that macroscopic systems such as apparatus and observers are described by the same dynamics and theory as the observed systems. In other words, the qualitative separation or 'shift' between observed and observers which lies at the core of the orthodox interpretation vanishes completely in the hidden-variable theory presented by Bohm. A similar claim was developped in the second 1952 published article . We now know that the von Neumann's proof relies on some unwarranted additivity assumptions which were clearly identified and debunked by John Bell in 1966 (and before that by Grete Hermann in 1935 ). The analysis of Bohm can therefore only have a qualitative value. It should be emphasized that de Broglie also published his own criticism of von Neumann's theorem in his note of September 1951 . One very interesting point raised by de Broglie against von Neumann's theorem is a proof by contradiction (reductio ad absurdum): the mere existence of the pilot-wave theory shows that von Neumann's proof is generally wrong. De Broglie also included a discussion of quantum measurements. Following his discussion von Neumann's theorem fails because the different statistics associated with measurements of complementary observables such as position x and momentum p can not be obtained in the same experiment whereas in the pilot-wave theory the actual position of the particle x(t) plays a fundamental role imposing the probability of presence |Ψ(x)| 2 dx as more fundamental and valid at any time (de Broglie analysis is further developed in ). Likewise, the analysis of de Broglie (like the one made by Bohm) is very general and doesn't identify the specific mathematical issue invalidating the generality of von Neumann's proof. In retrospect, when we re-analyze de Broglie and Bohm criticisms of von Neumann's proof with the results obtained by Hermann and Bell we see that indeed the pilot-wave theory contradicts the additivity assumptions made by von Neumann. In the same context, ACCIQT contains a still sketchy argumentation concerning the measurement theory which will be extended in the final papers of 1952. This measurement theory is generally considered to be a key contribution of Bohm in . We stress that quantum measurements were already analyzed by Bohm in from a Bohrian orthodox perspective. Therefore, Bohm was well designated to develop a measurement theory for the pilot-wave interpretation. From Bohm's interview we know that it is only after discussing with Einstein that Bohm decided to discuss measurement processes in response to Pauli's objections. Again, this suggests that the manuscript ACCIQT was already a modified and hybrid version of the original one sent to Pauli, Einstein and de Broglie. Generally speaking, Bohm tried to emphasize the novelty and superiority of his work in ACCIQT compared to de Broglie's study by underlining some words such as 'all, individual, practical, every...' playing a key role in the message of the paper. For example the opposition between 'individual' and 'intrinsically statistical' emphasizes the novelty of the causal interpretation with respect to the orthodox interpretation limited to statistical ensembles and neglecting individual systems. It is important to stress that this dilemma was at the core of Einstein criticisms of the orthodox quantum interpretation. For example in his popular book written with Leopold Infeld the comparison is made between quantum statistical mechanics and statistics in classical physics. Here they wrote : 'But in quantum physics the state of affairs is entirely different. Here the statistical laws are given immediately. The individual laws are discarded ' . It should be emphasized that in a letter written in October 1951 Bohm commented some important changes made in the much longer version sent to Pauli probably before July (see letter 1290 in ). One of these changes concerns discussions of a 'molecular chaos' hypothesis whose importance was weakened in the version sent to Pauli and in the final articles of 1952. In the letter to Pauli Bohm explained that he doesn't 'need to use molecular chaos' to justify Born's rule P (x) = |Ψ(x)| 2 . Indeed, as shown by Bohm the Born rule holding true at one time will be so at any other time (this is done in analogy with Liouville theorem's in classical mechanics). This idea was already known by de Broglie in 1926 who however tacitly assumed the equality P (x) = |Ψ(x)| 2 . Still, this molecular chaos hypothesis is clearly discussed in ACCIQT as a key ingredient in the theory (even though not necessary). More precisely, in ACCIQT Bohm mentions (in connections with molecular chaos) the possibility that Born's rule P (x) = |Ψ(x)| 2 relies on the chaotic Brownian motions of particles interacting with other systems. Moreover, in ACCIQT Bohm affirms that 'it can be shown that after sufficient interactions have taken place the probability density will tend to approach P (x) = |Ψ(x)| 2 ' (in the second 1952 article Bohm mentions the existence of a H-theorem reminiscent of Boltzmann's theory for justifying the tendency to reach statistical equilibrium). We can also point out that in ACCIQT a too fast reading could have easily led Pauli to believe that the diffusion and relaxation process linked to molecular chaos are essential and not contingent to the theory. Bohm's explanation in his letter to Pauli was intended to be clarifications of these misunderstandings. In his October letter Bohm wrote : 'Thus the complicated and chaotic motion that occurs in interaction, to which you and de Broglie objected so strongly, is just what is needed to establish the ensemble P = |Ψ| 2 . It is therefore something that is desirable in the theory' (letter 1290 in ). The final version of 1952 clarified this misunderstanding by emphasizing more cautiously what is central and what is not. Once again, this discussion strongly suggests that ACCIQT was a still primitive version of the 1952 paper very similar to the original manuscript. Furthermore we remind that all these important ideas of Bohm were actually further developed in papers written in 1953 , and in 1954 conjointly with Vigier , and in a book published in 1957 but we saw that these ideas were already discussed and partly understood in 1951. Interestingly, Pauli came back to the issue about probabilities in an article written in honour of de Broglie in 1953 where he again claimed that Born's rule is not justified in the pilot-wave theory (interestingly Pauli didn't question de Broglie directly but focused his critical work on Bohm). A final ingredient of ACCIQT was to suggest some empirical differences between his theory and the standard approach. Bohm's suggested new features occurring at physical scales below 10 −13 cm where non-linearities could modify the law of motions. Similar suggestions were developed in all Bohm's subsequent works. This point is indeed crucial for Bohm since a difference with standard quantum mechanics would allow him to reply to criticisms made by those like Pauli and Heisenberg claiming that the theory is purely metaphysical. Pauli for instance called this hypothesis 'a check which can not cashed ' whereas Heisenberg ironically quoting N. Bohr compared Bohm's program to the 'hope that it will later turn out that sometimes 2 × 2 = 5 for this would be of great advantage for our finance' . In particular the uncertainty principle mentioned in ACCIQT could lose his general validity. This issue became the core of the collaboration in the 1950's and 1960's between Bohm, Vigier, and de Broglie who all accepted the idea of a complex 'sub-quantum dynamics' strongly affecting the microscopic quantum evolution . De Broglie expected very much from the Bohm-Vigier work and was delighted by the new possibilities. In the preface to Bohm's book he wrote: 'One can it seems to me, hope that these efforts will be fruitful and will help to rescue quantum physics from the cul-de-sac where it is at the moment' . Clearly, the ACCIQT manuscript of 1951 is a precious one since it reveals some of the early fundamental ideas and concepts of Bohm to be developed during the rest of his life. V. CONCLUSION: BOHM AND THE IMPLICATE ORDER As we saw, the manuscript ACCIQT contains already many of the key elements to be discussed by Bohm in his subsequent works. Most importantly, the draft discusses the role of statistics and stochasticity (i.e., how to justify Born's rule) and the possibility of new physics in the sub-nuclear regime below 10 −13 cm, where present theories do not seem to be adequate (probably nowadays we would better consider the Planck length 10 −33 cm as a typical scale where gravitation is going to play a critical role in quantum physics). The ideas of Bohm in ACCIQT also included the role of man-body interactions which are only briefly sketched (in particular in relation with the von Neumann no-go theorem). Later, development emphasized the role of non-locality which is already discussed in in connection with the EPR paradox. One of the key element for Bohm during the 1950's was the role played by Marxism and by the book Materialism and Empirio-criticism written by Lenin in 1908 . In this book about dialectical materialism Lenin strongly criticized the positivism of Ernst Mach and strongly supported causality for a clear description of matter in space and time. The reject of positivism by Bohm is already very clear in the manuscript ACCIQT where the word causal appears in the title. The criticism of Mach and positivism was more detailed in the 1952 articles and in his book Causality and Chance in Modern Physics . In that book Bohm described his approach of an infinity of levels where he conceived mechanism and strict determinism a la Laplace as only a first approximation for a causal theory. Bohm saw the presence of stochastic elements as a sign that the theory of the Universe must be scale dependent (a topic which also played a role in his research in condensed matter physics, i.e., related to the development of the theory of renormalization in connection with collective quantum excitation in plasma: the so called plasmons). In his frame work, which was also advocated by his Marxist friends Vigier and Schatzman (see for a clear discussion), the presence of stochastic elements corresponded to an approximation for a causal and realistic underlying physics, i.e., at the sub-quantum level. Yet, for Bohm it became clear that at such lower scales and higher energies the structure of physical laws should not re-establish the strict determinism of classical physics. Instead, Bohm conceived the existence of a new emerging set of laws applicable to the lower spatial scales and still containing random and stochastic elements mixed together with deterministic rules. This is a bit like in Langevin's description of Brownian motion where a random and fluctuating force η is added to the classical force F in the Newtonian dynamics mẍ = F + η. This process was for Bohm infinite, meaning that new laws and properties emerged at different scales (the idea generalized some early speculations made by Lenin about 'the inexhaustible electron' ). Moreover, for Bohm, additionally to stochastic elements, the presence of a quantum potential U = − 2 2m ∇ 2 |Ψ| |Ψ| was a completely new feature which emphasized collective and nonlocal properties without classical counterpart. Indeed, for Bohm this quantum potential was not completely mechanical in the sense that its intensity doesn't fall out with the distance and this is very different from classical force like Newtonian gravitation or electromagnetic forces which strongly decay with the distance between particles. Also, this strange potential only depends on the local form of the wave function but not on its absolute amplitude (i.e., the multiplication of |Ψ| by a constant doesn't change U). For Bohm, like in his work with plasmons, this non-local and collective feature was a specificity of the new quantum order. However, the early model proposed in the 1950's was progressively abandoned by Bohm in the 1960-70's because of too much arbitrariness in the choice for the new quantum dynamics (this was reminiscent of criticisms already made by Pauli, Einstein and de Broglie). Instead, Bohm emphasized that the mere existence of the pilot-wave model is at least possible. As Bohm wrote in 1962 in a comment to Heisenberg's 1958 book : 'While trying to find a way to remedy the absence of 'actuality function' he developed a definite example of an alternative interpretation, which permitted the quantum theory to be extended so as to include them in a logically consistent way' . In other words, the pilot-wave model Bohm developed in 1951-52 already shows the possibility for an alternative causal quantum dynamics, i.e., clearly violating the usual Copenhagen credo that no such a model is even conceivable (a point which was also stressed by de Broglie in 1951 ). This minimalist view was often accepted and used by proponents of the so-called 'Bohmian mechanics'. For example Bell wrote: 'Why is the pilot wave picture ignored in text books? Should it not be taught, not as the only way, but as an antidote to the prevailing complacency? To show that vagueness, subjectivity, and indeterminism, are not forced on us by experimental facts, but by deliberate theoretical choice? ' . However, it is central to recognize that this choice of a minimalistic interpretation was for Bohm like for de Broglie only a temporary expedient. Contrarily to widespread beliefs Bohm was not a proponent of Bohmian mechanics: His approach should better been named Bohmian non-mechanics since a return to strict determinism is not expected. In the same article of 1962 Bohm explained that in his new approach trajectories should be better considered as having a fractal nature: the notion of resolution being central for defining a dynamics (even the notion of continuty of trajectories was not central). In 1962 he also presented a paper (reproduced as chapter 4 in Wholeness and the implicate order ) where he presented an alternative ontological interpretation generalizing quantum mechanics and hoping that new experimental facts could be generated at high energy in the subquantum regime. However, in 1979 he went back to his old quantum potential approach after the important numerical work made by his collaborator Basil Hiley with two students . Together with Hiley Bohm wrote the influential textbook The undivided Universe where many of his remarkable ideas were synthetized. This included the pilot-wave theory but also some speculations about the undivided wholeness, implicate order, and the concept of active information which all played a fundamental role in his work over the years. In particular, active information characterizes the specificity of the quantum potential carrying information through space and time in a non-local and thus highly non-classical or mechanical way. It is interesting to see that the old manuscript ACCIQT of 1951 mirrors this ultimate work containing implicitly all the questions raised from the start. VI. NOTES ADDED IN PROOF After this work was completed we learned about the work made by the historian Olival Freire in 2005 where the existence of Bohm's manuscript published here is briefly mentionned. The manuscript we found and analyzed here is very probably an article submitted to Nature by S. W. Massey in 1951 and refused after some critical comments made by Léon Rosenfeld to the editors. This therefore answers our second question in section III concerning the journal where ACCIQT was submitted and confirms our hypothesis made at the end of section III concerning a potential submission to Nature. VII. ACKNOWLEDGMENTS The authors wish to thank the Foundation Louis de Broglie for very interesting discussions motivating the present work. We specially thank interactions with Christian Thomas de Pange, Philippe Frébault, Michel Karatchentzeff, Daniel Fargue and Georges Lochak, as well as for their help and supports and for answering many historical questions. Authors also thank the archives Louis de Broglie hosted at the Academies des Sciences Paris for allowing reproduction of the present document. We thank Basil Hiley for interesting discussions and for allowing us to reproduce Bohm's manuscript. We thank the Archives David Bohm
#ifndef UNIT_PREFIX_H #define UNIT_PREFIX_H #include <stdio.h> #include <sys/types.h> #include <stdint.h> struct unit_prefix { const unsigned dont_scale; /* Don't change number, maybe add grouping */ const unsigned dont_group; /* Don't group number */ const unsigned decimal; /* Use powers of 1000 instead of 1024 */ const unsigned space; /* Add space between number and unit prefix */ int (*const unit_prefix)(char *const buf, /* If NULL printf() is used */ const size_t bufsiz, FILE *file_ptr, /* If NULL `stdout` is used */ const intmax_t value, const unsigned mode); }; extern const struct unit_prefix UnitPrefix; #endif /* UNIT_PREFIX_H */
<gh_stars>1-10 import sys import os from subprocess import Popen as run from subprocess import PIPE from django.core.management.base import NoArgsCommand, CommandError from django.conf import settings from kronos import uninstall class Command(NoArgsCommand): help = 'Remove tasks from cron' def handle_noargs(self, **options): uninstall()
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ // inner angular imports // these are necessary to bootstrap the local angular. // They can stay even after NP cutover import './application/index.scss'; import angular from 'angular'; // required for `ngSanitize` angular module import 'angular-sanitize'; import { EuiIcon } from '@elastic/eui'; import { i18nDirective, i18nFilter, I18nProvider } from '@osd/i18n/angular'; import { CoreStart, PluginInitializerContext } from 'opensearch-dashboards/public'; import { DataPublicPluginStart } from '../../data/public'; import { Storage } from '../../opensearch_dashboards_utils/public'; import { NavigationPublicPluginStart as NavigationStart } from '../../navigation/public'; import { createDocTableDirective } from './application/angular/doc_table'; import { createTableHeaderDirective } from './application/angular/doc_table/components/table_header'; import { createToolBarPagerButtonsDirective, createToolBarPagerTextDirective, } from './application/angular/doc_table/components/pager'; import { createTableRowDirective } from './application/angular/doc_table/components/table_row'; import { createPagerFactory } from './application/angular/doc_table/lib/pager/pager_factory'; import { createInfiniteScrollDirective } from './application/angular/doc_table/infinite_scroll'; import { createDocViewerDirective } from './application/angular/doc_viewer'; import { createRenderCompleteDirective } from './application/angular/directives/render_complete'; import { initAngularBootstrap, configureAppAngularModule, PrivateProvider, PromiseServiceCreator, registerListenEventListener, watchMultiDecorator, createTopNavDirective, createTopNavHelper, } from '../../opensearch_dashboards_legacy/public'; import { createContextErrorMessageDirective } from './application/components/context_error_message'; import { DiscoverStartPlugins } from './plugin'; import { getScopedHistory } from './opensearch_dashboards_services'; import { createDiscoverLegacyDirective } from './application/components/create_discover_legacy_directive'; /** * returns the main inner angular module, it contains all the parts of Angular Discover * needs to render, so in the end the current 'opensearchDashboards' angular module is no longer necessary */ export function getInnerAngularModule( name: string, core: CoreStart, deps: DiscoverStartPlugins, context: PluginInitializerContext ) { initAngularBootstrap(); const module = initializeInnerAngularModule(name, core, deps.navigation, deps.data); configureAppAngularModule(module, { core, env: context.env }, true, getScopedHistory); return module; } /** * returns a slimmer inner angular module for embeddable rendering */ export function getInnerAngularModuleEmbeddable( name: string, core: CoreStart, deps: DiscoverStartPlugins ) { return initializeInnerAngularModule(name, core, deps.navigation, deps.data, true); } let initialized = false; export function initializeInnerAngularModule( name = 'app/discover', core: CoreStart, navigation: NavigationStart, data: DataPublicPluginStart, embeddable = false ) { if (!initialized) { createLocalI18nModule(); createLocalPrivateModule(); createLocalPromiseModule(); createLocalTopNavModule(navigation); createLocalStorageModule(); createPagerFactoryModule(); createDocTableModule(); initialized = true; } if (embeddable) { return angular .module(name, [ 'ngSanitize', 'react', 'ui.bootstrap', 'discoverI18n', 'discoverPrivate', 'discoverDocTable', 'discoverPagerFactory', 'discoverPromise', ]) .config(watchMultiDecorator) .directive('icon', (reactDirective) => reactDirective(EuiIcon)) .directive('renderComplete', createRenderCompleteDirective); } return angular .module(name, [ 'ngSanitize', 'ngRoute', 'react', 'ui.bootstrap', 'discoverI18n', 'discoverPrivate', 'discoverPromise', 'discoverTopNav', 'discoverLocalStorageProvider', 'discoverDocTable', 'discoverPagerFactory', ]) .config(watchMultiDecorator) .run(registerListenEventListener) .directive('renderComplete', createRenderCompleteDirective) .directive('discoverLegacy', createDiscoverLegacyDirective) .directive('contextErrorMessage', createContextErrorMessageDirective); } function createLocalPromiseModule() { angular.module('discoverPromise', []).service('Promise', PromiseServiceCreator); } function createLocalPrivateModule() { angular.module('discoverPrivate', []).provider('Private', PrivateProvider); } function createLocalTopNavModule(navigation: NavigationStart) { angular .module('discoverTopNav', ['react']) .directive('osdTopNav', createTopNavDirective) .directive('osdTopNavHelper', createTopNavHelper(navigation.ui)); } function createLocalI18nModule() { angular .module('discoverI18n', []) .provider('i18n', I18nProvider) .filter('i18n', i18nFilter) .directive('i18nId', i18nDirective); } function createLocalStorageModule() { angular .module('discoverLocalStorageProvider', ['discoverPrivate']) .service('localStorage', createLocalStorageService('localStorage')) .service('sessionStorage', createLocalStorageService('sessionStorage')); } const createLocalStorageService = function (type: string) { return function ($window: any) { return new Storage($window[type]); }; }; function createPagerFactoryModule() { angular.module('discoverPagerFactory', []).factory('pagerFactory', createPagerFactory); } function createDocTableModule() { angular .module('discoverDocTable', ['discoverPagerFactory', 'react']) .directive('docTable', createDocTableDirective) .directive('osdTableHeader', createTableHeaderDirective) .directive('toolBarPagerText', createToolBarPagerTextDirective) .directive('osdTableRow', createTableRowDirective) .directive('toolBarPagerButtons', createToolBarPagerButtonsDirective) .directive('osdInfiniteScroll', createInfiniteScrollDirective) .directive('docViewer', createDocViewerDirective); }
DECL|gfsk_bt_0p3_h_0p5_mode_config|variable|gfsk_bt_0p3_h_0p5_mode_config DECL|xcvr_GFSK_BT_0p3_h_0p5_1mbps_config|variable|xcvr_GFSK_BT_0p3_h_0p5_1mbps_config DECL|xcvr_GFSK_BT_0p3_h_0p5_250kbps_config|variable|xcvr_GFSK_BT_0p3_h_0p5_250kbps_config DECL|xcvr_GFSK_BT_0p3_h_0p5_500kbps_config|variable|xcvr_GFSK_BT_0p3_h_0p5_500kbps_config
template<unsigned B> class ullmanset_iter; template<unsigned B> class ullmanset_const_iter; template<unsigned B> class ullmanset_const_stl_iter; template<unsigned B> class ullmanset { private: friend class ullmanset_iter<B>; friend class ullmanset_const_iter<B>; friend class ullmanset_const_stl_iter<B>; class keypos { public: unsigned key; unsigned pos; }; class data : public refcounted { public: unsigned size; unsigned n; keypos kp[1]; public: inline void delete_at_pos (unsigned p); }; ptr<data> d; public: typedef ullmanset_iter<B> iter; typedef ullmanset_const_iter<B> const_iter; public: ullmanset (unsigned size); ullmanset () : ullmanset(0) { } ullmanset (const ullmanset &s) : d(s.d) { } ullmanset (copy, const ullmanset &s); ullmanset (const bitset &t); ullmanset (unsigned size, initializer_list<unsigned> il); ullmanset (reader &r); ~ullmanset () { } ullmanset &operator = (const ullmanset &s) { d = s.d; return *this; } ullmanset &operator = (const bitset &t); // range-based for inline ullmanset_const_stl_iter<B> begin () const; inline ullmanset_const_stl_iter<B> end () const; unsigned size () const { return d->size; } bool is_empty () const { return d->n == 0; } unsigned card () const { return d->n; } unsigned head () const { assert (d->n > 0); return d->kp[0].key; } bool operator == (const ullmanset &s); bool operator != (const ullmanset &s) { return !operator == (s); } void restore (unsigned old_card) { assert (d->n >= old_card); d->n = old_card; } void clear () { d->n = 0; } inline void push (unsigned k); inline void operator += (unsigned k); // ??? should these be inline? inline void operator -= (unsigned k); void yank (unsigned k) { assert (operator % (k)); operator -= (k); } void toggle (unsigned k) { if (operator % (k)) operator -= (k); else operator += (k); } ullmanset &operator |= (const ullmanset &s); ullmanset &operator &= (const ullmanset &s); ullmanset &operator ^= (const ullmanset &s); bool operator % (unsigned k) const { assert ((k - B) >= 0); assert ((k - B) < d->size); unsigned p = d->kp[k - B].pos; return p < d->n && d->kp[p].key == k; } bool operator () (unsigned k) const { return operator % (k); } // always 0-based unsigned nth (unsigned p) const { assert (p < d->n); return d->kp[p].key; } unsigned position (unsigned k) const { assert (operator % (k)); return d->kp[k - B].pos; } void write_self (writer &w) const; }; template<unsigned B> void ullmanset<B>::data::delete_at_pos (unsigned p) { assert (p < n); --n; if (p != n) { unsigned ell = kp[n].key; kp[ell - B].pos = p; kp[p].key = ell; } } template<unsigned B> ullmanset<B>::ullmanset (unsigned size) { data *newd = (data *)new char[sizeof (data) + sizeof (keypos) * size - sizeof (keypos)]; new (newd) data; newd->size = size; newd->n = 0; d = newd; } template<unsigned B> ullmanset<B>::ullmanset (unsigned size, initializer_list<unsigned> il) : ullmanset(size) { for (unsigned i : il) operator += (i); } template<unsigned B> ullmanset<B>::ullmanset (copy, const ullmanset &s) : ullmanset(s.size ()) { d->n = s.d->n; memcpy (&d->kp[0], &s.d->kp[0], sizeof (keypos) * d->n); } template<unsigned B> ullmanset<B>::ullmanset (reader &r) : ullmanset(r.read_unsigned ()) { unsigned card_ = r.read_unsigned (); for (unsigned i = 0; i < card_; i ++) push (r.read_unsigned ()); } template<unsigned B> bool ullmanset<B>::operator == (const ullmanset &s) { if (d->n != s.d->n) return 0; for (iter i = *this; i; i ++) { if (!s(i.val ())) return 0; } return 1; } template<unsigned B> void ullmanset<B>::push (unsigned k) { assert (!operator % (k)); unsigned p = d->n ++; d->kp[p].key = k; d->kp[k - B].pos = p; } template<unsigned B> void ullmanset<B>::operator += (unsigned k) { assert ((k - B) >= 0); assert ((k - B) < d->size); if (!operator % (k)) { unsigned p = d->n ++; d->kp[p].key = k; d->kp[k - B].pos = p; } } template<unsigned B> void ullmanset<B>::operator -= (unsigned k) { assert ((k - B) >= 0); assert ((k - B) < d->size); if (operator % (k)) { unsigned p = d->kp[k - B].pos; d->delete_at_pos (p); } } template<unsigned B> ullmanset<B> & ullmanset<B>::operator |= (const ullmanset &s) { for (iter i = s; i; i ++) operator += (i.val ()); } template<unsigned B> ullmanset<B> & ullmanset<B>::operator &= (const ullmanset<B> &s) { for (iter i = *this; i; i ++) { unsigned k = i.val (); if (!s(k)) i.del (); } } template<unsigned B> ullmanset<B> & ullmanset<B>::operator ^= (const ullmanset<B> &s) { for (const_iter i = s; i; i ++) { int k = i.val (); if (operator % (k)) operator -= (k); else push (k); } return *this; } template<unsigned B> void ullmanset<B>::write_self (writer &w) const { write (w, size ()); write (w, card ()); for (const_iter i = *this; i; i ++) write (w, i.val ()); } template<unsigned B> class ullmanset_const_stl_iter { private: ptr<typename ullmanset<B>::data> d; unsigned p; public: ullmanset_const_stl_iter (const ullmanset<B> &s, unsigned p_) : d(s.d), p(p_) { } bool operator != (const ullmanset_const_stl_iter &end) const { return p != end.p; } unsigned operator * () const { assert (p < d->n); return d->kp[p].key; } ullmanset_const_stl_iter &operator ++ () { p ++; return *this; } }; template<unsigned B> ullmanset_const_stl_iter<B> ullmanset<B>::begin () const { return ullmanset_const_stl_iter<B> (*this, 0); } template<unsigned B> ullmanset_const_stl_iter<B> ullmanset<B>::end () const { return ullmanset_const_stl_iter<B> (*this, d->n); } template<unsigned B> class ullmanset_iter { private: ptr<typename ullmanset<B>::data> d; unsigned i; bool deleted; public: ullmanset_iter (ullmanset<B> &s) : d(s.d), i(0), deleted(0) { } ~ullmanset_iter () { } void del () { assert (!deleted); assert (i < d->n); d->delete_at_pos (i); } unsigned val () const { assert (!deleted); assert (i < d->n); return d->kp[i].key; } unsigned pos () const { assert (!deleted); assert (i < d->n); return i; } operator bool () const { assert (!deleted); return i < d->n; } void operator ++ () { if (deleted) deleted = 0; else i ++; } void operator ++ (int) { operator ++ (); } }; template<unsigned B> class ullmanset_const_iter { private: ptr<typename ullmanset<B>::data> d; unsigned i; public: ullmanset_const_iter (const ullmanset<B> &s) : d(s.d), i(0) { } ~ullmanset_const_iter () { } unsigned val () const { assert (i < d->n); return d->kp[i].key; } unsigned pos () const { assert (i < d->n); return i; } operator bool () const { return i < d->n; } void operator ++ () { i ++; } void operator ++ (int) { i ++; } }; /* interoperating with other set types */ template<unsigned B> set<unsigned> &operator |= (set<unsigned> &s, const ullmanset<B> &t) { for (ullmanset_const_iter<B> i = t; i; i ++) s += i.val (); return s; } template<unsigned B> ullmanset<B> &operator |= (ullmanset<B> &s, const set<unsigned> &t) { for (set_const_iter<unsigned> i = t; i; i ++) s += i.val (); return s; } template<unsigned B> ullmanset<B> &operator &= (ullmanset<B> &s, const set<unsigned> &t) { for (ullmanset_const_iter<B> i = s; i; i ++) { int k = i.val (); if (!t(k)) i.del (); } return s; } template<unsigned B> ullmanset<B> &operator ^= (ullmanset<B> &s, const set<unsigned> &t) { for (set_const_iter<unsigned> i = t; i; i ++) { int k = i.val (); if (s % k) s -= (k); else s.push (k); } return s; }
def resume_job(print_job_id: str, my_logger: Logger) -> bool: cmd = "lp -i " + print_job_id + " -H resume" out = subprocess.getstatusoutput(cmd) if out[0] != 0: my_logger.critical("Job with id " + print_job_id + " was not sent to printer!!") return False my_logger.warning("Job with id " + print_job_id + " was sent to printer.") return True
package io.github.mrspock182; import io.github.mrspock182.exception.CryptographyException; import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; public interface Decryption { Long toLong(String value) throws CryptographyException; String toString(String value) throws CryptographyException; Integer toInteger(String value) throws CryptographyException; BigDecimal toBigDecimal(String value) throws CryptographyException; BigInteger toBigInteger(String value) throws CryptographyException; LocalDate toLocalDate(String value, String dateFormatter) throws CryptographyException; LocalDateTime toLocalDateTime(String value, String dateFormatter) throws CryptographyException; }
/// Construct an `mpsse::Context` for the requested interface. pub fn mpsse(&self, interface: ftdi::Interface) -> Result<Rc<RefCell<mpsse::Context>>> { match interface { // Note: we may want to be able to create an MPSSE for interface A in the future. // There are enough IOs for a second SPI bus or for JTAG or I2C busses. // For now, only interface B is supported. ftdi::Interface::B => self.mpsse_interface_b(), _ => { bail!( "I don't know how to create an MPSSE context for interface {:?}", interface ); } } }
<reponame>thc202/zap-extensions /* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2014 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.pscanrulesBeta; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import net.htmlparser.jericho.Source; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.core.scanner.Alert; import org.parosproxy.paros.core.scanner.Plugin; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.addon.commonlib.CommonAlertTag; import org.zaproxy.zap.extension.pscan.PluginPassiveScanner; /** * Server Header Version Information Leak passive scan rule * https://github.com/zaproxy/zaproxy/issues/1169 * * @author <EMAIL> */ public class ServerHeaderInfoLeakScanRule extends PluginPassiveScanner { private static final int PLUGIN_ID = 10036; private static final Logger logger = LogManager.getLogger(ServerHeaderInfoLeakScanRule.class); private static final Pattern VERSION_PATTERN = Pattern.compile(".*\\d.*"); private static final Map<String, String> ALERT_TAGS = CommonAlertTag.toMap( CommonAlertTag.OWASP_2021_A05_SEC_MISCONFIG, CommonAlertTag.OWASP_2017_A06_SEC_MISCONFIG, CommonAlertTag.WSTG_V42_INFO_02_FINGERPRINT_WEB_SERVER); @Override public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { long start = System.currentTimeMillis(); List<String> serverOption = msg.getResponseHeader().getHeaderValues("Server"); if (!serverOption.isEmpty()) { // Header Found // It is set so lets check it. Should only be one but it's a vector so iterate to be // sure. for (String serverDirective : serverOption) { boolean matched = VERSION_PATTERN.matcher(serverDirective).matches(); if (matched) { // See if there's any version info. // While an alpha string might be the server type (Apache, Netscape, IIS, etc.) // that's much less of a head-start than actual version details. raiseAlert( Alert.RISK_LOW, Alert.CONFIDENCE_HIGH, Constant.messages.getString( "pscanbeta.serverheaderversioninfoleak.name"), Constant.messages.getString( "pscanbeta.serverheaderversioninfoleak.desc"), Constant.messages.getString( "pscanbeta.serverheaderinfoleak.general.soln"), Constant.messages.getString( "pscanbeta.serverheaderinfoleak.general.refs"), serverDirective); } else if (Plugin.AlertThreshold.LOW.equals(this.getAlertThreshold())) { raiseAlert( Alert.RISK_INFO, Alert.CONFIDENCE_HIGH, Constant.messages.getString("pscanbeta.serverheaderinfoleak.name"), Constant.messages.getString("pscanbeta.serverheaderinfoleak.desc"), Constant.messages.getString( "pscanbeta.serverheaderinfoleak.general.soln"), Constant.messages.getString( "pscanbeta.serverheaderinfoleak.general.refs"), serverDirective); } } } logger.debug("\tScan of record {} took {}ms", id, System.currentTimeMillis() - start); } @Override public int getPluginId() { return PLUGIN_ID; } @Override public String getName() { return Constant.messages.getString("pscanbeta.serverheader.rule.name"); } @Override public Map<String, String> getAlertTags() { return ALERT_TAGS; } private void raiseAlert( int risk, int confidence, String name, String desc, String soln, String refs, String evidence) { newAlert() .setName(name) .setRisk(risk) .setConfidence(confidence) .setDescription(desc) .setSolution(soln) .setReference(refs) .setEvidence(evidence) .setCweId(200) .setWascId(13) .raise(); } }
/* Copyright 2021 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type NodeSelectorPolicy string const ( Newest NodeSelectorPolicy = "Newest" Oldest NodeSelectorPolicy = "Oldest" Random NodeSelectorPolicy = "Random" ) // FloatingIPBindingSpec defines the desired state of FloatingIPBinding type FloatingIPBindingSpec struct { // The floating IP address to bind nodes to. i.e. "1.2.3.4" FloatingIP string `json:"floatingIP"` // An optional LabelSelector to select nodes. Defaults to all nodes. // A label selector is a label query over a set of resources. The result of matchLabels // and matchExpressions are ANDed. An empty label selector matches all objects. A null // label selector matches no objects. // +optional // +nullable NodeSelector *metav1.LabelSelector `json:"nodeSelector,omitempty"` // An optional policy to choose a node from those that match the NodeSelector // Defaults to Newest // +kubebuilder:default:="Newest" // +optional NodeSelectorPolicy NodeSelectorPolicy `json:"nodeSelectorPolicy,omitempty"` } // FloatingIPBindingStatus defines the observed state of FloatingIPBinding type FloatingIPBindingStatus struct { AssignedDropletID int `json:"assignedDropletID,omitempty"` AssignedDropletName string `json:"assignedDropletName,omitempty"` } // +kubebuilder:object:root=true // FloatingIPBinding is the Schema for the floatingipbindings API // +kubebuilder:printcolumn:name="FLOATING_IP",type=string,JSONPath=`.spec.floatingIP` // +kubebuilder:printcolumn:name="ASSIGNED_DROPLET_ID",type=string,JSONPath=`.status.assignedDropletID` // +kubebuilder:printcolumn:name="ASSIGNED_DROPLET_NAME",type=string,JSONPath=`.status.assignedDropletName` // +kubebuilder:subresource:status type FloatingIPBinding struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec FloatingIPBindingSpec `json:"spec,omitempty"` Status FloatingIPBindingStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true // FloatingIPBindingList contains a list of FloatingIPBinding type FloatingIPBindingList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []FloatingIPBinding `json:"items"` } func init() { SchemeBuilder.Register(&FloatingIPBinding{}, &FloatingIPBindingList{}) }
import os from conan.tools.files.files import save_toolchain_args from conan.tools.gnu import Autotools from conans.test.utils.mocks import ConanFileMock from conans.test.utils.test_files import temp_folder def test_source_folder_works(): folder = temp_folder() os.chdir(folder) save_toolchain_args({ "configure_args": "-foo bar", "make_args": ""} ) conanfile = ConanFileMock() conanfile.folders.set_base_install(folder) sources = "/path/to/sources" conanfile.folders.set_base_source(sources) autotools = Autotools(conanfile) autotools.configure(build_script_folder="subfolder") assert conanfile.command.replace("\\", "/") == '"/path/to/sources/subfolder/configure" -foo bar' autotools.configure() assert conanfile.command.replace("\\", "/") == '"/path/to/sources/configure" -foo bar'
// CreateVM wraps the the POST function in the VM API that creates a new VM. // // param requestBody: The struct representing the VM to be created // // param m: map containing provider config info func CreateVM(requestBody *structs.VMInfo, m map[string]string) error { log.Printf("! In create API wrapper") auth, err := util.GetAuth(m) if err != nil { log.Printf("! In create API wrapper, error authenticating") return err } asJSON, err := json.Marshal(requestBody) if err != nil { log.Printf("! In create API wrapper, error encoding request as JSON") return err } req, err := http.NewRequest("POST", m["vm_api_url"]+"vms", bytes.NewBuffer(asJSON)) if err != nil { return err } req.Header.Add("Authorization", "Bearer "+auth) req.Header.Set("Content-Type", "application/json") client := &http.Client{} log.Printf("! JSON being sent to API:\n %v", string(asJSON)) resp, err := client.Do(req) if err != nil { log.Printf("! In create API wrapper, error making HTTP request") return err } log.Printf("! In create API wrapper, request returned with status code %d", resp.StatusCode) if resp.StatusCode != http.StatusCreated { return fmt.Errorf("Request returned with status code %d", resp.StatusCode) } log.Printf("! Returning from create wrapper without error") return nil }
The idea of a Nietzschean 'politics' has long been under a cloud of suspicion, especially since prominent National Socialists in Germany appropriated Nietzsche as the forerunner of their political agenda. In an effort to distance Nietzsche from this tainted association, subsequent Nietzsche scholarship in the post-war period often focused on individualist themes from Nietzsche centering on private self-cultivation and freedom from herdish conformism. While these apolitical individualist readings, in one form or another, remain the dominant view, Hugo Drochon argues that this approach is in error. In his readable, yet scholarly book, he makes a provocative case that Nietzsche indeed has a politics, and he seeks to outline its contours. The approach throughout the book is methodologically in line with that of the "Cambridge School" of political theory and intellectual history, carefully situating Nietzsche in his biographical, historical and political context. Drochon, to this end, draws not just on Nietzsche's published work, but extensively on his notebooks, lectures, and letters, as well as various sources contemporary to Nietzsche. While one might remain doubtful of various aspects of Drochon's interpretation, this is among the most illuminating studies that have been written on the topic of Nietzsche's political thought. Complementary to the more negative sort of case Tamsin Shaw ably mounts in Nietzsche's Political Skepticism, Drochon's book makes the best case I've come across that Nietzsche has a positive political vision. Before we get into the details of Drochon's account, a couple of issues are worth considering for framing the interpretive position that he offers. The question of whether Nietzsche has a "politics" can be understood in two different ways. First, does Nietzsche have a political philosophy? That is, does he offer theories about the distinctive questions of political philosophy? Second, does Nietzsche have a political agenda, namely ideas for transforming political institutions or for his broader cultural agenda of a "revaluation of all values" to be implemented through political mechanisms? These might of course overlap and work in tandem, but it is important to see that they are at least potentially distinct. Although Drochon never really separates these, it is a useful distinction for the sorts of issues he wants to consider. After all, some of Drochon's opponents are interested in establishing that Nietzsche doesn't have a political philosophy. Some are interested in establishing that he doesn't have a political agenda. And some are interested in establishing that he has neither. Relatedly, the word "politics" is used with considerable frequency in this study, following Nietzsche's own occasional use of the phrase "great politics" (e.g., Beyond Good and Evil, §208). In addition to the issue of whether "politics" refers to a political philosophy, a political agenda, or both, much will also turn on how expansive a conception of "politics" (and of the "political") one has in mind. At times, Drochon seemed to be operating with a broad conception indeed, whereby it seemed that virtually anything beyond just the individual was thereby "political." Perhaps little is to be gained by quibbling over the semantics. But Drochon's thesis becomes rather less provocative if the political is thinned down in such a way that it doesn't have much to do with the state or other modes of government, with laws enforced by this government authority, and the like. It was unclear throughout the book how the 'political' and the 'social' differed, if at all. On these fronts, I found there to be a lack of conceptual elaboration and precision around "politics" and its cognates that made the book's thesis and its import somewhat elusive. It would have been good to outline in more detail what scope of the concept "politics" was being assumed, or what it would take for something to count as "political." Much of Drochon's book is framed as an answer to Bernard Williams, who is skeptical of the idea that Nietzsche has a politics. Williams, posing the challenge that Drochon seeks to meet, writes as follows: [Nietzsche] provides no way of relating his ethical and psychological insights to an intelligible account of modern society -- a failing only thinly concealed by the impression he gives of having thoughts about modern politics that are determinate but terrible. But we need a politics, in the sense of a coherent set of opinions about the ways in which power should be exercised in modern societies, with what limitations and to what ends (Shame and Necessity, quoted in Drochon, 3). Williams does not provide a very good foil, however. In the first part of the quotation, Williams implies that Nietzsche doesn't have a politics, in part because he doesn't have a way of relating his ethical and psychological insights to an intelligible account of modern society. Yet this is an odd claim to make. For Nietzsche does relate his ethical and psychological insights to an intelligible account of modern society. Do many sympathetic readers of Nietzsche -- apart from Williams apparently -- really think otherwise? And moreover, how relevant is this to having a "politics?" One could, it would seem, be an excellent diagnostician of social ills without having a politics in any full-blooded or interesting sense. In the second part of the quotation, Williams offers a further criterion: In order to have a politics, one would also need a theory of the way power should be exercised in modern societies, with what limitations and to what ends. This criterion is better, yet it is still too imprecise. Unless governments or laws are involved, it is rather misleading to frame it as a political issue. If one's theory is about how private actors or corporate non-governmental agents should justifiably exercise power, is that a political theory as opposed to a social or ethical one? If so, why? If one takes what Williams says in this passage at face value, it would be rather easy to show that Nietzsche had a politics. One would basically just need to show he has views about modern society. Again, little should turn on the semantics. But I think Drochon is trying to establish something more ambitious, controversial, and thus interesting than what is indicated by Williams's criteria. As a matter of fact, I think Drochon succeeds, according to more plausible criteria, in showing that Nietzsche, in certain key respects, has a politics. The reliance on Williams is therefore unhelpful, since it does not cast into sharp enough relief what Drochon actually needs to show (and to some extent, does manage to show) in making his case. Drochon's first chapter concerns Nietzsche's relationship to the Greek world and his criticisms of and affinities with Socrates and Plato. Drochon has a good discussion of Nietzsche's ambivalent relationship with Socrates, someone Nietzsche views as both a gadfly worthy of admiration and a decadent worthy of scorn. Drochon's discussion of Plato is more distinctive. One of the most insightful aspects of this chapter is his use of Nietzsche's lectures on Plato, which are often ignored by Anglophone Nietzsche scholars. Drochon is trying to establish a similarity between the supposed Platonic political project (particularly as understood by Nietzsche) and Nietzsche's own supposed political project. Plato, on this view, is someone with both a political philosophy (as elaborated in the Republic and elsewhere) and someone with a political agenda behind his writings. Key to Drochon's chapter is his view of why Plato writes. He is not simply trying to convey abstract philosophical ideas through his dialogues, but (at least on Drochon's reading of Nietzsche's controversial view, as presented in the Plato lectures) to have concrete political effects, including paving the way for the foundation of a new and reformed polis. We should, Drochon suggests, also be attentive to what Nietzsche is trying to achieve through writing (47-8). Even if Nietzsche doesn't mention political change explicitly, he may be trying to effect it through his philosophical works, and Drochon thinks his letters and notebooks provide good evidence of this, a matter to which Drochon returns at the end of the book. In Chapter 2, Drochon considers Nietzsche's views on the state. He makes a good case for why Nietzsche is not part of the social contract tradition. In making this point about Nietzsche's divergence from such views, Drochon seeks to counter Brian Leiter's influential position that Nietzsche has no political philosophy to speak of (55). Yet Drochon's line here is unpersuasive, because it depends on a misinterpretation of Leiter. He attributes to Leiter the view that in order to have a political philosophy one must have a social contract theory of the state, and then he proceeds to charge Leiter with an overly narrow conception of political philosophy that would, on this basis, exclude Nietzsche. While Leiter does give three examples of figures from the social contract tradition (Hobbes, Locke, and Rousseau) as emblematic of political philosophy, nowhere does he claim that subscribing to social contract theory is necessary for having a political philosophy. Indeed, it is clear from the places that Drochon cites in Leiter's work that Leiter takes Marx (presumably no subscriber to social contract theory) to be a paradigm (perhaps even his favored paradigm) of political philosophy. Setting up a straw man in this way is unfortunate, because it distracts from the fact that Drochon actually does go quite some way to establishing (in Chapters 3 and 6 especially) that Nietzsche has a political philosophy and political agenda. As the chapter continues, Drochon gives a nice reading of Nietzsche's early unpublished piece "The Greek State," in particular bringing out some of the uncomfortable ideas about slavery that Nietzsche broaches there. Drochon further argues that Nietzsche seeks to move away from the decaying nation-state and to refocus normative and political authority in another direction, toward "private companies" (66) taking up the state's functions. Even if true, however, does this help to establish that Nietzsche has a political philosophy or a political agenda? Isn't this is a non-political route for the carrying out of what were previously political functions? Chapter 3 turns to Nietzsche's views on democracy and related issues. Several commentators have built on Nietzschean themes to develop a more agonal, Nietzschean form of democracy. Others have focused on the aristocratic dimensions of his thinking and the ways in which those are opposed to democracy. Drochon offers a subtle account of Nietzsche's understanding of democracy. This is one of his most successful chapters. One of its virtues is that it helps to establish that Nietzsche has serious philosophical insight to offer on the subject of democracy. Democracy often operates as an unquestioned value in Western political discourse, and Drochon gives us the resources for understanding it more critically through such Nietzschean notions as "herd morality" and "misarchism" (103). In Chapter 4, Drochon gives a political interpretation of three of Nietzsche's central ideas: the will to power, the Übermensch, and the eternal recurrence. Drochon resists a way of reading these ideas in an overly individualistic fashion. These are not just doctrines in ethics and moral psychology, relating to one's character and attitudes and the like. Rather, he maintains, they have important 'political' application beyond this. Precision around the concept of 'the political' is again an issue here: Is the overman going to have political power, in the sense of being a ruler backed-up by the force of law? Similarly, reactions to the thought of the eternal recurrence may be a guide to separating the strong from the weak. But what are its political implications? Will government intervene and deprive those who fail the eternal recurrence test of certain legal privileges? Is it like a poll test? In the final two chapters, Drochon presents what he takes to be Nietzsche's positive political agenda. On his reading, this is intimated in the published work, but elaborated in more detail in the unpublished work. Chapter 5 was more stage-setting than anything else, but included a wealth of interesting detail about Nietzsche's envisaged "revaluation of all values." The basic, and quite controversial, line of argument is that Nietzsche turns toward a more political dimension in his re-evaluative enterprise. In Chapter 6, Drochon explores Nietzsche's conception of a "Great Politics." Although it has now become a familiar point that Nietzsche is opposed to German nationalism and Bismarckian power politics, there has been little discussion of what Nietzsche would prefer in its place. Drochon argues, to my mind quite suggestively, that Nietzsche indeed has a geopolitical vision, namely one of a unified continental Europe, led by a "transnational and transracial European caste" (160). In connection with this, Nietzsche wants to encourage a "party of life" that is going to inject life-affirming values into society and is going to pursue a "great politics of breeding a new type of being" (167). Talk of "breeding" brings us into rather uncomfortable territory, which Drochon traverses undaunted. Readings that gloss over the more unsavoury and repellent things that Nietzsche says are legion in philosophical circles, and Drochon, an intellectual historian and political theorist, is courageous for presenting Nietzsche's views unadulterated, something many philosophers seem unwilling to do. Nietzsche does, after all, say that the party of life will need to be involved in the "ruthless extermination of everything degenerate and parasitic" (Drochon quoting Ecce Homo, "The Birth of Tragedy," §4). Shocking, horrifying stuff. Maybe this is a metaphor. Maybe this is rhetorical overkill, given that Nietzsche's views on degeneration are more measured elsewhere (in Human, all too Human, §224, for example.) But whatever it is, we shouldn't let a revulsion toward Nietzsche's vision, and a desire for him to be saying something nicer, cloud our jument about the nasty things he is actually sometimes saying. Drochon faces such things squarely, and it is one of the great merits of his study. Nonetheless, one still wonders how much actual political authority these characters in the "party of life" are supposed to have. Is it just that they will have an influence on society? Or will the force of law secure their power and back up what they do? It seems to me that the answer to this question is crucial in determining the extent to which Nietzsche, in this respect, has a politics (in any full-blooded sense), or just a vision of and plan for society's betterment, with no clear ideas about how to implement it politically. Still, the "party of life" aside, what Drochon says about a transnational Europe is, to my mind, distinctively political and quite interesting. His book is an important contribution to the scholarly literature on this topic. Those who confidently maintain that Nietzsche has no "politics" will be forced, if not to abandon their view completely, then seriously to reconsider it.
General and split forms of some well-known s-domain algorithms A common frame for some well-known algorithms for the stability analysis of continuous-time linear systems is derived. Specifically, a general polynomial recursion is given which includes as particular cases both Routh- and Levinson-type algorithms and is capable of generating new algorithms too. A systematic analysis of all possible corresponding split forms (three-term immittance-domain recurrence relations) is then carried out. This may allow one to clarify and compare the properties of the standard procedures.
<filename>src/components/emojiButton.tsx import {BaseEmoji, NimbleEmoji, NimblePicker} from 'emoji-mart'; import React, {FC, Fragment, useState} from 'react'; import data from '../assets/emoji-mart-data.json'; import {isHTMLElement} from '../helpers/domHelpers'; import {getEmojiSheetUrl} from '../helpers/emojiHelpers'; import {useTweetdeckTheme} from '../helpers/hookHelpers'; import {HandlerOf} from '../helpers/typeHelpers'; export const nimbleEmojiBaseProps = { sheetRows: 60, sheetColumns: 60, data: data as any, }; export const EmojiButton: FC<{onClick: HandlerOf<string>}> = (props) => { const [isPickerShown, setIsPickerShown] = useState(false); const theme = useTweetdeckTheme(); const composerRect = () => document.querySelector('.compose-text-container')!.getBoundingClientRect(); const color = '#1da1f2'; return ( <Fragment> {isPickerShown && ( <div id="emojiPickerWrapper" onClick={(e) => { if (isHTMLElement(e.target) && e.target.closest('.emoji-mart')) { return; } setIsPickerShown(false); }}> <NimblePicker set="twitter" autoFocus onSelect={(emoji: BaseEmoji) => { props.onClick(emoji.native); }} color={color} emoji="sparkles" useButton={false} emojiSize={20} {...nimbleEmojiBaseProps} perLine={7} backgroundImageFn={getEmojiSheetUrl} title="" theme={theme} style={{ position: 'fixed', top: composerRect().top + composerRect().height, left: 0, width: composerRect().width, border: 'none', transform: 'translateX(calc(-100% - 15px))', }} /> </div> )} <div className="btd-emoji-button-wrapper" style={{ height: 20, position: 'absolute', top: 10, right: 10, width: 20, display: 'block', }}> <NimbleEmoji {...nimbleEmojiBaseProps} emoji="joy" size={20} onClick={() => setIsPickerShown(true)} set="twitter" backgroundImageFn={getEmojiSheetUrl} /> </div> </Fragment> ); };
Sovereign Policy Flexibility for Social Protection: Managing Regulatory Risk in IIAs This Report focuses on the design of regulatory risk in international investment agreements (IIAs), and its counterpart treatment in investment arbitral practices. It demonstrates that the uneven conception and treatment of regulatory risk in investment arbitrations stands to threaten the basic premise of regulatory predictability in IIA design. IIAs do not intend to entrench static or hermetically sealed regulatory frameworks, but rather, are designed to enable States Parties to the IIA as well as investors (as third-party beneficiaries of the IIA), to mutually, fairly, and transparently predict and estimate the economic returns and risks of investment. Thus, while the substantive standards of protection in the IIA provide criteria for future legal assessment of host States’ conduct towards investors, they must also be seen to establish the regulatory boundaries that States Parties to the IIA deem acceptably predictable for the duration of any investment to be covered under the IIA.Part I (Regulatory Predictability in IIAs: Paradoxes over Policy Flexibility) of this Report describes the evolving substantive content and structural architecture of IIAs, and shows how various strategies have been deployed to maintain and constrain the regulatory prerogatives of a host State – from substantive standards (e.g. legality clauses, stabilization clauses, exceptions clauses, expanded definitions of investment and treaty applicability provisions, balance of payments provisions, among others), to procedural devices (e.g. dependence on jurisprudence constante in tribunal interpretations, State Parties’ joint decision mechanisms, authoritative interpretations and treaty compliance monitoring devices). As will be seen in Part I, these strategies rarely differentiate between regulatory risk in ordinary business cycles, and regulatory risk endogenous to financial or economic crises. A crystal example of the lack of differentiation may be seen from the disparate analytical treatment of regulatory risk in the issues of indirect (creeping) expropriations vis-a-vis non- compensable regulatory takings, as against the issue of 'legitimate expectations' under the fair and equitable treatment (FET) standard. As investment arbitrations have shown, it has become entirely possible for a tribunal to find that, while a host State is not liable for indirect expropriation when it imposes a regulatory change, the same regulatory change may be found to have violated investors’ 'legitimate expectations' and thus lead to a breach of the fair and equitable treatment standard, for which the host State is (often and problematically) found liable for compensation. Rather unusually, the value of compensation for these FET breach is frequently pegged at the level of the same indirect expropriation claim that the tribunal previously rejected.Part II (Managing Regulatory Risk from Social Protection Measures) proceeds to show that the estimation of regulatory risk from the design of IIAs can, and should, foreseeably include States Parties’ continuing dynamic obligations under the International Covenant on Economic Social and Cultural Rights (ICESCR). It shows, first, that the due diligence process can be revised to identify areas of host State policy flexibility that should be anticipated during the life of an investment as part of ICESCR compliance - Host States’ ICESCR compliance are now susceptible of empirical investigation and inclusion in investors’ regulatory risk assessments. Second, the ICESCR may have utility as an interpretive device read into the IIA – whether as part of the interpretation of standards of 'treatment' made obligatory upon States Parties, or within the process of valuation of compensation for breaches of non-expropriation standards of the IIA. Finally, Part II also posits that an investor’s home State which is a party both to the ICESCR as well as any given IIA, assumes counterpart duties to ensure the extraterritorial application of the ICESCR to its nationals in other jurisdictions, including a duty to ensure that such nationals do not act in ways that cause States to violate the fundamental obligation to ‘respect’, ‘protect’, or ‘fulfill’ ICESCR rights.Part III (Regulatory Risk Assessment for Diverse Investment Assets) then shows that different types or forms of investment require an appropriate analysis of the valuation method for each form. The assessment of regulatory risk for hedge funds, for example, may be tied more to generally to the assessments of a country’s macroeconomic political risk (usually based on inflation, the risk-free rate of a government security, among other variables). By contrast, it may be more appropriate to perform a regulatory regime assessment that is industry-specific for foreign direct investments (such as physical infrastructure or utilities), particularly where the regulatory process will entail inevitable impacts on ICESCR compliance. As seen in recent developments in Socially Responsible Investment (SRI) benchmarking and the UN Principles on Responsible Investment, it is not impossible to assess regulatory risk with a view to indexing the host State’s continuing social protection obligations under the ICESCR.In the Conclusion (Shedding the Myth of Static Investment Regulation in an Era of Social Protection), this Report shows that, while regulatory predictability is a key objective of IIAs, it need not exclude dynamic host State regulations so long as the latter can be transparently tracked and verified by States Parties to the IIA. The kind of regulatory risk that should be deemed rightly compensable under IIAs should be tailored more towards host State conduct that prohibitively creates moral hazards and incentivizes adverse selection (fueled by the information asymmetry that favors the host State), ultimately resulting in violations to investors’ due process rights and foreseeable contractual expectations. The fundamental task of new IIA design must enable both investors and States Parties to endogenously factor in the costs of policy uncertainty as a result of the continuing demands upon host States to comply with the ICESCR. In this sense, ‘dynamic’ host State regulations (or the degree of policy flexibility that must be maintained to ensure that a State’s social protection measures to comply with the ICESCR remain in place during the life of an investment), should not be prohibited or penalized ex ante, as compensable breaches of an IIA. Where States Parties and investors have been transparently informed at the outset of this continuing dimension of regulatory risk on the ultimate price of investment, there can be no justifiable claim to compensation.
import math import sys s = input().split() a = int(s[0]) b = int(s[1]) c = int(s[2]) print(math.ceil(a/c)*math.ceil(b/c))
<gh_stars>1-10 import pickle import numpy as np import load_policy import tf_util import tensorflow as tf import pandas as pd def generate_expert_data(envname, max_timesteps, expert_policy_file, num_rollouts, save=True): with tf.Session(): tf_util.initialize() import gym env = gym.make(envname) max_steps = max_timesteps or env.spec.timestep_limit print('loading and building expert policy') policy_fn = load_policy.load_policy(expert_policy_file) print('loaded and built') returns = [] observations = [] actions = [] for i in range(num_rollouts): print('iter', i) obs = env.reset() done = False totalr = 0. steps = 0 while not done: action = policy_fn(obs[None,:]) #print("action", action) observations.append(obs) actions.append(action) obs, r, done, _ = env.step(action) totalr += r steps += 1 if steps % 100 == 0: print("%i/%i"%(steps, max_steps)) if steps >= max_steps: break returns.append(totalr) #print('returns', returns) #print('mean return', np.mean(returns)) #print('std of return', np.std(returns)) expert_data = { 'observations': np.array(observations), 'actions': np.array(actions), 'returns': np.array(returns) } if save: f = open("experts/"+envname+'.meta','wb') pickle.dump(expert_data, f) return expert_data def data_table_stats(data): mean = data['returns'].mean() std = data['returns'].std() return pd.Series({ 'mean reward': mean, 'std reward': std, }) def compare_data(data, imit_data, envname): df = pd.DataFrame({ 'expert': data_table_stats(data), 'imitation': data_table_stats(imit_data) }) print("Analyzing experiment", envname) print(df) def build_model(args, data, env): from keras.models import Sequential from keras.layers import Dense, Lambda from keras.optimizers import Adam mean, std = np.mean(data['observations'],axis=0), np.std(data["observations"], axis=0) + 1e-5 model = Sequential() model.add(Lambda(lambda x: (x-mean)/std, batch_input_shape=(None,env.observation_space.shape[0] ))) model.add(Dense(args.hidden, activation="tanh")) model.add(Dense(args.hidden, activation="tanh")) model.add(Dense(env.action_space.shape[0])) opt = Adam(lr=args.lr) model.compile(optimizer=opt, loss="mse", metrics=["mse"]) return model def test_model(model, args, env, envname, save=True): max_steps = env.spec.timestep_limit returns = [] observations = [] actions = [] for i in range(args.num_rollouts): obs = env.reset() done = False totalr = 0. steps = 0 while not done: action = model.predict(obs[None, :]) observations.append(obs) actions.append(action) obs, r, done, _ = env.step(action) totalr += r steps += 1 if args.render: env.render() if steps >= max_steps: break returns.append(totalr) imitation_data = {'observations': np.array(observations), 'actions': np.array(actions), 'returns': np.array(returns) } if save: pickle.dump(imitation_data, open("experts/"+envname+'.imit.meta','wb')) return imitation_data def run_expert_on_observations(observations, expert_policy_file): policy_fn = load_policy.load_policy(expert_policy_file) with tf.Session(): tf_util.initialize() actions = [] for obs in observations: action = policy_fn(obs[None,:]) actions.append(action) return np.array(actions)
/** * @author Marek Mikula * @version 17/5/21 */ public class GetEscapeModuleReadyOption implements TerminalOption { private final Terminal terminal; private final Game game; public GetEscapeModuleReadyOption(Terminal terminal, Game game) { this.terminal = terminal; this.game = game; } @Override public int getNumber() { return 1; } @Override public String getText() { return "Prepare the escape module"; } @Override public void handle() { ((EscapeModule) game.getMap().getRoom(RoomCode.ROOM_7).getItem(ItemCode.ITEM_6.getNumber())).setIsModuleReady(true); game.getTerminalHandler().output(terminal, "Module is ready to go!"); } @Override public Boolean shouldList() { return !((EscapeModule) game.getMap().getRoom(RoomCode.ROOM_7).getItem(ItemCode.ITEM_6.getNumber())).isModuleReady(); } }
def gen_NACA4_airfoil(p, m, xx, n_points): def yt(xx, xsi): a0 = 1.4845 a1 = 0.6300 a2 = 1.7580 a3 = 1.4215 a4 = 0.5075 return xx*(a0*np.sqrt(xsi) - a1*xsi - a2*xsi**2 + a3*xsi**3 - a4*xsi**4) def yc(p, m, xsi): def yc_xsi_lt_p(xsi): return (m/p**2)*(2*p*xsi - xsi**2) def dyc_xsi_lt_p(xsi): return (2*m/p**2)*(p - xsi) def yc_xsi_ge_p(xsi): return (m/(1 - p)**2)*(1 - 2*p + 2*p*xsi - xsi**2) def dyc_xsi_ge_p(xsi): return (2*m/(1 - p)**2)*(p - xsi) yc = np.array([yc_xsi_lt_p(x) if x < p else yc_xsi_ge_p(x) for x in xsi]) dyc = np.array([dyc_xsi_lt_p(x) if x < p else dyc_xsi_ge_p(x) for x in xsi]) return yc, dyc xsi = np.linspace(0, 1, n_points) yt = yt(xx, xsi) yc, dyc = yc(p, m, xsi) theta = np.arctan(dyc) x_upper = xsi - yt*np.sin(theta) y_upper = yc + yt*np.cos(theta) x_lower = xsi + yt*np.sin(theta) y_lower = yc - yt*np.cos(theta) upper = np.array([x_upper, y_upper]) lower = np.array([x_lower, y_lower]) return upper, lower
<reponame>tommyblue/golab-2020-go-game-development package main import ( "image/color" "log" "github.com/golang/freetype/truetype" "github.com/hajimehoshi/ebiten" "github.com/hajimehoshi/ebiten/text" "golang.org/x/image/font" ) const ( sampleText = `Hello, Gophers!` dpi = 72 fontSize = 36 ) type game struct{} var mplusNormalFont font.Face func (g *game) Update(screen *ebiten.Image) error { return nil } func (g *game) Draw(screen *ebiten.Image) { // calculate the rectangle containing the text bounds := text.BoundString(mplusNormalFont, sampleText) // write moving the text down by its height text.Draw(screen, sampleText, mplusNormalFont, 10, bounds.Dy(), color.White) } func (g *game) Layout(x, y int) (int, int) { return x, y } func init() { tt, err := truetype.Parse(Font) if err != nil { log.Fatal(err) } mplusNormalFont = truetype.NewFace(tt, &truetype.Options{ Size: fontSize, DPI: dpi, Hinting: font.HintingFull, }) } func main() { ebiten.SetWindowSize(640, 480) ebiten.SetWindowTitle("inputs") ebiten.RunGame(&game{}) }
package graphql.analysis; import graphql.Internal; import graphql.execution.ConditionalNodes; import graphql.execution.ValuesResolver; import graphql.introspection.Introspection; import graphql.language.Argument; import graphql.language.Directive; import graphql.language.Field; import graphql.language.FragmentDefinition; import graphql.language.FragmentSpread; import graphql.language.InlineFragment; import graphql.language.Node; import graphql.language.NodeVisitorStub; import graphql.language.ObjectField; import graphql.language.TypeName; import graphql.language.Value; import graphql.language.VariableDefinition; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLCodeRegistry; import graphql.schema.GraphQLCompositeType; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLFieldsContainer; import graphql.schema.GraphQLInputObjectField; import graphql.schema.GraphQLInputObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLUnmodifiedType; import graphql.util.TraversalControl; import graphql.util.TraverserContext; import java.util.Map; import static graphql.Assert.assertNotNull; import static graphql.schema.GraphQLTypeUtil.unwrapAll; import static graphql.util.TraverserContext.Phase.LEAVE; import static java.lang.String.format; /** * Internally used node visitor which delegates to a {@link QueryVisitor} with type * information about the visited field. */ @Internal public class NodeVisitorWithTypeTracking extends NodeVisitorStub { private final QueryVisitor preOrderCallback; private final QueryVisitor postOrderCallback; private final Map<String, Object> variables; private final GraphQLSchema schema; private final Map<String, FragmentDefinition> fragmentsByName; private final ConditionalNodes conditionalNodes = new ConditionalNodes(); private final ValuesResolver valuesResolver = new ValuesResolver(); public NodeVisitorWithTypeTracking(QueryVisitor preOrderCallback, QueryVisitor postOrderCallback, Map<String, Object> variables, GraphQLSchema schema, Map<String, FragmentDefinition> fragmentsByName) { this.preOrderCallback = preOrderCallback; this.postOrderCallback = postOrderCallback; this.variables = variables; this.schema = schema; this.fragmentsByName = fragmentsByName; } @Override public TraversalControl visitDirective(Directive node, TraverserContext<Node> context) { // to avoid visiting arguments for directives we abort the traversal here return TraversalControl.ABORT; } @Override public TraversalControl visitInlineFragment(InlineFragment inlineFragment, TraverserContext<Node> context) { if (!conditionalNodes.shouldInclude(variables, inlineFragment.getDirectives())) { return TraversalControl.ABORT; } QueryVisitorInlineFragmentEnvironment inlineFragmentEnvironment = new QueryVisitorInlineFragmentEnvironmentImpl(inlineFragment, context, schema); if (context.getPhase() == LEAVE) { postOrderCallback.visitInlineFragment(inlineFragmentEnvironment); return TraversalControl.CONTINUE; } preOrderCallback.visitInlineFragment(inlineFragmentEnvironment); // inline fragments are allowed not have type conditions, if so the parent type counts QueryTraversalContext parentEnv = context.getVarFromParents(QueryTraversalContext.class); GraphQLCompositeType fragmentCondition; if (inlineFragment.getTypeCondition() != null) { TypeName typeCondition = inlineFragment.getTypeCondition(); fragmentCondition = (GraphQLCompositeType) schema.getType(typeCondition.getName()); } else { fragmentCondition = parentEnv.getUnwrappedOutputType(); } // for unions we only have other fragments inside context.setVar(QueryTraversalContext.class, new QueryTraversalContext(fragmentCondition, parentEnv.getEnvironment(), inlineFragment)); return TraversalControl.CONTINUE; } @Override public TraversalControl visitFragmentDefinition(FragmentDefinition node, TraverserContext<Node> context) { if (!conditionalNodes.shouldInclude(variables, node.getDirectives())) { return TraversalControl.ABORT; } QueryVisitorFragmentDefinitionEnvironment fragmentEnvironment = new QueryVisitorFragmentDefinitionEnvironmentImpl(node, context, schema); if (context.getPhase() == LEAVE) { postOrderCallback.visitFragmentDefinition(fragmentEnvironment); return TraversalControl.CONTINUE; } preOrderCallback.visitFragmentDefinition(fragmentEnvironment); QueryTraversalContext parentEnv = context.getVarFromParents(QueryTraversalContext.class); GraphQLCompositeType typeCondition = (GraphQLCompositeType) schema.getType(node.getTypeCondition().getName()); context.setVar(QueryTraversalContext.class, new QueryTraversalContext(typeCondition, parentEnv.getEnvironment(), node)); return TraversalControl.CONTINUE; } @Override public TraversalControl visitFragmentSpread(FragmentSpread fragmentSpread, TraverserContext<Node> context) { if (!conditionalNodes.shouldInclude(variables, fragmentSpread.getDirectives())) { return TraversalControl.ABORT; } FragmentDefinition fragmentDefinition = fragmentsByName.get(fragmentSpread.getName()); if (!conditionalNodes.shouldInclude(variables, fragmentDefinition.getDirectives())) { return TraversalControl.ABORT; } QueryVisitorFragmentSpreadEnvironment fragmentSpreadEnvironment = new QueryVisitorFragmentSpreadEnvironmentImpl(fragmentSpread, fragmentDefinition, context, schema); if (context.getPhase() == LEAVE) { postOrderCallback.visitFragmentSpread(fragmentSpreadEnvironment); return TraversalControl.CONTINUE; } preOrderCallback.visitFragmentSpread(fragmentSpreadEnvironment); QueryTraversalContext parentEnv = context.getVarFromParents(QueryTraversalContext.class); GraphQLCompositeType typeCondition = (GraphQLCompositeType) schema.getType(fragmentDefinition.getTypeCondition().getName()); assertNotNull(typeCondition, () -> format("Invalid type condition '%s' in fragment '%s'", fragmentDefinition.getTypeCondition().getName(), fragmentDefinition.getName())); context.setVar(QueryTraversalContext.class, new QueryTraversalContext(typeCondition, parentEnv.getEnvironment(), fragmentDefinition)); return TraversalControl.CONTINUE; } @Override public TraversalControl visitField(Field field, TraverserContext<Node> context) { QueryTraversalContext parentEnv = context.getVarFromParents(QueryTraversalContext.class); GraphQLFieldDefinition fieldDefinition = Introspection.getFieldDef(schema, (GraphQLCompositeType) unwrapAll(parentEnv.getOutputType()), field.getName()); boolean isTypeNameIntrospectionField = fieldDefinition == schema.getIntrospectionTypenameFieldDefinition(); GraphQLFieldsContainer fieldsContainer = !isTypeNameIntrospectionField ? (GraphQLFieldsContainer) unwrapAll(parentEnv.getOutputType()) : null; GraphQLCodeRegistry codeRegistry = schema.getCodeRegistry(); Map<String, Object> argumentValues = valuesResolver.getArgumentValues(codeRegistry, fieldDefinition.getArguments(), field.getArguments(), variables); QueryVisitorFieldEnvironment environment = new QueryVisitorFieldEnvironmentImpl(isTypeNameIntrospectionField, field, fieldDefinition, parentEnv.getOutputType(), fieldsContainer, parentEnv.getEnvironment(), argumentValues, parentEnv.getSelectionSetContainer(), context, schema); if (context.getPhase() == LEAVE) { postOrderCallback.visitField(environment); return TraversalControl.CONTINUE; } if (!conditionalNodes.shouldInclude(variables, field.getDirectives())) { return TraversalControl.ABORT; } TraversalControl traversalControl = preOrderCallback.visitFieldWithControl(environment); GraphQLUnmodifiedType unmodifiedType = unwrapAll(fieldDefinition.getType()); QueryTraversalContext fieldEnv = (unmodifiedType instanceof GraphQLCompositeType) ? new QueryTraversalContext(fieldDefinition.getType(), environment, field) : new QueryTraversalContext(null, environment, field);// Terminal (scalar) node, EMPTY FRAME context.setVar(QueryTraversalContext.class, fieldEnv); return traversalControl; } @Override public TraversalControl visitArgument(Argument argument, TraverserContext<Node> context) { QueryTraversalContext fieldCtx = context.getVarFromParents(QueryTraversalContext.class); Field field = (Field) fieldCtx.getSelectionSetContainer(); QueryVisitorFieldEnvironment fieldEnv = fieldCtx.getEnvironment(); GraphQLFieldsContainer fieldsContainer = fieldEnv.getFieldsContainer(); GraphQLFieldDefinition fieldDefinition = Introspection.getFieldDef(schema, fieldsContainer, field.getName()); GraphQLArgument graphQLArgument = fieldDefinition.getArgument(argument.getName()); String argumentName = graphQLArgument.getName(); Object argumentValue = fieldEnv.getArguments().getOrDefault(argumentName, null); QueryVisitorFieldArgumentEnvironment environment = new QueryVisitorFieldArgumentEnvironmentImpl( fieldDefinition, argument, graphQLArgument, argumentValue, variables, fieldEnv, context, schema); QueryVisitorFieldArgumentInputValue inputValue = QueryVisitorFieldArgumentInputValueImpl .incompleteArgumentInputValue(graphQLArgument); context.setVar(QueryVisitorFieldArgumentEnvironment.class, environment); context.setVar(QueryVisitorFieldArgumentInputValue.class, inputValue); if (context.getPhase() == LEAVE) { return postOrderCallback.visitArgument(environment); } return preOrderCallback.visitArgument(environment); } @Override public TraversalControl visitObjectField(ObjectField node, TraverserContext<Node> context) { QueryVisitorFieldArgumentInputValueImpl inputValue = context.getVarFromParents(QueryVisitorFieldArgumentInputValue.class); GraphQLUnmodifiedType unmodifiedType = unwrapAll(inputValue.getInputType()); // // technically a scalar type can have an AST object field - eg field( arg : Json) -> field(arg : { ast : "here" }) if (unmodifiedType instanceof GraphQLInputObjectType) { GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) unmodifiedType; GraphQLInputObjectField inputObjectTypeField = inputObjectType.getField(node.getName()); inputValue = inputValue.incompleteNewChild(inputObjectTypeField); context.setVar(QueryVisitorFieldArgumentInputValue.class, inputValue); } return TraversalControl.CONTINUE; } @Override protected TraversalControl visitValue(Value<?> value, TraverserContext<Node> context) { if (context.getParentNode() instanceof VariableDefinition) { visitVariableDefinition(((VariableDefinition) context.getParentNode()), context); return TraversalControl.ABORT; } QueryVisitorFieldArgumentEnvironment fieldArgEnv = context.getVarFromParents(QueryVisitorFieldArgumentEnvironment.class); QueryVisitorFieldArgumentInputValueImpl inputValue = context.getVarFromParents(QueryVisitorFieldArgumentInputValue.class); // previous visits have set up the previous information inputValue = inputValue.completeArgumentInputValue(value); context.setVar(QueryVisitorFieldArgumentInputValue.class, inputValue); QueryVisitorFieldArgumentValueEnvironment environment = new QueryVisitorFieldArgumentValueEnvironmentImpl( schema, fieldArgEnv.getFieldDefinition(), fieldArgEnv.getGraphQLArgument(), inputValue, context, variables); if (context.getPhase() == LEAVE) { return postOrderCallback.visitArgumentValue(environment); } return preOrderCallback.visitArgumentValue(environment); } }
/** * When multi user settings are updated, this function triggers pertinent updates for central repository. * NOTE: If multi user settings were previously enabled and multi user settings are currently selected, this function assumes * there is a change in the postgres connectivity. * * @param parent The swing component that serves as a parent for dialogs that may arise. * @param muPreviouslySelected If multi user settings were previously enabled. * @param muCurrentlySelected If multi user settings are currently enabled as of most recent change. */ @NbBundle.Messages({ "GlobalSettingsPanel.onMultiUserChange.enable.title=Use with Central Repository?", "GlobalSettingsPanel.onMultiUserChange.enable.description=Do you want to update the Central Repository to use this PostgreSQL database?", "GlobalSettingsPanel.onMultiUserChange.enable.description2=The Central Repository stores hash values and accounts from past cases." }) public static void onMultiUserChange(Component parent, boolean muPreviouslySelected, boolean muCurrentlySelected) { boolean crEnabled = CentralRepoDbUtil.allowUseOfCentralRepository(); boolean crMultiUser = CentralRepoDbManager.getSavedDbChoice() == CentralRepoDbChoice.POSTGRESQL_MULTIUSER; boolean crDisabledDueToFailure = CentralRepoDbManager.isDisabledDueToFailure(); if (!muPreviouslySelected && muCurrentlySelected) { SwingUtilities.invokeLater(() -> { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(parent, "<html><body>" + "<div style='width: 400px;'>" + "<p>" + NbBundle.getMessage(GlobalSettingsPanel.class, "GlobalSettingsPanel.onMultiUserChange.enable.description") + "</p>" + "<p style='margin-top: 10px'>" + NbBundle.getMessage(GlobalSettingsPanel.class, "GlobalSettingsPanel.onMultiUserChange.enable.description2") + "</p>" + "</div>" + "</body></html>", NbBundle.getMessage(GlobalSettingsPanel.class, "GlobalSettingsPanel.onMultiUserChange.enable.title"), JOptionPane.YES_NO_OPTION)) { CentralRepoDbUtil.setUseCentralRepo(true); CentralRepoDbManager.saveDbChoice(CentralRepoDbChoice.POSTGRESQL_MULTIUSER); handleDbChange(parent); } }); } else if (muPreviouslySelected && !muCurrentlySelected && crEnabled && crMultiUser) { SwingUtilities.invokeLater(() -> { askForCentralRepoDbChoice(parent); }); } else if (muPreviouslySelected && muCurrentlySelected && crMultiUser && (crEnabled || crDisabledDueToFailure)) { CentralRepoDbUtil.setUseCentralRepo(true); handleDbChange(parent); } }
/** * This is the main application class of the webapp. * @author Lukas F&uuml;lling ([email protected]) */ @SpringBootApplication public class App implements CommandLineRunner { // The logger we use in this class Logger logger = LoggerFactory.getLogger(App.class); // The Database repository for users @Autowired private UserRepository userRepository; // The Database repository for configuration @Autowired private SysConfigRepository sysConfigRepository; public App() { } public static void main(String[] args) { // Run the springboot app SpringApplication.run(App.class, args); } @Override public void run(String... strings) throws Exception { // If root user isn't present or the 'deleteRoot' env is true, create a new root user and log the password logger.debug("Testing if root user exists"); User root = userRepository.findByUsername("root"); if (root == null) { logger.debug("Root user does not exist, creating a new one"); createNewRootUser(); } else if (Boolean.parseBoolean(System.getenv("deleteRoot"))) { logger.info("DeleteRoot env is set. Creating new root user..."); userRepository.delete("0"); createNewRootUser(); } else { logger.debug("Root user found"); } // Check settings for duplicates, if 'resetSettings' env is true, write default settings if (Boolean.parseBoolean(System.getenv("resetSettings"))) { logger.info("ResetSettings is set to true. Will now restore defaults..."); writeDefaultSettings(); } else { logger.debug("Probing settings:"); List<Config> configList = sysConfigRepository.findAll(); if (configList.isEmpty()) { writeDefaultSettings(); } if (!findDuplicates(configList).isEmpty()) { writeDefaultSettings(); } else { logger.debug("Found no duplicates."); } for (Config config : configList) { logger.debug("Found: " + config); } } } /** * Finds duplicates in a List. * @param listContainingDuplicates the list to check * @param <T> the type of the objects inside the list * @return the list as set (means there are no more dupes) */ public static <T> Set<T> findDuplicates(List<T> listContainingDuplicates) { final Set<T> setToReturn = new HashSet<>(); final Set<T> set1 = new HashSet<>(); setToReturn.addAll(listContainingDuplicates.stream().filter(yourT -> !set1.add(yourT)).collect(Collectors.toList())); //dafuq return setToReturn; } /** * Deletes all settings and writes default ones to db. */ private void writeDefaultSettings() { // Set the config options ArrayList<Config> configList = new ArrayList<>(); configList.add(new Config(Consts.KEY_APP_TITLE, "<%=appName%>")); // registration is public by default. configList.add(new Config(Consts.KEY_REGISTER_PUBLIC, "true")); // Do DB stuff sysConfigRepository.deleteAll(); sysConfigRepository.save(configList); logger.info("Settings reset to default!"); } /** * Creates a new root user and logs the password. */ private void createNewRootUser() throws CannotPerformOperationException { User root = new User(); root.setId("0"); root.setUsername("root"); root.setAdminState(true); root.setEmail("root@" + Consts.APPNAME.toLowerCase() + ".local"); root.setImage(generateSomeImage()); String password = UUID.randomUUID().toString().substring(0, 7); root.setPassword(PasswordStorage.createHash(password)); userRepository.save(root); logger.info("Created new root user.\n\n\tPassword: " + password + "\n"); } private String generateSomeImage() { int sz = 200; BufferedImage image = new BufferedImage( sz, sz, BufferedImage.TYPE_INT_ARGB); // paint the image.. Graphics2D g = image.createGraphics(); g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.WHITE); for (int ii = 0; ii < sz; ii += 5) { g.draw3DRect(ii, ii, sz - ii, sz - ii, true); } g.dispose(); // convert the image ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); } catch (IOException e) { logger.error("Unable to unable.", e); } String data = DatatypeConverter.printBase64Binary(baos.toByteArray()); return "data:image/png;base64," + data; } }
<filename>spec/patterns-test.ts import assert from 'assert'; import * as patterns from '../src/patterns'; describe("Channel pattern stuff", function() { describe("#compile", function() { it("supports wildcard matching", function() { let re = patterns.compile('cardstack:*'); assert.ok(re.test('cardstack:hello')); assert.ok(re.test('cardstack:*')); assert.ok(re.test('cardstack:')); }); it("properly escapes regex characters", function() { let re = patterns.compile('[abc]'); assert.ok(!re.test('a')); assert.ok(re.test('[abc]')); }); }); describe("#findMatch", function() { it("finds the last matching value from a list", function() { let rules: ([RegExp, number])[] = [ [/q/, 0], [/[abc]/, 1], [/./, 2] ]; let result = patterns.findMatch(rules, 'b', 100); assert.equal(result, 2); }); it("returns the default if none match", function() { let rules: ([RegExp, string])[] = [ [/q/, 'thing'] ]; let result = patterns.findMatch(rules, 'b', 'none'); assert.equal(result, 'none'); }); }); });
package jp.co.future.uroborosql.sample; import static org.junit.Assert.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.junit.BeforeClass; import org.junit.Test; /** * SqlAgentSampleクラスのテストケース * * (注意) * このテストケースをテストする際は、src/test/resources をクラスパスに含めてください。(sqlファイルが参照できません) * * @author H.Sugimoto * @version 2014/09/05 新規作成 */ public class SqlAgentSampleTest { private static SqlAgentSampleApp app = null; private static Map<String, Object> row1 = new LinkedHashMap<>(); private static Map<String, Object> row2 = new LinkedHashMap<>(); private static Map<String, Object> row3 = new LinkedHashMap<>(); @SuppressWarnings("deprecation") @BeforeClass public static void setUpBeforeClass() throws Exception { String url = "jdbc:h2:mem:SqlAgentSampleTest;DB_CLOSE_DELAY=-1"; String user = null; String password = null; try (Connection conn = DriverManager.getConnection(url, user, password)) { conn.setAutoCommit(false); // テーブル作成 try (Statement stmt = conn.createStatement()) { stmt.execute("create table if not exists test( id NUMERIC(4),name VARCHAR(10),age NUMERIC(5),birthday DATE )"); try (PreparedStatement pstmt = conn.prepareStatement("insert into test values (?, ?, ?, ?)")) { pstmt.setInt(1, 1); pstmt.setString(2, "aaa"); pstmt.setInt(3, 10); pstmt.setDate(4, new java.sql.Date(100, 0, 1)); pstmt.addBatch(); pstmt.setInt(1, 2); pstmt.setString(2, "あああ"); pstmt.setInt(3, 20); pstmt.setDate(4, new java.sql.Date(100, 1, 1)); pstmt.addBatch(); pstmt.setInt(1, 3); pstmt.setString(2, "1111"); pstmt.setInt(3, 3000); pstmt.setDate(4, new java.sql.Date(100, 2, 1)); pstmt.addBatch(); pstmt.executeBatch(); conn.commit(); } } } row1.put("ID", 1); row1.put("NAME", "aaa"); row1.put("AGE", 10); row1.put("BIRTHDAY", new java.sql.Date(100, 0, 1)); row2.put("ID", 2); row2.put("NAME", "あああ"); row2.put("AGE", 20); row2.put("BIRTHDAY", new java.sql.Date(100, 1, 1)); row3.put("ID", 3); row3.put("NAME", "1111"); row3.put("AGE", 3000); row3.put("BIRTHDAY", new java.sql.Date(100, 2, 1)); app = new SqlAgentSampleApp(url, user, password); } @Test public void sqlQueryTestNoParam() throws Exception { List<Map<String, Object>> actual = app.query("example/select_test"); List<Map<String, Object>> expected = new ArrayList<>(); expected.add(row1); expected.add(row2); expected.add(row3); assertEquals(toString(expected), toString(actual)); } @Test public void sqlQueryTestWithId() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("id", 1); List<Map<String, Object>> actual = app.query("example/select_test", params); List<Map<String, Object>> expected = new ArrayList<>(); expected.add(row1); assertEquals(toString(expected), toString(actual)); } @Test public void sqlQueryTestWithName() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("name", "あああ"); List<Map<String, Object>> actual = app.query("example/select_test", params); List<Map<String, Object>> expected = new ArrayList<>(); expected.add(row2); assertEquals(toString(expected), toString(actual)); } private String toString(final List<Map<String, Object>> obj) { return ToStringBuilder.reflectionToString(obj, ToStringStyle.SHORT_PREFIX_STYLE); } }
/** * test if add given two nums overflow * * @param operand1 first * @param operand2 second * @param result result after the adding * @return 1 means overflow, 0 means not */ private String addOverFlow(String operand1, String operand2, String result) { int X = operand1.charAt(0) - '0'; int Y = operand2.charAt(0) - '0'; int S = result.charAt(0) - '0'; return "" + ((~X & ~Y & S) | (X & Y & ~S)); }
<reponame>CodeSeoul/JavaAbstractStaticFinal package org.codeseoul.java.intro; public interface IWritable { public void write(); }
// This is a very dumb implementation for getData handling // by default GDCM simply drop the BulkData so we need to store // the actual BulkData somewhere for proper implementation of getData class SimpleFileXMLPrinter : public XMLPrinter { public: void HandleBulkData(const char *uuid, const TransferSyntax & ts, const char *bulkdata, size_t bulklen) { std::ofstream out( uuid, std::ios::binary ); out.write( bulkdata, bulklen ); out.close(); std::string tsfn = uuid; tsfn += ".ts"; const char *tsstring = ts.GetString(); assert( tsstring ); std::ofstream out2( tsfn.c_str(), std::ios::binary ); out2.write( tsstring, strlen(tsstring) ); out2.close(); } }
// AttemptLogin takes the token and server configuration it is given, and tries to call the /jobs endpoint on the server // If it gets a 200 OK, it assumes login is fine, if not, it returns an error func AttemptLogin(server string, token string) error { if server == "" { return errors.New("server is missing") } req, err := http.NewRequest("GET", fmt.Sprintf("%s/datasets", server), nil) utils.HandleError(err) if token != "" { req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) } pterm.Println() introSpinner, err := pterm.DefaultSpinner.WithRemoveWhenDone(true).Start("Login in to: " + server) utils.HandleError(err) resp, err := http.DefaultClient.Do(req) utils.HandleError(err) time.Sleep(500 * time.Millisecond) err = introSpinner.Stop() utils.HandleError(err) if resp.StatusCode != http.StatusOK { bodyBytes, err := ioutil.ReadAll(resp.Body) utils.HandleError(err) message := &Response{} err = json.Unmarshal(bodyBytes, message) return errors.New(message.Message) } defer func() { _ = resp.Body.Close() }() pterm.Success.Println("Logged in to " + server) return nil }
<filename>samples/vault api/Insert.ts import {Skyflow, generateBearerToken, isExpired, setLogLevel, LogLevel} from "skyflow-node"; var filePath = "<YOUR_CREDENTIAL_FILE>"; setLogLevel(LogLevel.INFO) var bearerToken = "" const skyflow = Skyflow.init({ vaultID: "<VAULT_ID>", vaultURL: "<VAULT_URL>", getBearerToken: () => { return new Promise((resolve, reject) => { if(!isExpired(bearerToken)) { resolve(bearerToken) } else { generateBearerToken(filePath) .then((res) => { bearerToken = res.accessToken resolve(bearerToken); }) .catch((err) => { reject(err); }); } }) } }); const response = skyflow.insert({ records: [ { fields: { card_number: "411111111111111", expiry_date: "11/22", fullname : "firstNameTest" }, table: "cards", }, ], },{tokens:true}); response .then( (res) => { console.log("insert result:"); console.log(JSON.stringify(res)); }, (err) => { console.log("insert error:"); console.log(JSON.stringify(err)); } ) .catch((err) => { console.log("insert exception:"); console.log(JSON.stringify(err)); });
/** * Creates and releases all periods (including ad periods) defined in the last timeline to be * returned from {@link #prepareSource()}, {@link #assertTimelineChange()} or * {@link #assertTimelineChangeBlocking()}. */ public void assertPrepareAndReleaseAllPeriods() { Timeline.Period period = new Timeline.Period(); for (int i = 0; i < timeline.getPeriodCount(); i++) { assertPrepareAndReleasePeriod(new MediaPeriodId(i)); timeline.getPeriod(i, period); for (int adGroupIndex = 0; adGroupIndex < period.getAdGroupCount(); adGroupIndex++) { for (int adIndex = 0; adIndex < period.getAdCountInAdGroup(adGroupIndex); adIndex++) { assertPrepareAndReleasePeriod(new MediaPeriodId(i, adGroupIndex, adIndex)); } } } }
// Code generated by "stringer --type=TocType"; DO NOT EDIT package mmvdump import "fmt" const _TocType_name = "TocIndomsTocInstancesTocMetricsTocValuesTocStrings" var _TocType_index = [...]uint8{0, 9, 21, 31, 40, 50} func (i TocType) String() string { i -= 1 if i < 0 || i >= TocType(len(_TocType_index)-1) { return fmt.Sprintf("TocType(%d)", i+1) } return _TocType_name[_TocType_index[i]:_TocType_index[i+1]] }
def _locateCommands(self, tag, contents, start): output = [] ind = start startTag = "<" + tag + ">" endTag = "</" + tag + ">" while ind < len(contents): if startTag in contents[ind]: currentLine = "" command = [] while True: if ind == len(contents): print "ERROR: End of file reached while parsing " + self.name sys.exit() if "<br>" in contents[ind]: temp = contents[ind].split("<br>") currentLine += temp[0] command.append(currentLine.strip()) for i in range(1,len(temp)-1): command.append(temp[i].strip()) currentLine = temp[len(temp)-1].strip() else: currentLine += " " + contents[ind].strip() if endTag in contents[ind]: currentLine = re.sub(endTag,"",currentLine) command.append(currentLine.strip()) break ind = ind + 1 output.append(command) ind = ind + 1 return output
Twenty Years of Riparian Zone Research (1997-2017): Where to Next? Riparian zones have been used for water quality management with respect to NO in subsurface flow and total P (TP), sediments, and pesticides in overland flow for decades. Only recently has the fate and transport of soluble reactive P (SRP), Hg, emerging contaminants, and greenhouse gas (GHG) fluxes (NO, CO, and CH) been examined in riparian zones. Overall, riparian zones are efficient at reducing emerging contaminants in subsurface flow and only function as hot spots of methylmercury production in the landscape when dominated by Hg-rich wet organic soils. However, riparian zones do not provide consistent benefits with respect to SRP removal or GHG emissions. Although most existing riparian models almost exclusively focus on NO removal, recent developments in riparian models demonstrate the potential for using easily accessible digital environmental datasets to simulate and scale up riparian functions beyond NO removal to include SRP, TP, and GHG dynamics. To further inform integrated watershed management efforts, more research should be conducted on how various practices, including stream restoration, subsurface drainage, two-stage ditches, beaver dam analogues, denitrification bioreactors and permeable reactive barriers, artificial wetlands, and short-rotation forestry crops affect riparian water and air quality functions. Riparian zone benefits should be discussed not only with respect to water and air quality, but also in terms of recreation, habitat for wildlife, and other ecosystem services. More research is needed to fully address potential water quality or air quality tradeoffs associated with riparian zone management in a multicontaminant-multiuse landscape context.
a=list(map(int,open(0)));print(["Yay!",":("][max(a[:5])-min(a[:5])>a[5]])
<reponame>soygul/recursion-tree-visualizer // a partir de uma adjList, determina a melhores coordenadas (x,y) de cada nó import { Point, TreeNode, AdjList } from '../../../types' // dado uma árvore, retorna as coordenadas de cada vértice no svg de uma forma esteticamente agradável export default function getCoords(adjList: AdjList, rootId = 0) { const rawCoords: Record<number, Point> = {} // rawCoords[u]: coordenada do vértice u const rawTopLeft: Point = [0, 0] const rawBottomRight: Point = [0, 0] if (Object.keys(adjList).length > 0) { const root: TreeNode = { id: rootId, parent: null, children: [], x: 0, y: 0, mod: 0, // modifier, valor pendente para ser incrementado no x de todos os filhos do nó atual, o que não inclui ele mesmo thread: undefined, // aponta para o próximo nó do contour } initNodes(root) // constroi o objeto root a partir da adjList firstTraversal(root) // post-order traversal lastTraversal(root) // pre-order traversal } return { rawCoords, rawTopLeft, rawBottomRight } function initNodes(node: TreeNode, nodeId = rootId, nodeDepth = 0) { if (adjList[nodeId] === undefined) return // for each child of node for (const { v: childId } of adjList[nodeId]) { const child = { id: childId, parent: node, x: 0, y: nodeDepth + 1, mod: 0, children: [], } node.children.push(child) initNodes(child, childId, nodeDepth + 1) } } function firstTraversal(node: TreeNode): TreeNode { if (node.children.length === 0) return node if (node.children.length === 1) { node.x = firstTraversal(node.children[0]).x return node } // para cada par de sub-árvores filhas leftChild e rightChild const [firstChild, ...children] = node.children let leftChild = firstTraversal(firstChild) for (const child of children) { const rightChild = firstTraversal(child) // post-order traversal below shiftRightSubtree(leftChild, rightChild) leftChild = rightChild } node.x = centralX(node.children) return node } // desloca toda a sub-árvore enraizada por right para o mais próximo possível da sub-árvore enraizada por left de forma que não haja nenhum conflito function shiftRightSubtree(left: TreeNode, right: TreeNode) { let { li, ri, lo, ro, diff, leftOffset, rightOffset } = contour(left, right) // desloca right right.x += diff right.mod += diff if (right.children.length > 0) rightOffset += diff // se as subárvores left e right tem alturas diferentes if (ri && !li) { lo.thread = ri // define a thread lo -> ri lo.mod = rightOffset - leftOffset } else if (li && !ri) { ro.thread = li // define a thread ro -> li ro.mod = leftOffset - rightOffset ro.mod += li.parent?.mod || 0 // preserva o mod que li tinha de seu pai para o agora mod de ro } } // retorna os contornos das sub-árvores left e tree function contour( left: TreeNode, right: TreeNode, leftOuter?: TreeNode, rightOuter?: TreeNode, maxDiff?: number, leftOffset = 0, rightOffset = 0 ): { li: TreeNode ri: TreeNode lo: TreeNode ro: TreeNode diff: number leftOffset: number rightOffset: number } { let currDiff = left.x + leftOffset - (right.x + rightOffset) + 1 maxDiff = Math.max(maxDiff || currDiff, currDiff) const li = nextRight(left) // left inner const ri = nextLeft(right) // right inner let lo = nextLeft(leftOuter || left) // left outer let ro = nextRight(rightOuter || right) // right outer if (li && ri) { leftOffset += left.mod rightOffset += right.mod return contour(li, ri, lo, ro, maxDiff, leftOffset, rightOffset) } lo = leftOuter || left ro = rightOuter || right return { li, ri, lo, ro, diff: maxDiff, leftOffset, rightOffset } } // atualiza o x real dos nós function lastTraversal(node: TreeNode, accMod = 0) { // console.log(node.id, node.x, node.mod) node.x += accMod // console.log(`${node.id}: [${node.x}, ${node.y}]`) rawCoords[node.id] = [node.x, node.y] rawBottomRight[0] = Math.max(rawBottomRight[0], node.x) rawBottomRight[1] = Math.max(rawBottomRight[1], node.y) for (const child of node.children) lastTraversal(child, accMod + node.mod) } } // retorna o próximo nó depois de node no contorno function nextRight(node: TreeNode) { return node.thread || node.children[node.children.length - 1] || null } function nextLeft(node: TreeNode) { return node.thread || node.children[0] || null } // retorna o x central de nodes function centralX(nodes: TreeNode[]) { const { length } = nodes return length % 2 === 0 ? (nodes[0].x + nodes[length - 1].x) / 2 : nodes[(length - 1) / 2].x }
<reponame>zeroam/TIL """cal_prod.py 10만번 곱한 시간 측정 """ import time def cal_prod(): product = 1 for i in range(1, 100000): product = product * i return product if __name__ == "__main__": start_time = time.time() prod = cal_prod() end_time = time.time() print(f"The result is {len(str(prod))} digits long") print(f"Took {end_time - start_time} seconds to calculate")
UNITED NATIONS (Reuters) - The U.N. peacekeeping chief strongly denied on Wednesday allegations from the Philippines’ army chief that Filipino peacekeepers in the Golan Heights were ordered to surrender their weapons to Islamist militants who had trapped them. Philippine Armed Forces chief General Gregorio Pio Catapang Jr. gestures as he speaks during a forum with members of Foreign Correspondents Association of the Philippines (FOCAP) in Mandaluyong city, Metro Manila September 2, 2014. REUTERS/Erik De Castro Filipino army chief General Gregorio Catapang said his soldiers had defended themselves against Islamist rebels last weekend in defiance of an order from their U.N. force commander to surrender their weapons, a move that would be highly controversial in the six-nation, blue-helmeted force. The U.N.’s under-secretary-general for peacekeeping, Herve Ladsous, denied that any such order was given. The back-and-forth underlines a rise in tensions in the U.N. peacekeeping force following weekend skirmishes with Islamist militants in Israeli-controlled territory on Syria’s southeastern border. Islamist fighters battling the Syrian army overran last week a crossing point in the line that has separated Israelis from Syrians in the Golan Heights since a 1973 war, the most recent escalation of Syria’s civil war, now in its fourth year. The fighters then turned against U.N. blue helmets from a peacekeeping force that has patrolled the ceasefire line since 1974. After 45 Fijians were captured on Thursday, 72 Filipinos were besieged at two other locations for two days by militants before they escaped. The militants, believed to be part of an al-Qaeda-linked group known as Nusra Front, are still holding the 45 Fijian members of the United Nations’ UNDOF Golan Heights force. Catapang said that at one point while the Filipinos were trapped, UNDOF Force Commander General Iqbal Singh Singha of India ordered the soldiers to surrender their arms to prevent harm from befalling the captured Fijians. Asked what order was given to the Filipinos, Ladsous replied, “Never to hand over weapons.” The order was simply “not to shoot,” he said. One U.N. official told Reuters that no force commander would order his troops to hand over weapons to rebels. If that were to happen, the official said, the commander would “be out of a job” since countries that supply weapons and materiel to the force would be reluctant to re-supply the mission. Several Security Council diplomats said the issue of what orders might have been given was discussed on Wednesday in a closed-door meeting of the 15-nation body. In that meeting, Ladsous expressed full support for Singha, diplomats who were present told Reuters. Ladsous later told reporters that Singha had “exercised good sound judgment all along” during the crisis. Ladsous said the United Nations had not confirmed that the militants who attacked the Filipinos and are holding the Fijians belong to Nusra Front. UNDOF troops were kidnapped twice last year and in both cases were released unharmed.
#include <stdlib.h> #include <SDL/sge.h> #include "font.h" #include "misc.h" const char * const FONT_DIR = DATA_DIR "/font"; sge_TTFont *font_load(const char *file, int ptsize) { char buf[1024]; sge_TTFont *font; snprintf(buf, 1024, "%s/%s", FONT_DIR, file); font = sge_TTF_OpenFont(buf, ptsize); if (!font) { fprintf(stderr, "unable to load font: %s: %s\n", file, SDL_GetError()); exit(1); } return font; }
A chip-interleaving DS SS system and its performance under on-off wide-band jamming A modified direct sequence spread spectrum system employing the concept of chip-interleaving is proposed. Its performance under periodic on-off wide-band jamming is analyzed and closed-form bit error rate (BER) performances of the proposed system for both the best case and the worst case are obtained. The proposed system is compared with conventional system using numerical examples.
def linear_skeleton(): rows = np.arange(1,11) coords = np.zeros((10,3), dtype=int) coords[:,0] = rows**2 radii = rows.astype(np.float32) links = [-1, *range(1,10)] df = pd.DataFrame({'rowId': rows, 'x': coords[:,0], 'y': coords[:,1], 'z': coords[:,2], 'radius': radii, 'link': links}) return df
package app.services.api; import java.util.List; import app.domain.dtos.venues.VenueXmlDto; import app.domain.dtos.venues.VenueinSofiaXmlDto; import app.domain.entities.Venue; public interface VenueService { void save(Venue entity); void save(List<Venue> entity); List<Venue> findAll(); Venue findOneById(Long id); Long count(); void saveFromVenueXmlDtos(List<VenueXmlDto> venueXmlDtos); List<VenueinSofiaXmlDto> findAllVenuesInSofia(); }
/** * Servlet filter responsible merely for setting up {@link InvocationContext}. All servlets relaying on * {@link InvocationContext} should be wrapped by this filter. This filter must be installed after the authentication * filter, if the latter is used. * @author K. Benedyczak */ public class InvocationContextSetupFilter implements Filter { private static final Logger log = Log.getLogger(Log.U_SERVER_WEB, InvocationContextSetupFilter.class); public static final String LANGUAGE_COOKIE = "language"; private UnityServerConfiguration config; private AuthenticationRealm realm; private String baseAddress; private List<AuthenticationFlow> authenticationFlows; /** * @param baseAddress public address of the server with scheme and port, with empty path. */ public InvocationContextSetupFilter(UnityServerConfiguration config, AuthenticationRealm realm, String baseAddress, List<AuthenticationFlow> authenticationFlows) { this.realm = realm; this.config = config; this.baseAddress = baseAddress; this.authenticationFlows = authenticationFlows; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; InvocationContext ctx = createInvocationContext(httpRequest); setLoginSession(httpRequest, ctx); setLocale(httpRequest, ctx); try { chain.doFilter(httpRequest, response); } finally { InvocationContext.setCurrent(null); } } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } private InvocationContext createInvocationContext(HttpServletRequest request) { X509Certificate[] clientCert = (X509Certificate[]) request.getAttribute( "javax.servlet.request.X509Certificate"); IdentityTaV tlsId = (clientCert == null) ? null : new IdentityTaV(X500Identity.ID, clientCert[0].getSubjectX500Principal().getName()); InvocationContext context = new InvocationContext(tlsId, realm, authenticationFlows); InvocationContext.setCurrent(context); if (baseAddress != null) context.setCurrentURLUsed(baseAddress); log.trace("A new invocation context was set"); return context; } private void setLoginSession(HttpServletRequest request, InvocationContext ctx) { HttpSession session = request.getSession(false); if (session != null) { LoginSession ls = (LoginSession) session.getAttribute( LoginToHttpSessionBinder.USER_SESSION_KEY); if (ls != null) { ctx.setLoginSession(ls); log.trace("Login session was set for the invocation context"); } } } /** * Sets locale in invocation context. If there is cookie with selected and still supported * locale then it is used. Otherwise a default locale is set. */ private void setLocale(HttpServletRequest request, InvocationContext context) { String value = CookieHelper.getCookie(request, LANGUAGE_COOKIE); if (value != null) { Locale locale = UnityServerConfiguration.safeLocaleDecode(value); if (config.isLocaleSupported(locale)) { context.setLocale(locale); log.trace("Requested locale was set for the invocation context"); return; } } context.setLocale(config.getDefaultLocale()); log.trace("Default locale was set for the invocation context"); } }
/** * Deserialize a given {@link DataInput} as a {@link BlobMessage} object * @param pInput * @return returns the {@link BlobMessage} for the given {@link DataInput} * @throws IOException */ public static BlobMessage deserializeOnlyMeta(InputStream pInput) throws IOException{ byte[] pBytes = new byte[pInput.available()]; pInput.read(pBytes); ByteArrayDataInput input = ByteStreams.newDataInput(pBytes); int argC = input.readInt(); Map<String, String> args = new HashMap<String, String>(); for (int i = 0; i < argC; i++) { byte[] keyByte = new byte[input.readInt()]; input.readFully(keyByte); String key = new String(keyByte, "UTF-8"); byte[] valueByte = new byte[input.readInt()]; input.readFully(valueByte); String value = new String(valueByte, "UTF-8"); args.put(key, value); } int dataHashSize = input.readInt(); byte[] datahash = new byte[dataHashSize]; input.readFully(datahash); BlobMessage message = new BlobMessage(null); message.setArgs(args); message.setDataHash(datahash); return message; }
#pragma once #ifdef CH2_PLATFORM_WINDOWS #ifdef CH2_BUILD_DLL #define CHAOS2D_API __declspec(dllexport) #else #define CHAOS2D_API __declspec(dllimport) #endif #else #error Chaos2D only supports Windows #endif #define BIT(X) (1 << X)
from sys import stdin,stdout n=int(input()) cycles=list(map(int,stdin.readline().split())) total=0 for i in range(n): cycle=cycles[i] aretes=cycle-1 total=(total+aretes)%2 if total%2==0: stdout.write("2"+"\n") else: stdout.write("1"+"\n")
def is_VDLRecord_file(path): return "vdlrecords" in path
<reponame>dcu/capn-hook<filename>core/default_manifests.go package core // DefaultManifest returns a default manifest func DefaultManifest() *Manifest { return &Manifest{ PreCommit: []*Hook{ &Hook{ Pattern: "*", Run: []string{ "echo {files}", "echo {file}", }, Required: false, }, }, } } // DefaultGolangManifest returns a default manifest for golang func DefaultGolangManifest() *Manifest { return &Manifest{ PreCommit: []*Hook{ &Hook{ Pattern: "*.go", Run: []string{ "golint -min_confidence 0.3 -set_exit_status {files}", "gocyclo -over 10 {file}", "varcheck", "deadcode", "structcheck", }, Required: true, }, }, PrePush: []*Hook{ &Hook{ Run: []string{ "go test .", }, Required: true, }, }, PostReceive: []*Hook{ &Hook{ Pattern: "glide.*", Run: []string{ "glide install", }, Required: false, }, }, } } // DefaultRubyManifest returns a default manifest for ruby func DefaultRubyManifest() *Manifest { return &Manifest{ PreCommit: []*Hook{ &Hook{ Pattern: "*.rb", Run: []string{ "rubycritic -f console {files}", }, Required: true, }, &Hook{ Pattern: "Gemfile*", Run: []string{ "dawn -z -K .", }, Required: true, }, }, PostReceive: []*Hook{ &Hook{ Pattern: "Gemfile*", Run: []string{ "bundle install", }, Required: false, }, }, } } // DefaultAndroidManifest returns the default manifest for android func DefaultAndroidManifest() *Manifest { return &Manifest{ PreCommit: []*Hook{ &Hook{ Pattern: "*.java", Run: []string{ "lint .", }, Required: false, }, &Hook{ Pattern: "*.xml", Run: []string{ "lint .", }, Required: false, }, }, } }
<reponame>mhuisi/lean4 // Lean compiler output // Module: Init.Default // Imports: Init.Core Init.Control Init.Data.Basic Init.WF Init.Data Init.System Init.Util Init.Fix Init.LeanInit Init.ShareCommon #include "runtime/lean.h" #if defined(__clang__) #pragma clang diagnostic ignored "-Wunused-parameter" #pragma clang diagnostic ignored "-Wunused-label" #elif defined(__GNUC__) && !defined(__CLANG__) #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-label" #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif #ifdef __cplusplus extern "C" { #endif lean_object* initialize_Init_Core(lean_object*); lean_object* initialize_Init_Control(lean_object*); lean_object* initialize_Init_Data_Basic(lean_object*); lean_object* initialize_Init_WF(lean_object*); lean_object* initialize_Init_Data(lean_object*); lean_object* initialize_Init_System(lean_object*); lean_object* initialize_Init_Util(lean_object*); lean_object* initialize_Init_Fix(lean_object*); lean_object* initialize_Init_LeanInit(lean_object*); lean_object* initialize_Init_ShareCommon(lean_object*); static bool _G_initialized = false; lean_object* initialize_Init_Default(lean_object* w) { lean_object * res; if (_G_initialized) return lean_mk_io_result(lean_box(0)); _G_initialized = true; res = initialize_Init_Core(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_Control(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_Data_Basic(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_WF(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_Data(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_System(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_Util(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_Fix(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_LeanInit(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Init_ShareCommon(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); return lean_mk_io_result(lean_box(0)); } #ifdef __cplusplus } #endif
/** * Returns the result of calling {@link CacheLoader#loadAll}, or null if {@code loader} doesn't * implement {@code loadAll}. */ @Nullable Map<K, V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader) throws ExecutionException { checkNotNull(loader); checkNotNull(keys); Stopwatch stopwatch = Stopwatch.createStarted(); Map<K, V> result; boolean success = false; try { @SuppressWarnings("unchecked") Map<K, V> map = (Map<K, V>) loader.loadAll(keys); result = map; success = true; } catch (UnsupportedLoadingOperationException e) { success = true; throw e; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ExecutionException(e); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } finally { if (!success) { globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS)); } } if (result == null) { globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS)); throw new InvalidCacheLoadException(loader + " returned null map from loadAll"); } stopwatch.stop(); boolean nullsPresent = false; for (Entry<K, V> entry : result.entrySet()) { K key = entry.getKey(); V value = entry.getValue(); if (key == null || value == null) { nullsPresent = true; } else { put(key, value); } } if (nullsPresent) { globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS)); throw new InvalidCacheLoadException(loader + " returned null keys or values from loadAll"); } globalStatsCounter.recordLoadSuccess(stopwatch.elapsed(NANOSECONDS)); return result; }
/** * MQTT Service to connect to a MQTT message broker and subscribe to all messages. * @author Thomas Pilz */ public class MqttService implements MqttCallback { private static final Logger logger = LoggerFactory.getLogger(MqttService.class); private Consumer<KpiMsg> onValidMessageListener; private final MqttClientPersistence persistence; private final MqttConnectionOptions connectionOptions; private static final ObjectMapper jsonMapper = new ObjectMapper(); private final String msgBrokerUrl; private final String clientId; public MqttService(String msgBrokerUrl, String clientId, Consumer<KpiMsg> onValidMessageListener) { this.msgBrokerUrl = msgBrokerUrl; this.clientId = clientId; // Set memory persistence to prevent paho to create lots of lock files this.persistence = new MemoryPersistence(); // Set MQTT connection options this.connectionOptions = new MqttConnectionOptionsBuilder() .automaticReconnect(true) .cleanStart(true) .build(); this.onValidMessageListener = onValidMessageListener; } public MqttService(String msgBrokerUrl, String clientId){ this(msgBrokerUrl, clientId, msg -> {}); } public void connectAndSubscribeAll(){ try { // Use async MQTT client for better performance/ non-blocking operations logger.info("Attempting to connect to {} as {}", msgBrokerUrl, clientId); var client = new MqttAsyncClient(msgBrokerUrl, clientId, persistence); client.setCallback(this); var conToken = client.connect(connectionOptions, new MqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { logger.warn("Failed to connect to {}", msgBrokerUrl, exception); } }); conToken.waitForCompletion(); client.subscribe("#", 0); } catch (MqttException e) { logger.warn("Failed to connect due to exception.", e); } } public Consumer<KpiMsg> getOnValidMessageListener() { return onValidMessageListener; } public void setOnValidMessageListener(Consumer<KpiMsg> onValidMessageListener) { this.onValidMessageListener = onValidMessageListener; } public void onValidMessageReceived(Consumer<KpiMsg> listener, KpiMsg kpiMsg){ listener.accept(kpiMsg); } @Override public void disconnected(MqttDisconnectResponse disconnectResponse) { logger.warn("Disconnect from MQTT message broker: Reason Code: {}; Reason: {}", disconnectResponse.getReturnCode(), disconnectResponse.getReasonString()); } @Override public void mqttErrorOccurred(MqttException exception) { logger.warn("An MQTT error occurred!", exception); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { logger.debug("Received message of topic {}", topic); /* JsonNode msg = null; try { msg = new ObjectMapper().readTree(message.getPayload()); } catch (IOException e){ logger.warn("Received message could not be parsed as JSON. Message is ignored."); return; } var validation = Validator.isMsgValid(msg); if(!validation.isValid()) { logger.warn(validation.getErrMsg()); return; } System.out.println("parsed");*/ // now we know the type of the message; No need to catch DatabindException as validator ensures message has the right format KpiMsg kpiMsg; try { kpiMsg = jsonMapper.readValue(message.getPayload(), KpiMsg.class); } catch (DatabindException e){ logger.warn("Received message does not conform to required structure.", e); return; } catch (IOException e){ logger.warn("Could not parse message for topic {}", topic, e); return; } logger.debug("Parsed message: {}", kpiMsg.toString()); onValidMessageListener.accept(kpiMsg); } @Override public void deliveryComplete(IMqttToken token) { } @Override public void connectComplete(boolean reconnect, String serverURI) { if(reconnect) logger.info("Successfully reconnected to {}", serverURI); else logger.info("Successfully connected to {}", serverURI); } @Override public void authPacketArrived(int reasonCode, MqttProperties properties) { } }
print("".strip()) print(" \t\n\r\v\f".strip()) print(" T E S T".strip()) print("abcabc".strip("ce")) print("aaa".strip("b")) print("abc efg ".strip("g a")) print(' spacious '.lstrip()) print('www.example.com'.lstrip('cmowz.')) print(' spacious '.rstrip()) print('mississippi'.rstrip('ipz')) print(b'mississippi'.rstrip(b'ipz')) try: print(b'mississippi'.rstrip('ipz')) except TypeError: print("TypeError") try: print('mississippi'.rstrip(b'ipz')) except TypeError: print("TypeError") # single-char subj string used to give a problem print("a".strip()) print("a".lstrip()) print("a".rstrip()) print(" a".strip()) print(" a".lstrip()) print(" a".rstrip()) print("a ".strip()) print("a ".lstrip()) print("a ".rstrip()) # \0 used to give a problem print("\0abc\0".strip()) print("\0abc\0".lstrip()) print("\0abc\0".rstrip()) print("\0abc\0".strip("\0")) # Test that stripping unstrippable string returns original object s = "abc" print(id(s.strip()) == id(s))
def football(players): if any(len(x) >= 7 for x in players.split("0") + players.split("1")): print("YES") else: print("NO") football(input())
#include <bits/stdc++.h> using namespace std; using ll = int64_t; using P = pair<ll, ll>; using mat = vector<vector<ll>>; inline void IOS() { ios::sync_with_stdio(false), cin.tie(0); } template <typename A, size_t N, typename T> void Fill(A (&array)[N], const T &val){ fill((T *)array, (T *)(array + N), val); } const ll INF = 1e16; const ll MOD = 1e9 + 7; //int dx[4] = {1,0,-1,0}; //int dy[4] = {0,1,0,-1}; //ll pas[5001][5002]; signed main(){ IOS(); ll a, b, c; cin >> a >> b >>c; if(a + b > c){ cout << b + c << endl; } else { ll ans = b; cout << ans + min(a + b + 1, c) << endl; } }
from .utils import RequestHandler, HTTPException, role_admitted, scanAllLinks, export from .controllers import Roles, add_event_to_user, verify_token, remove_event_from_user from .controllers import get_event, get_all_events, update_event, get_user_events, get_user_tags import json class Events(RequestHandler): @role_admitted(Roles.USER, Roles.ADMIN) def get(self): token = self.request.headers['HTTP_AUTHORIZATION'] user_urlsafe = verify_token(token) user_tags = get_user_tags(user_urlsafe) event_data = [] events = get_all_events(user_tags) for event in events: event_dict = {} event_dict["id"] = event.urlsafe event_dict["title"] = event.title event_dict["image_link"] = event.image_link event_dict["description"] = event.description event_dict["location"] = event.location event_dict["date"] = event.date.strftime("%Y-%m-%d %H:%M") event_data.append(event_dict) json_data = json.dumps(event_data) return json_data @role_admitted(Roles.USER, Roles.ADMIN) def post(self): event_urlsafe = self.request.payload.get("event_id") field_name = self.request.payload.get("field_name") modification = self.request.payload.get("modification") if not event_urlsafe or field_name or modification: raise HTTPException("400", "Please specify all fields") update_event(event_urlsafe, field_name, modification) return {} class EventInfo(RequestHandler): @role_admitted(Roles.USER, Roles.ADMIN) def get(self): urlsafe = self.request.args["event_id"] if not urlsafe: raise HTTPException("400", "Please specify event id") event = get_event(urlsafe) event_dict = {} event_dict["id"] = event.urlsafe event_dict["title"] = event.title event_dict["image_link"] = event.image_link event_dict["description"] = event.description event_dict["location"] = event.location event_dict["date"] = event.date.strftime("%Y-%m-%d %H:%M") if event.price: event_dict["price"] = event.price else: event_dict["price"] = "-" if event.capacity: event_dict["capacity"] = event.capacity else: event_dict["capacity"] = "-" tag_names = [] for tag in event.tags: tag_entity = tag.get() tag_names.append(tag_entity.name) event_dict["tags"] = tag_names return event_dict class MyEvents(RequestHandler): @role_admitted(Roles.USER, Roles.ADMIN) def get(self): event_data = [] token = self.request.headers['HTTP_AUTHORIZATION'] user_urlsafe = verify_token(token) events = get_user_events(user_urlsafe) print (events) for event_key in events: event = event_key.get() if event is None: continue event_dict = {} event_dict["id"] = event.urlsafe event_dict["title"] = event.title event_dict["image_link"] = event.image_link event_dict["description"] = event.description event_dict["location"] = event.location event_dict["date"] = event.date.strftime("%Y-%m-%d %H:%M") event_data.append(event_dict) json_data = json.dumps(event_data) return json_data @role_admitted(Roles.USER, Roles.ADMIN) def put(self): event_urlsafe = self.request.payload.get('event_id') if not event_urlsafe: raise HTTPException("400", "Please specify event id") event = get_event(event_urlsafe) token = self.request.headers['HTTP_AUTHORIZATION'] user_urlsafe = verify_token(token) add_event_to_user(user_urlsafe, event.key) return {'status':'200', 'message':'Event heart succesfully added'} @role_admitted(Roles.USER, Roles.ADMIN) def delete(self): event_urlsafe = self.request.payload.get('event_id') if not event_urlsafe: raise HTTPException("400", "Please specify event id") event = get_event(event_urlsafe) token = self.request.headers['HTTP_AUTHORIZATION'] user_urlsafe = verify_token(token) remove_event_from_user(user_urlsafe, event.key) return {'status':'200', 'message':'Event heart succesfully removed'} class Calendar(RequestHandler): @role_admitted(Roles.USER, Roles.ADMIN) def get(self): token = self.request.headers['HTTP_AUTHORIZATION'] user_urlsafe = verify_token(token) data = export(user_urlsafe) return data.encode('utf-8') class EventsCrawl(RequestHandler): def get(self): scanAllLinks() return {}
<reponame>sfc-gh-xwang/keen import styled from 'styled-components'; import { colors } from '@keen.io/colors'; export const StyledColorPalette = styled.div` display: flex; flex-wrap: wrap; gap: 3px; `; export const SortableContainer = styled.div` display: flex; flex-wrap: wrap; gap: 3px; `; export const AddColorButton = styled.div` width: 70px; height: 37px; position: relative; cursor: pointer; border: 1px solid ${colors.gray[300]}; background-color: ${colors.gray[200]}; box-sizing: border-box; display: flex; align-items: center; justify-content: center; `; export const StyledContainer = styled.div<{ x: number; y: number }>` position: absolute; top: ${(props) => props.y}px; left: ${(props) => props.x}px; `;
def digit(x): if x <= 0: return 0 return x % 10 + digit(x // 10) n = int(input().strip()) ans = min(digit(a) + digit(n-a) for a in range(1, n)) print (ans)
/** * Stub class for performance testing. Replacement for {@link deltix.qsrv.hf.tickdb.impl.TickCursorImpl}. */ public class TickCursorStub1 /*implements TickCursor*/ { public final MessageSourceMultiplexer <InstrumentMessage> mx; private InstrumentToObjectMap<Byte> subscribedEntities = new InstrumentToObjectMap<Byte>(); private boolean isSubscribedToAllEntities = true; private Set <String> subscribedTypeNames = null; // // Current message data, guarded by the virtual query thread // private InstrumentMessage currentMessage; private RecordClassDescriptor currentType; private TickStream currentStream; private TypedMessageSource currentSource = null; private boolean inRealtime = false; private boolean realTimeNotifications = false; // // Monitoring objects // private volatile boolean closed = false; public TickCursorStub1(boolean live) { //this.options = options; this.realTimeNotifications = false; mx = new MessageSourceMultiplexer<>(true, false); mx.setLive (live); if (live) // live mode should use allowLateOutOfOrder mx.setAllowLateOutOfOrder(true); else mx.setAllowLateOutOfOrder (false); } private boolean isSubscribed(IdentityKey iid) { // no allocations if (subscribedEntities.containsKey(iid)) return true; return false; } public boolean next () { boolean ret; RuntimeException x = null; Runnable lnr; //nextWatch.start(); synchronized (mx) { for (;;) { //x1Watch.start(); try { boolean hasNext; try { hasNext = mx.syncNext(); } catch (RuntimeException xx) { x = xx; ret = false; // make compiler happy break; } if (!hasNext) { ret = false; break; } } finally { //x1Watch.stop(); } //x2Watch.start(); currentMessage = mx.syncGetMessage (); //x2Watch.stop(); //x3Watch.start(); try { // current message is indicator of real-time mode if (realTimeNotifications && mx.isRealTimeStarted()) { currentType = Messages.REAL_TIME_START_MESSAGE_DESCRIPTOR; ret = inRealtime = true; break; } if (!isSubscribedToAllEntities && !isSubscribed(currentMessage)) { if (DebugFlags.DEBUG_MSG_DISCARD) { DebugFlags.discard( "TB DEBUG: Discarding message " + currentMessage + " because we are not subscribed to its entity" ); } if (closed) throw new CursorIsClosedException(); continue; } } finally { //x3Watch.stop(); } //x4Watch.start(); //x4a1Watch.start(); final TypedMessageSource source = (TypedMessageSource) mx.syncGetCurrentSource (); //x4a1Watch.stop(); //x4a2Watch.start(); //x4a2Watch.start(); currentStream = null;//((TickStreamRelated) source).getStream (); currentSource = source; //x4a2Watch.stop(); //x4a3Watch.start(); if (currentMessage.getClass () == RawMessage.class) currentType = ((RawMessage) currentMessage).type; else currentType = source.getCurrentType (); //x4a3Watch.stop(); //x4Watch.stop(); //x5Watch.start(); try { if (subscribedTypeNames != null && !subscribedTypeNames.contains(currentType.getName())) { if (DebugFlags.DEBUG_MSG_DISCARD) { DebugFlags.discard( "TB DEBUG: Discarding message " + currentMessage + " because we are not subscribed to its type" ); } if (closed) throw new CursorIsClosedException(); continue; } } finally { //x5Watch.stop(); } //x6Watch.start(); //stats.register (currentMessage); ret = true; //x6Watch.stop(); break; } // // Surprisingly, even mx.next () can call the av lnr (on truncation) // //lnr = lnrTriggered (); } //x7Watch.start(); /* if (lnr != null) lnr.run ();*/ //x7Watch.stop(); //nextWatch.stop(); if (x != null) throw x; return (ret); } public InstrumentMessage getMessage () { return (currentMessage); } @Override public String toString () { StringBuilder sb = new StringBuilder (); sb.append ("TickCursorImpl(").append(this.hashCode()).append(") <== ["); sb.append ("]"); return (sb.toString ()); } public void reset (long time) { } public boolean isRealTime() { return inRealtime; } public boolean realTimeAvailable() { return realTimeNotifications; } public void subscribeToAllEntities() { } public void close() { } }
package com.swapab.cctv.creditcard.usecase; public class UserDoesNotExistsException extends RuntimeException { public UserDoesNotExistsException() { super("User not found"); } }
#include <bits/stdc++.h> using namespace std; using ll = long long; #define IOS \ ios::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0) #define CAS \ int cas; \ cin >> cas; \ while (cas--) template <typename T, typename... Args> void test(T x, Args... args) { cerr << x << " "; test(args...); } #define il inline #define ll long long #define ld long double #define ull unsigned long long #define rep(i, a, b) for (register int i = a; i < b; i++) #define Rep(i, a, b) for (register int i = a; i <= b; i++) #define per(i, a, b) for (register int i = b - 1; i >= a; i--) #define Per(i, a, b) for (register int i = b; i >= a; i--) #define pb push_back #define eb emplace_back #define MP make_pair #define fi first #define se second #define SZ(x) (x).size() #define LEN(x) (x).length() #define ALL(X) (X).begin(), (X).end() #define MS0(X) memset((X), 0, sizeof((X))) #define MS1(X) memset((X), -1, sizeof((X))) #define MS(X, a) memset((X), a, sizeof(X)) #define CASET \ int ___T; \ scanf("%d", &___T); \ for (register int cs = 1; cs <= ___T; cs++) #define Read(x) scanf("%d", &x) #define Read2(x, y) scanf("%d%d", &x, &y) #define Read3(x, y, z) scanf("%d%d%d", &x, &y, &z) #define Read4(x, y, z, t) scanf("%d%d%d%d", &x, &y, &z, &t) #define ind(x) scanf("%d", &x) #define inlf(x) scanf("%lf", &x) #define inll(x) scanf("%lld", &x) #define inllf(x) scanf("%llf", &x) #define outd(x) printf("%d\n", x) #define outf(x) printf("%f\n", x) #define outlld(x) printf("%lld\n", x) #define outLf(x) printf("%Lf\n", x) #define IO \ ios::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); constexpr ld pi = acos(-1); constexpr ll mod = 1e9 + 7; #define lowbit(x) (x & (-x)) constexpr ld eps = 1e-6; constexpr int maxn = 1e5 + 10; constexpr int INF = 0x3f3f3f3f; constexpr ll LLINF = 0x3f3f3f3f3f3f3f3f; constexpr double e = 2.718281828459045; typedef long long LL; typedef unsigned long long ULL; typedef long double LD; typedef pair<int, int> PII; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<PII> VPII; typedef pair<LL, LL> PLL; typedef vector<PLL> VPLL; typedef vector<int> VI; typedef pair<int, int> PII; #define Accepted 0 inline ll quick(ll a, ll b, ll m) { ll ans = 1; while (b) { if (b & 1) ans = (a * ans) % m; a = (a * a) % m; b >>= 1; } return ans; } inline ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } inline void ADD(int &a, int b) { a += b; if (a >= mod) a -= mod; if (a < 0) a += mod; } inline ll LCM(ll a, ll b) { return a / __gcd(a, b) * b; } inline ll inverse(ll a, ll p) { return quick(a, p - 2, p); } struct Min_25 { ll n, Sqr, w[maxn]; ll prime[maxn], id1[maxn], id2[maxn], h[maxn], g[maxn], m; bool vis[maxn]; int tot, sp[maxn], sp2[maxn]; void pre(int n) //预处理出质数 { //举例f=p^2-p tot = 0; //则需要筛出p和p^2的素数处的前缀和 memset(vis, 0, sizeof(vis)); vis[1] = true; for (int i = 2; i <= n; i++) { if (!vis[i]) prime[++tot] = i, sp[tot] = (sp[tot - 1] + i) % mod, sp2[tot] = (sp2[tot - 1] + 1ll * i * i % mod) % mod; // sp为质数的前缀和 ,sp2为素数平方处的前缀和 for (int j = 1; j <= tot && i * prime[j] <= n; j++) { vis[i * prime[j]] = true; if (i % prime[j] == 0) break; } } } void init(ll n) { m = 0; for (ll l = 1, r; l <= n; l = r + 1) { r = n / (n / l); w[++m] = n / l; //积性函数f(p)由几个多项式生成就需要几个预处理的函数 //比如f(p)=p^3-p^2+p-1就需要预处理i^3 i^2 i 1这四个前缀和 //此处h需要维护素数个数的前缀和,初始化为所有数的前缀和 h[m] = (w[m] % mod) * ((w[m] + 1) % mod) % mod * inverse(2, mod) % mod; //举例f=p^2-p h处理2,3,..n的和,g处理2^2,3^2,...n^2的前缀和 h[m]--; //(把所有数都当做质数初始化) h(x)=f1(2)+f1(3)+...+f1(n) g[m] = ((w[m] % mod) * ((w[m] + 1) % mod) % mod) % mod * ((2 * w[m] + 1) % mod) % mod * inverse(6, mod) % mod; g[m]--; //此处g维护f(p)的前缀和 还是将所有数当做质数 //(因此初始化为所有数的前缀和) g(x)=f2(2)+...+f2(x) if (w[m] <= Sqr) id1[w[m]] = m; //用来存小于sqrt(n)整除分块的序号 w[m]<sqrt(n) else id2[r] = m; //用来存w[n/m] 减少数组内存为sqrt(n)数量级 } //我们需要求出每个g(n/i,|P|)的值,因为在递归求S中只需要这些位置的值 //接下来利用g(n/l,0)来递推g(n/l,|P|); for (int j = 1; j <= tot; j++) { for (int i = 1; i <= m && prime[j] * prime[j] <= w[i]; i++) { int k = (w[i] / prime[j] <= Sqr) ? id1[w[i] / prime[j]] : id2[n / (w[i] / prime[j])]; //找到k在哪个块 即[n/(l*prime[i])]被存在哪个g/h里面 g[i] = (g[i] - 1ll * (prime[j] * prime[j] % mod) * ((g[k] - sp2[j - 1]) % mod) % mod) % mod; // g(n,j)=g(n,j-1)-f(p_j)(g(n/p_j,j-1)-sum{i=1}^{j-1}(f(pi))) //此处分别f=p^2,f=p; h[i] = (h[i] - 1ll * prime[j] * (h[k] - sp[j - 1]) % mod) % mod; } } } ll S(ll x, int y) { // S(n,j)=g(n,|P|)-\sum{i=1}^{j-1}(f(i))+\sum{k>j&&p_k^(e+1)<=n}^{}(f(p_k^e)*S(n/(p_k^e),k+1)+f(p_k^(e+1))) if (x <= 1 || prime[y] > x) return 0; ll k = (x <= Sqr) ? id1[x] : id2[n / x], ret = ((g[k] - h[k]) % mod - ((sp2[y - 1] - sp[y - 1]) % mod)) % mod; //初始化g(x,|P|)-\sum{i=1}^{y-1}(f(i)) for (int i = y; i <= tot && 1ll * prime[i] * prime[i] <= x; ++i) { ll t1 = prime[i], t2 = 1ll * prime[i] * prime[i]; // t1->p^e t2->p^(e+1) for (int e = 1; t2 <= x; ++e, t1 = t2, t2 *= prime[i]) { ret = (ret + ((1ll * S(x / t1, i + 1) * ((t1 % mod) * ((t1 - 1) % mod) % mod) % mod + ((t2 % mod) * ((t2 - 1) % mod) % mod) % mod))) % mod; //(f(p_k^e)*S(n/(p_k^e),k+1)+f(p_k^(e+1))) } } return ret; } ll query(ll nn) { n = nn; memset(id1, 0, sizeof(id1)); memset(id2, 0, sizeof(id2)); Sqr = sqrt(nn); pre(Sqr); init(nn); ll ans = S(nn, 1) + 1; //最后加上f(1) if (ans < 0) ans += mod; return ans; } } M; int ans[maxn]; int ask(int t, int i, int j, int x) { cout << "? " << t << " " << i << " " << j << " " << x << endl; cout.flush(); int y; cin >> y; return y; } int main() { int n; CAS { memset(ans, 0, sizeof(ans)); M.init(maxn); cin >> n; int tmp1 = -1, tmp; bool flag = false; for (int i = 1; i < n; i += 2) { tmp = ask(1, i, i + 1, n - 1); if (tmp == n) { tmp1 = i + 1; ans[tmp1] = n; break; } else if (tmp == n - 1) { tmp = ask(1, i + 1, i, n - 1); if (tmp == n) { tmp1 = i; ans[tmp1] = n; break; } else { flag = true; tmp = ask(1, i, i + 1, n - 2); if (tmp == n - 2) { tmp1 = i; ans[tmp1] = n - 1; break; } else { tmp1 = i + 1; ans[tmp1] = n - 1; break; } } } } for (int i = 1; i <= n; i++) { if (i == tmp1) continue; tmp = ask(2, i, tmp1, 1); ans[i] = tmp; } cout << "! "; for (int i = 1; i <= n; i++) { if (ans[i] == n - 1 && tmp1 != i && flag) cout << n << " "; else cout << ans[i] << " "; } cout << endl; cout.flush(); } return 0; }
/****************************************************************** * * This code is for the Complaints service project. * * * © 2018, Complaints Management All rights reserved. * * ******************************************************************/ package com.zed.config.security; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { }
def parse(self, line, offset): splits = [x for x in line.expandtabs(1).split(" ") if len(x) > 0] assert len(splits) + offset >= 5, "Help: %s" % (line,) self.gmtoff = splits[2 - offset] self.rule = splits[3 - offset] self.format = splits[4 - offset] if len(splits) >= 6 - offset: self.until = " ".join(splits[5 - offset:])
<reponame>justidle2012/XJOI_Solution<filename>Lv1/9291/9291.cpp<gh_stars>1-10 #include <cstdio> int main() { printf("I LOVE OI.\n"); return 0; }
<filename>packages/crusher-electron-app/src/extension/ui/app.tsx import React, { useEffect, useMemo, useRef, useState } from "react"; import { render } from "react-dom"; import { SidebarActionsBox } from "./containers/app/sidebarActionsBox"; import { BrowserWindow } from "./containers/app/browserWindow"; import configureStore, { getStore } from "../redux/store"; import { Provider } from "react-redux"; import { recorderMessageListener } from "../messageListener"; import ReactModal from "react-modal"; import { ModalManager } from "./containers/app/modals"; import { AdvancedURL } from "../utils/url"; import { ACTIONS_IN_TEST } from "@shared/constants/recordedActions"; import { recordAction } from "../redux/actions/actions"; import { submitPostDataWithForm } from "../utils/helpers"; import { resolveToBackendPath } from "@shared/utils/url"; import { Conditional } from "./components/conditional"; import { StartupModal } from "./containers/app/modals/startupModal"; import "../style/main.css"; const App = () => { const deviceIframeRef = useRef<HTMLIFrameElement>(null); const [recordingStartTime] = useState(new Date()); const [url] = useState(AdvancedURL.getUrlFromCrusherExtensionUrl(window.location.href)); useEffect(() => { const isReturningUser = localStorage.getItem("lastVisit"); if (isReturningUser) { localStorage.setItem("lastVisit", Date.now().toString()); } }, []); const saveTest = () => { const store = getStore(); const steps = store.getState().actions.list; const lastActionTime = store.getState().actions.last_action; if (!lastActionTime) { return; } submitPostDataWithForm(resolveToBackendPath("test/goToEditor", process.env.BACKEND_URL), { events: escape(JSON.stringify(steps)), totalTime: lastActionTime.getTime() - recordingStartTime.getTime(), }); }; useMemo(() => { const store = getStore(); const device = AdvancedURL.getDeviceFromCrusherExtensionUrl(window.location.href); const userAgent = AdvancedURL.getUserAgentFromUrl(AdvancedURL.getUrlFromCrusherExtensionUrl(window.location.href) as string); store.dispatch( recordAction({ type: ACTIONS_IN_TEST.SET_DEVICE, payload: { meta: { device: device, userAgent: userAgent, }, }, }), ); window.addEventListener("message", recorderMessageListener.bind(window, deviceIframeRef)); }, []); return ( <div style={containerStyle}> <Conditional If={url}> <BrowserWindow deviceIframeRef={deviceIframeRef} saveTestCallback={saveTest} /> <SidebarActionsBox deviceIframeRef={deviceIframeRef} /> <ModalManager deviceIframeRef={deviceIframeRef} /> </Conditional> <Conditional If={!url}> <StartupModal isOpen={true} /> </Conditional> <link rel="stylesheet" href={chrome.runtime.getURL("/styles/devices.min.css")} /> <link rel="stylesheet" href={chrome.runtime.getURL("/styles/app.css")} /> <link rel="stylesheet" href={chrome.runtime.getURL("/styles/fonts.css")} /> <style>{` .CodeMirror { font-size: 0.9rem; } .ReactModalPortal { height: 100%; } `}</style> </div> ); }; const containerStyle = { display: "flex", height: "100%", background: "rgb(40, 40, 40)", }; ReactModal.setAppElement("#root"); render( <Provider store={configureStore()}> <App /> </Provider>, document.querySelector("#root"), );
// Get the record for key, apply wildcard if bare record doesn't work func (s *RedisDNSServer) Get(key string) *Record { keys := append([]string{key}, wildcardKeys(key)...) r := &Record{} for i := 0; i < len(keys); i++ { bAry := Lookup(s.redisClient, keys[i]) if bAry != nil { err := r.Parse(bAry) if err != nil { log.Printf("Error parsing JSON %s: %s\n", keys[i], err) return r } if r.TTL == 0 { r.TTL = TTL } return r } } return r }
""" denoise, mainly concerning the motion artefacts some of the CPSC2020 records have segments of severe motion artefacts, such segments should be eliminated from feature computation Process ------- 1. detect segments of nearly constant values, and slice these segments out 2. detect motion artefact (large variation of values in a short time), and further slice the record into segments without motion artefact 3. more? References ---------- to add """ from typing import Union, Optional, List from numbers import Real import numpy as np from easydict import EasyDict as ED from train.train_crnn_cpsc2020.utils import mask_to_intervals __all__ = [ "ecg_denoise", ] def ecg_denoise(filtered_sig:np.ndarray, fs:Real, config:ED) -> List[List[int]]: """ finished, checked, a naive function removing non-ECG segments (flat and motion artefact) Parameters ---------- filtered_sig: ndarray, 1d filtered (typically bandpassed) ECG signal, fs: real number, sampling frequency of `filtered_sig` config: dict, configs of relavant parameters, like window, step, etc. Returns ------- intervals: list of (length 2) list of int, list of intervals of non-noise segment of `filtered_sig` """ _LABEL_VALID, _LABEL_INVALID = 1, 0 # constants siglen = len(filtered_sig) window = int(config.get("window", 2000) * fs / 1000) # 2000 ms step = int(config.get("step", window/5)) ampl_min = config.get("ampl_min", 0.2) # 0.2 mV ampl_max = config.get("ampl_max", 6.0) # 6 mV mask = np.zeros_like(filtered_sig, dtype=int) if siglen < window: result = [] return result # detect and remove flat part n_seg, residue = divmod(siglen-window+step, step) start_inds = [idx*step for idx in range(n_seg)] if residue != 0: start_inds.append(siglen-window) n_seg += 1 for idx in start_inds: window_vals = filtered_sig[idx:idx+window] ampl = np.max(window_vals)-np.min(window_vals) if ampl > ampl_min: mask[idx:idx+window] = _LABEL_VALID # detect and remove motion artefact window = window // 2 # 1000 ms step = window // 5 n_seg, residue = divmod(siglen-window+step, step) start_inds = [idx*step for idx in range(n_seg)] if residue != 0: start_inds.append(siglen-window) n_seg += 1 for idx in start_inds: window_vals = filtered_sig[idx:idx+window] ampl = np.max(window_vals)-np.min(window_vals) if ampl > ampl_max: mask[idx:idx+window] = _LABEL_INVALID # mask to intervals interval_threshold = int(config.get("len_threshold", 5)*fs) # 5s intervals = mask_to_intervals(mask, _LABEL_VALID) intervals = [item for item in intervals if item[1]-item[0]>interval_threshold] return intervals
/** * Add the given user to a group. * * @param ac * @param groupUuid * Group uuid * @param userUuid * Uuid of the user which should be added to the group */ public void handleAddUserToGroup(InternalActionContext ac, String groupUuid, String userUuid) { validateParameter(groupUuid, "groupUuid"); validateParameter(userUuid, "userUuid"); db.asyncTx(() -> { Group group = boot.get().groupRoot().loadObjectByUuid(ac, groupUuid, UPDATE_PERM); User user = boot.get().userRoot().loadObjectByUuid(ac, userUuid, READ_PERM); ResultInfo info = db.tx(() -> { SearchQueueBatch batch = searchQueue.create(); group.addUser(user); batch.store(group, true); GroupResponse model = group.transformToRestSync(ac, 0); return new ResultInfo(model, batch); }); return info.getBatch().processAsync().andThen(Single.just(info.getModel())); }).subscribe(model -> ac.send(model, OK), ac::fail); }
Peri-implant strain around mesially inclined two-implant-retained mandibular overdentures with Locator attachments. This study aimed to evaluate the peri-implant strain around mesially inclined implants used to retain mandibular overdentures with Locator resilient attachments. Four mandibular edentulous acrylic resin models received two implants in the canine areas with 0°, 5°, 10°, and 20° mesial inclinations. Overdentures were connected to the implants using Locator attachments. Pink nylon inserts (light retention) were used for all implant inclinations, and red inserts were used for 20° inclination (20°red). Four strain gages were bonded on the mesial (M), distal (D), buccal (B), and lingual (L) surfaces of each implant. Peri-implant strains were measured during bilateral and unilateral loading. The 20° inclination showed the highest strain, followed by 10° and 5°, and both 0° and 20°red presented with the lowest strain. Site D was associated with the highest strain, followed by M, B, and L, which showed the lowest strain values. Unilateral loading and the loading side presented with significantly higher strain values than bilateral loading and the nonloading side, respectively. Hence, in this study, strains around the two-implant-retained overdentures with Locator attachments increased with increases in mesial implant angulation, except when red male inserts were used.
<filename>projects/ngx-grid-core/src/lib/ui/cell/cell-types/value-parsing/parsers/base-parser.abstract.ts import { GridControllerService } from '../../../../../controller/grid-controller.service' import { IGridCellCoordinates, IGridValueParsingResult } from '../../../../../typings/interfaces' import { TAtLeast } from '../../../../../typings/types/at-least.type' import { IParsingTest } from './parsing-test.interface' export abstract class BaseParser implements IParsingTest { public abstract run(gridController: GridControllerService, cellCoords: TAtLeast<IGridCellCoordinates, 'columnKey'>): IGridValueParsingResult public abstract readonly initialValue: any public return(isValid: boolean, transformedValue: any = undefined): IGridValueParsingResult { const { initialValue } = this const isInvalid = !isValid if (isValid && transformedValue === undefined) transformedValue = initialValue return { initialValue, isInvalid, isValid, transformedValue, } } public passed(transformedValue: any = undefined): IGridValueParsingResult { return this.return(true, transformedValue) } public failed(transformedValue: any = undefined): IGridValueParsingResult { return this.return(false, transformedValue) } }
def configure_mailing_list(name: str) -> Result: command(["/usr/sbin/config_list", "--inputfile", "/root/mailman-newlist-defaults", name]) return Result(State.success)
/** * MyEventQueue class serves as a custom event queue that can be modified * upon the necessity of a particular Test */ class MyEventQueue extends EventQueue { private boolean dispatchEventCalled = false; public boolean isDispatchEventCalled() { return dispatchEventCalled; } public void dispatchEvent(AWTEvent event) { dispatchEventCalled = true; super.dispatchEvent(event); } }
#include <bits/stdc++.h> using namespace std; int main(){ int c,d; cin>>c>>d; if (c==d) cout<<0; else if (c > d){ int pdif= (d+360 - c); int ndif = (c - d); if (ndif == pdif) cout<<180; else if (ndif < pdif) cout<<(-1*ndif); else cout<<pdif; } else{ int pdif = d-c; int ndif = (c+360)-d; if (ndif == pdif) cout<<180; else if (ndif < pdif) cout<<(-1*ndif); else cout<<pdif; } }
#include<bits/stdc++.h> #define ll long long #define ff first #define ss second #define pb push_back using namespace std; const int N = 1e6 + 69; ll n,x,ans,ans1; ll A[N],rao[N][27]; string s; int main(){ cin>>s; n = s.size(); s = '#' + s; for(int i=1;i<=n;i++){ for(int j=0;j<26;j++) rao[i][j] = rao[i-1][j] + (j == s[i]-'a'); } for(int i=0;i<26;i++){ ans = max(ans,rao[n][i]); } for(int i=0;i<26;i++){ for(int j=0;j<26;j++){ //if(i==j)continue; ans1 = 0; for(int t=1;t<=n;t++) if(s[t] == i+'a'){ ans1 += rao[t-1][j]; } ans = max(ans,ans1); } } cout<<ans<<endl; }
<gh_stars>0 """ Classe responsavel por fazer o mapeamento dos arquivos .csv para teste e para treino da rede tratando as respostas esperadas para o problema e gerando dicionarios para melhor manipulá-los Functions: init(self): Inicia a leitura do arquivo. handle_input: Funcao que le o arquivo .csv retornando um dicioncario de dados para ser usado na rede neural. arquivo(self): Funcao que guarda o objeto do retorno da funcao 'handle_input' na variavel _arquivo. arquivo(self,value): Funcao que 'seta' os valores do objeto guardado pela funcao 'arquivo(self)' na variavel _arquivo. get_target(self, target): Funcao que retorna o valor esperado dentro da rede de acordo com o target alfanumerico """ import csv from src.env import ARQUIVOS_PARA_TREINO, ARQUIVOS_PARA_TESTE class Mapper: def __init__(self): self._arquivos = self.get_multiple_files() self.arquivos_teste = self.get_test_file() @property def arquivos(self): return self._arquivos @arquivos.setter def arquivos(self, value): self._arquivos = value def get_multiple_files(self): result = [] for arquivo in ARQUIVOS_PARA_TREINO: result.append(self.handle_input(arquivo)) return result def get_test_file(self): result = [] for arquivo in ARQUIVOS_PARA_TESTE: result.append(self.handle_input(arquivo)) return result def handle_input(self, filename): inputs = [] caminho_arquivo = '../inputs/Part-1/' + filename with open(caminho_arquivo, 'rt', encoding="utf-8-sig") as data: dados_arquivo = csv.reader(data) for linha in dados_arquivo: target = self.get_target(linha[-1]) sample = linha[:-1] inputs.append({ 'target_description': linha[-1], 'target': target, 'sample': sample }) result = {'nome_problema': filename[:-4], 'inputs': inputs} return result def get_target(self, target): dict = { 'A': [1, 0, 0, 0, 0, 0, 0], 'B': [0, 1, 0, 0, 0, 0, 0], 'C': [0, 0, 1, 0, 0, 0, 0], 'D': [0, 0, 0, 1, 0, 0, 0], 'E': [0, 0, 0, 0, 1, 0, 0], 'J': [0, 0, 0, 0, 0, 1, 0], 'K': [0, 0, 0, 0, 0, 0, 1], '0': [0], '1': [1] } """ O target dos outros problemas e transformado em lista para que a rede seja generica para todos os problemas em questao """ return dict[target]
// RegisterV1LiveCheckService Register the blademaster route with middleware map // midMap is the middleware map, the key is defined in proto func RegisterV1LiveCheckService(e *bm.Engine, svc LiveCheck, midMap map[string]bm.HandlerFunc) { v1LiveCheckSvc = svc e.GET("/xlive/resource/v1/liveCheck/LiveCheck", liveCheckLiveCheck) e.GET("/xlive/resource/v1/liveCheck/GetLiveCheckList", liveCheckGetLiveCheckList) e.GET("/xlive/resource/v1/liveCheck/AddLiveCheck", liveCheckAddLiveCheck) }
/** * Non-public helper class used by {@link MxParser} to parse the business header * in its two variants, using MxNode. * * @author [email protected] * @since 7.8.4 */ class MxBusinessHeaderParser { private static final transient Logger log = Logger.getLogger(MxBusinessHeaderParser.class.getName()); /** * Parses the application header from the parameter node. * @return parsed header or null if the content cannot be parsed or the header is not present in the xml */ static ApplicationHeader parseApplicationHeader(final MxNode tree) { final long t0 = System.currentTimeMillis(); try { if (tree != null) { final MxNode header = tree.findFirstByName(MxParser.HEADER_LOCALNAME); if (header == null) { log.warning(MxParser.HEADER_LOCALNAME + " element not found"); } else { final ApplicationHeader result = new ApplicationHeader(); /* * From */ MxNode From = header.findFirst("./From"); if (From != null) { result.setFrom(new EntityIdentification()); MxNode Type = From.findFirst("./Type"); if (Type != null) { result.getFrom().setType(Type.getValue()); } MxNode Id = From.findFirst("./Id"); if (Id != null) { result.getFrom().setId(Id.getValue()); } } /* * To */ MxNode To = header.findFirst("./To"); if (To != null) { result.setTo(new EntityIdentification()); MxNode Type = To.findFirst("./Type"); if (Type != null) { result.getTo().setType(Type.getValue()); } MxNode Id = To.findFirst("./Id"); if (Id != null) { result.getTo().setId(Id.getValue()); } } /* * Service name */ MxNode SvcName = header.findFirst("./SvcName"); if (SvcName != null) { result.setSvcName(SvcName.getValue()); } /* * Message name */ MxNode MsgName = header.findFirst("./MsgName"); if (MsgName != null) { result.setMsgName(MsgName.getValue()); } /* * Message reference */ MxNode MsgRef = header.findFirst("./MsgRef"); if (MsgRef != null) { result.setMsgRef(MsgRef.getValue()); } /* * Date */ MxNode CrDate = header.findFirst("./CrDate"); if (CrDate != null) { try { result.setCrDate(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(CrDate.getValue())); } catch (final javax.xml.datatype.DatatypeConfigurationException e) { log.warning("exception " + e + " parsign header crDate [" + CrDate.getValue() + "]"); } } /* * Duplicate information */ MxNode Dup = header.findFirst("./Dup"); if (Dup != null) { result.setDup(new DuplicateIndication()); MxNode Ref = Dup.findFirst("./Ref"); if (Ref != null) { result.getDup().setRef(Ref.getValue()); } MxNode Info = Dup.findFirst("./Info"); if (Info != null) { result.getDup().setInfo(Info.getValue()); } } return result; } } } finally { final long t1 = System.currentTimeMillis(); log.fine("parseApplicationHeader_sax: " + (t1 - t0) + "ms"); } return null; } /** * Parses the application header from the parameter node. * @return parsed header or null if the content cannot be parsed or the header is not present in the xml */ static BusinessApplicationHeaderV01 parseBusinessApplicationHeaderV01(final MxNode tree) { final long t0 = System.currentTimeMillis(); if (tree != null) { final MxNode header = tree.findFirstByName(MxParser.HEADER_LOCALNAME); if (header == null) { log.warning(MxParser.HEADER_LOCALNAME + " element not found"); } else { final BusinessApplicationHeaderV01 result = new BusinessApplicationHeaderV01(); MxNode CharSet = header.findFirst("./CharSet"); if (CharSet != null) { result.setCharSet(CharSet.getValue()); } MxNode Fr = header.findFirst("./Fr"); if (Fr != null) { result.setFr(new Party9Choice()); parse(Fr, result.getFr()); } MxNode To = header.findFirst("./To"); if (To != null) { result.setTo(new Party9Choice()); parse(To, result.getTo()); } MxNode BizMsgIdr = header.findFirst("./BizMsgIdr"); if (BizMsgIdr != null) { result.setBizMsgIdr(BizMsgIdr.getValue()); } MxNode MsgDefIdr = header.findFirst("./MsgDefIdr"); if (MsgDefIdr != null) { result.setMsgDefIdr(MsgDefIdr.getValue()); } MxNode BizSvc = header.findFirst("./BizSvc"); if (BizSvc != null) { result.setBizSvc(BizSvc.getValue()); } MxNode CreDt = header.findFirst("./CreDt"); if (CreDt != null) { try { result.setCreDt(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(CreDt.getValue())); } catch (final javax.xml.datatype.DatatypeConfigurationException e) { log.warning("exception " + e + " parsing header crDate [" + CreDt.getValue() + "]"); } } MxNode CpyDplct = header.findFirst("./CpyDplct"); if (CpyDplct != null) { try { result.setCpyDplct(CopyDuplicate1Code.valueOf(CpyDplct.getValue())); } catch (final Exception e) { log.warning("exception " + e + " parsing header CpyDplct [" + CpyDplct.getValue() + "]"); } } MxNode PssblDplct = header.findFirst("./PssblDplct"); if (PssblDplct != null) { try { result.setPssblDplct(Boolean.valueOf(PssblDplct.getValue())); } catch (final Exception e) { log.warning("exception " + e + " parsing header PssblDplct [" + PssblDplct.getValue() + "]"); } } MxNode Prty = header.findFirst("./Prty"); if (Prty != null) { result.setPrty(Prty.getValue()); } MxNode Sgntr = header.findFirst("./Sgntr"); if (Sgntr != null) { result.setSgntr(new SignatureEnvelope()); result.getSgntr().setAny(Sgntr.getValue()); } MxNode Rltd = header.findFirst("./Rltd"); if (Rltd != null) { result.setRltd(new BusinessApplicationHeader1()); parse(Rltd, result.getRltd()); } return result; } } final long t1 = System.currentTimeMillis(); log.fine("parseApplicationHeader_sax: " + (t1 - t0) + "ms"); return null; } /** * Helper parse for BusinessApplicationHeader1. * This actually parses a BusinessApplicationHeaderV01 and copies all its content into * the result BusinessApplicationHeader1. Both header model classes share the same fields. * @param node current node for the path search * @param h object to fill with parsed content */ private static void parse(MxNode node, BusinessApplicationHeader1 h) { BusinessApplicationHeaderV01 bah = parseBusinessApplicationHeaderV01(node); if (bah != null) { h.setBizMsgIdr(bah.getBizMsgIdr()); h.setBizSvc(bah.getBizSvc()); h.setCharSet(bah.getCharSet()); h.setCpyDplct(bah.getCpyDplct()); h.setCreDt(bah.getCreDt()); h.setFr(bah.getFr()); h.setMsgDefIdr(bah.getMsgDefIdr()); h.setPrty(bah.getPrty()); h.setSgntr(bah.getSgntr()); h.setTo(bah.getTo()); h.setPssblDplct(bah.isPssblDplct()); } } /** * Helper parse for Party9Choice * @param node current node for the path search * @param party object to fill with parsed content */ private static void parse(MxNode node, Party9Choice party) { MxNode OrgId = node.findFirst("./OrgId"); if (OrgId != null) { party.setOrgId(new PartyIdentification42()); parse(OrgId, party.getOrgId()); } MxNode FIId = node.findFirst("./FIId"); if (FIId != null) { party.setFIId(new BranchAndFinancialInstitutionIdentification5()); parse(FIId, party.getFIId()); } } /** * Helper parse for BranchAndFinancialInstitutionIdentification5 * @param node current node for the path search * @param fiId object to fill with parsed content */ private static void parse(MxNode node, BranchAndFinancialInstitutionIdentification5 fiId) { MxNode FinInstnId = node.findFirst("./FinInstnId"); if (FinInstnId != null) { fiId.setFinInstnId(new FinancialInstitutionIdentification8()); parse(FinInstnId, fiId.getFinInstnId()); } MxNode BrnchId = node.findFirst("./BrnchId"); if (BrnchId != null) { fiId.setBrnchId(new BranchData2()); parse(BrnchId, fiId.getBrnchId()); } } /** * Helper parse for BranchData2 * @param node current node for the path search * @param branch object to fill with parsed content */ private static void parse(MxNode node, BranchData2 branch) { MxNode Id = node.findFirst("./Id"); if (Id != null) { branch.setId(Id.getValue()); } MxNode Nm = node.findFirst("./Nm"); if (Nm != null) { branch.setNm(Nm.getValue()); } MxNode PstlAdr = node.findFirst("./PstlAdr"); if (PstlAdr != null) { branch.setPstlAdr(new PostalAddress6()); parse(PstlAdr, branch.getPstlAdr()); } } /** * Helper parse for PostalAddress6 * @param node current node for the path search * @param pstlAdr object to fill with parsed content */ private static void parse(MxNode node, PostalAddress6 pstlAdr) { MxNode AdrTp = node.findFirst("./AdrTp"); if (AdrTp != null) { try { pstlAdr.setAdrTp(AddressType2Code.valueOf(AdrTp.getValue())); } catch (final Exception e) { log.warning("exception " + e + " parsing header AdrTp [" + AdrTp.getValue() + "]"); } } MxNode Dept = node.findFirst("./Dept"); if (Dept != null) { pstlAdr.setDept(Dept.getValue()); } MxNode SubDept = node.findFirst("./SubDept"); if (AdrTp != null) { pstlAdr.setSubDept(SubDept.getValue()); } MxNode StrtNm = node.findFirst("./StrtNm"); if (StrtNm != null) { pstlAdr.setStrtNm(StrtNm.getValue()); } MxNode BldgNb = node.findFirst("./BldgNb"); if (BldgNb != null) { pstlAdr.setBldgNb(BldgNb.getValue()); } MxNode PstCd = node.findFirst("./PstCd"); if (PstCd != null) { pstlAdr.setPstCd(PstCd.getValue()); } MxNode TwnNm = node.findFirst("./TwnNm"); if (TwnNm != null) { pstlAdr.setTwnNm(TwnNm.getValue()); } MxNode CtrySubDvsn = node.findFirst("./CtrySubDvsn"); if (CtrySubDvsn != null) { pstlAdr.setCtrySubDvsn(CtrySubDvsn.getValue()); } MxNode Ctry = node.findFirst("./Ctry"); if (Ctry != null) { pstlAdr.setCtry(Ctry.getValue()); } } /** * Helper parse for FinancialInstitutionIdentification8 * @param node current node for the path search * @param finInstnId object to fill with parsed content */ private static void parse(MxNode node, FinancialInstitutionIdentification8 finInstnId) { MxNode BICFI = node.findFirst("./BICFI"); if (BICFI != null) { finInstnId.setBICFI(BICFI.getValue()); } MxNode ClrSysMmbId = node.findFirst("./ClrSysMmbId"); if (ClrSysMmbId != null) { finInstnId.setClrSysMmbId(new ClearingSystemMemberIdentification2()); parse(ClrSysMmbId, finInstnId.getClrSysMmbId()); } MxNode Nm = node.findFirst("./Nm"); if (Nm != null) { finInstnId.setNm(Nm.getValue()); } MxNode PstlAdr = node.findFirst("./PstlAdr"); if (PstlAdr != null) { finInstnId.setPstlAdr(new PostalAddress6()); parse(PstlAdr, finInstnId.getPstlAdr()); } MxNode Othr = node.findFirst("./Othr"); if (Othr != null) { finInstnId.setOthr(new GenericFinancialIdentification1()); parse(Othr, finInstnId.getOthr()); } } /** * Helper parse for GenericFinancialIdentification1 * @param node current node for the path search * @param fiId object to fill with parsed content */ private static void parse(MxNode node, GenericFinancialIdentification1 fiId) { MxNode Id = node.findFirst("./Id"); if (Id != null) { fiId.setId(Id.getValue()); } MxNode SchmeNm = node.findFirst("./SchmeNm"); if (SchmeNm != null) { fiId.setSchmeNm(new FinancialIdentificationSchemeName1Choice()); parse(SchmeNm, fiId.getSchmeNm()); } MxNode Issr = node.findFirst("./Issr"); if (Issr != null) { fiId.setIssr(Issr.getValue()); } } /** * Helper parse for FinancialIdentificationSchemeName1Choice * @param node current node for the path search * @param schmeNm object to fill with parsed content */ private static void parse(MxNode node, FinancialIdentificationSchemeName1Choice schmeNm) { MxNode Cd = node.findFirst("./Cd"); if (Cd != null) { schmeNm.setCd(Cd.getValue()); } MxNode Prtry = node.findFirst("./Prtry"); if (Prtry != null) { schmeNm.setPrtry(Prtry.getValue()); } } /** * Helper parse for ClearingSystemMemberIdentification2 * @param node current node for the path search * @param clrSysMmbId object to fill with parsed content */ private static void parse(MxNode node, ClearingSystemMemberIdentification2 clrSysMmbId) { MxNode ClrSysId = node.findFirst("./ClrSysId"); if (ClrSysId != null) { clrSysMmbId.setClrSysId(new ClearingSystemIdentification2Choice()); parse(ClrSysId, clrSysMmbId.getClrSysId()); } MxNode MmbId = node.findFirst("./MmbId"); if (MmbId != null) { clrSysMmbId.setMmbId(MmbId.getValue()); } } /** * Helper parse for ClearingSystemIdentification2Choice * @param node current node for the path search * @param clrSysId object to fill with parsed content */ private static void parse(MxNode node, ClearingSystemIdentification2Choice clrSysId) { MxNode Cd = node.findFirst("./Cd"); if (Cd != null) { clrSysId.setCd(Cd.getValue()); } MxNode Prtry = node.findFirst("./Prtry"); if (Prtry != null) { clrSysId.setPrtry(Prtry.getValue()); } } /** * Helper parse for PartyIdentification42 * @param node current node for the path search * @param party object to fill with parsed content */ private static void parse(MxNode node, PartyIdentification42 party) { MxNode Nm = node.findFirst("./Nm"); if (Nm != null) { party.setNm(Nm.getValue()); } MxNode PstlAdr = node.findFirst("./PstlAdr"); if (PstlAdr != null) { party.setPstlAdr(new PostalAddress6()); parse(PstlAdr, party.getPstlAdr()); } MxNode Id = node.findFirst("./Id"); if (Id != null) { party.setId(new Party10Choice()); parse(Id, party.getId()); } MxNode CtryOfRes = node.findFirst("./CtryOfRes"); if (CtryOfRes != null) { party.setCtryOfRes(CtryOfRes.getValue()); } MxNode CtctDtls = node.findFirst("./CtctDtls"); if (CtctDtls != null) { party.setCtctDtls(new ContactDetails2()); parse(CtctDtls, party.getCtctDtls()); } } /** * Helper parse for ContactDetails2 * @param node current node for the path search * @param ctctDtls object to fill with parsed content */ private static void parse(MxNode node, ContactDetails2 ctctDtls) { MxNode NmPrfx = node.findFirst("./NmPrfx"); if (NmPrfx != null) { try { ctctDtls.setNmPrfx(NamePrefix1Code.valueOf(NmPrfx.getValue())); } catch (final Exception e) { log.warning("exception " + e + " parsing header NmPrfx [" + NmPrfx.getValue() + "]"); } } MxNode Nm = node.findFirst("./Nm"); if (Nm != null) { ctctDtls.setNm(Nm.getValue()); } MxNode PhneNb = node.findFirst("./PhneNb"); if (PhneNb != null) { ctctDtls.setPhneNb(PhneNb.getValue()); } MxNode MobNb = node.findFirst("./MobNb"); if (MobNb != null) { ctctDtls.setMobNb(MobNb.getValue()); } MxNode FaxNb = node.findFirst("./FaxNb"); if (FaxNb != null) { ctctDtls.setFaxNb(FaxNb.getValue()); } MxNode EmailAdr = node.findFirst("./EmailAdr"); if (EmailAdr != null) { ctctDtls.setEmailAdr(EmailAdr.getValue()); } MxNode Othr = node.findFirst("./Othr"); if (Othr != null) { ctctDtls.setOthr(Othr.getValue()); } } /** * Helper parse for Party10Choice * @param node current node for the path search * @param id object to fill with parsed content */ private static void parse(MxNode node, Party10Choice id) { MxNode OrgId = node.findFirst("./OrgId"); if (OrgId != null) { id.setOrgId(new OrganisationIdentification7()); parse(OrgId, id.getOrgId()); } MxNode PrvtId = node.findFirst("./PrvtId"); if (PrvtId != null) { id.setPrvtId(new PersonIdentification5()); parse(PrvtId, id.getPrvtId()); } } /** * Helper parse for PersonIdentification5 * @param node current node for the path search * @param prvtId object to fill with parsed content */ private static void parse(MxNode node, PersonIdentification5 prvtId) { MxNode DtAndPlcOfBirth = node.findFirst("./DtAndPlcOfBirth"); if (DtAndPlcOfBirth != null) { prvtId.setDtAndPlcOfBirth(new DateAndPlaceOfBirth()); parse(DtAndPlcOfBirth, prvtId.getDtAndPlcOfBirth()); } } /** * Helper parse for DateAndPlaceOfBirth * @param node current node for the path search * @param dtAndPlcOfBirth object to fill with parsed content */ private static void parse(MxNode node, DateAndPlaceOfBirth dtAndPlcOfBirth) { MxNode BirthDt = node.findFirst("./BirthDt"); if (BirthDt != null) { try { dtAndPlcOfBirth.setBirthDt(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(BirthDt.getValue())); } catch (final javax.xml.datatype.DatatypeConfigurationException e) { log.warning("exception " + e + " parsing header BirthDt [" + BirthDt.getValue() + "]"); } } MxNode PrvcOfBirth = node.findFirst("./PrvcOfBirth"); if (PrvcOfBirth != null) { dtAndPlcOfBirth.setPrvcOfBirth(PrvcOfBirth.getValue()); } MxNode CityOfBirth = node.findFirst("./CityOfBirth"); if (CityOfBirth != null) { dtAndPlcOfBirth.setCityOfBirth(CityOfBirth.getValue()); } MxNode CtryOfBirth = node.findFirst("./CtryOfBirth"); if (CtryOfBirth != null) { dtAndPlcOfBirth.setCtryOfBirth(CtryOfBirth.getValue()); } } /** * Helper parse for OrganisationIdentification7 * @param node current node for the path search * @param orgId object to fill with parsed content */ private static void parse(MxNode node, OrganisationIdentification7 orgId) { MxNode AnyBIC = node.findFirst("./AnyBIC"); if (AnyBIC != null) { orgId.setAnyBIC(AnyBIC.getValue()); } } }
<gh_stars>1-10 package notes import // rhythms are limited to 256 values // Base rhythm is 1/36 // Negra: 36 // Corchea: 18 // Tresillo de corcheas: 12 // Semicorchea: 9 // Tresillo de semicorcheas: 6 // Blanca 72 // Redonda 144 // Max: 255 -> // 255 - 144 (redonda) // 111 - 72 (blanca) // 39 - 36 (negra) // 3 (tresillo de fusas) "fmt" type Duration byte // English note names, A-G type NoteName byte const ( C NoteName = 0 D = 2 E = 4 F = 5 G = 7 A = 9 B = 11 ) var noteNames = map[NoteName]string{ A: "A", B: "B", C: "C", D: "D", E: "E", F: "F", G: "G", } func (n NoteName) String() string { return noteNames[n] } type Accidental int8 const ( DoubleFlat Accidental = -2 Flat = -1 Natural = 0 Sharp = 1 DoubleSharp = 2 ) var accidentalNames = map[Accidental]string{ DoubleFlat: "B", Flat: "b", Natural: "", Sharp: "#", DoubleSharp: "X", } func (a Accidental) String() string { return accidentalNames[a] } type Interval int32 type Pitch struct { Name NoteName Octave int8 Acc Accidental } func (p *Pitch) String() string { return fmt.Sprintf("%v%v%v", p.Name, p.Acc, p.Octave) } func (p *Pitch) num() int32 { return int32(p.Name) + int32(p.Acc) + 12*int32(p.Octave) } func (p *Pitch) Interval(q *Pitch) Interval { return Interval(q.num() - p.num()) } type Note struct { Duration Pitch }
<filename>packages/jsii-rosetta/test/jsii-imports.test.ts // Test translation of imports with actual jsii assemblies // // - For Python, there is a lot of variation in what imports get translated to (mirroring // the style in TypeScript, occasionally adding extra imports as required). // - For other languages, we'll mostly translate the same thing. import { TargetLanguage, TranslatedSnippet } from '../lib'; import { MultipleSources, TestJsiiModule, DUMMY_JSII_CONFIG } from './testutil'; describe('no submodule', () => { describe('top-level struct', () => { let module: TestJsiiModule; beforeAll(() => { module = makeJsiiModule({ withModule: false, nestedStruct: false }); }); afterAll(() => module.cleanup()); describe('package import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere(` import * as masm from 'my_assembly'; const obj = new masm.MyClass('value', { myStruct: { value: 'v', }, }); `); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'import example_test_demo as masm', 'obj = masm.MyClass("value",', ' my_struct=masm.MyStruct(', ' value="v"', ' )', ')', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.*;', ...DEFAULT_JAVA_CODE, ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo;', ...DEFAULT_CSHARP_CODE, ]); }); }); describe('class import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere( `import { MyClass } from 'my_assembly'; const obj = new MyClass('value', { myStruct: { value: 'v', }, }); `, ); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'from example_test_demo import MyStruct', 'from example_test_demo import MyClass', 'obj = MyClass("value",', ' my_struct=MyStruct(', ' value="v"', ' )', ')', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.MyClass;', ...DEFAULT_JAVA_CODE, ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo;', ...DEFAULT_CSHARP_CODE, ]); }); }); }); describe('nested struct', () => { let module: TestJsiiModule; beforeAll(() => { module = makeJsiiModule({ withModule: false, nestedStruct: true }); }); afterAll(() => module.cleanup()); describe('package import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere(` import * as masm from 'my_assembly'; const obj = new masm.MyClass('value', { myStruct: { value: 'v', }, }); `); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'import example_test_demo as masm', 'obj = masm.MyClass("value",', ' my_struct=masm.MyClass.MyStruct(', ' value="v"', ' )', ')', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.*;', ...DEFAULT_JAVA_CODE, ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo;', ...DEFAULT_CSHARP_CODE, ]); }); }); describe('class import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere(` import { MyClass } from 'my_assembly'; const obj = new MyClass('value', { myStruct: { value: 'v', }, }); `); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'from example_test_demo import MyClass', 'obj = MyClass("value",', ' my_struct=MyClass.MyStruct(', ' value="v"', ' )', ')', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.MyClass;', ...DEFAULT_JAVA_CODE, ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo;', ...DEFAULT_CSHARP_CODE, ]); }); }); }); describe('enum', () => { let module: TestJsiiModule; beforeAll(() => { module = TestJsiiModule.fromSource( { 'index.ts': `export enum MyEnum { OPTION_A = 'a', OPTION_B = 'b' } export interface MyProps { readonly prop: MyEnum } export function myFun(props: MyProps) { Array.isArray(props); } `, }, { name: 'my_assembly', jsii: DUMMY_JSII_CONFIG, }, ); }); afterAll(() => module.cleanup()); describe('package import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere(` import * as masm from 'my_assembly'; const x = masm.MyEnum.OPTION_A; `); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'import example_test_demo as masm', 'x = masm.MyEnum.OPTION_A', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.*;', 'MyEnum x = MyEnum.OPTION_A;', ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo;', 'MyEnum x = MyEnum.OPTION_A;', ]); }); }); describe('direct import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere( `import { MyEnum } from 'my_assembly'; const x = MyEnum.OPTION_A; `, ); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'from example_test_demo import MyEnum', 'x = MyEnum.OPTION_A', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.MyEnum;', 'MyEnum x = MyEnum.OPTION_A;', ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo;', 'MyEnum x = MyEnum.OPTION_A;', ]); }); }); describe('implicit import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere( `import * as masm from 'my_assembly'; masm.myFun({ prop: masm.MyEnum.OPTION_A }); `, ); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'import example_test_demo as masm', 'masm.my_fun(prop=masm.MyEnum.OPTION_A)', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.*;', 'myFun(MyProps.builder().prop(MyEnum.OPTION_A).build());', ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo;', 'MyFun(new MyProps { Prop = MyEnum.OPTION_A });', ]); }); }); }); }); describe('with submodule', () => { describe('top-level struct', () => { let module: TestJsiiModule; beforeAll(() => { module = makeJsiiModule({ withModule: true, nestedStruct: false }); }); afterAll(() => module.cleanup()); describe('namespace import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere(` import { submod as mod } from 'my_assembly'; const obj = new mod.MyClass('value', { myStruct: { value: 'v', }, }); `); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'from example_test_demo import boop as mod', 'obj = mod.MyClass("value",', ' my_struct=mod.MyStruct(', ' value="v"', ' )', ')', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.boop.*;', ...DEFAULT_JAVA_CODE, ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo.Boop;', ...DEFAULT_CSHARP_CODE, ]); }); }); }); describe('nested struct', () => { let module: TestJsiiModule; beforeAll(() => { module = makeJsiiModule({ withModule: true, nestedStruct: true }); }); afterAll(() => module.cleanup()); describe('namespace import', () => { let trans: TranslatedSnippet; beforeAll(() => { trans = module.translateHere(` import { submod as mod } from 'my_assembly'; const obj = new mod.MyClass('value', { myStruct: { value: 'v', }, }); `); }); test('to Python', () => { expectTranslation(trans, TargetLanguage.PYTHON, [ 'from example_test_demo import boop as mod', 'obj = mod.MyClass("value",', ' my_struct=mod.MyClass.MyStruct(', ' value="v"', ' )', ')', ]); }); test('to Java', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.JAVA, [ 'import example.test.demo.boop.*;', ...DEFAULT_JAVA_CODE, ]); }); test('to C#', () => { // eslint-disable-next-line prettier/prettier expectTranslation(trans, TargetLanguage.CSHARP, [ 'using Example.Test.Demo.Boop;', ...DEFAULT_CSHARP_CODE, ]); }); }); }); }); function makeJsiiModule(options: { readonly withModule: boolean; readonly nestedStruct: boolean }): TestJsiiModule { const nsRef = options.nestedStruct ? 'MyClass.' : ''; const nsDeclBegin = options.nestedStruct ? 'export namespace MyClass {\n' : ''; const nsDeclEnd = options.nestedStruct ? '}' : ''; const payload = ` export class MyClass { constructor(value: string, props: ${nsRef}MyClassProps) { Array.isArray(value); Array.isArray(props); } } ${nsDeclBegin} export interface MyClassProps { readonly myStruct: MyStruct; } export interface MyStruct { readonly value: string; } ${nsDeclEnd} `; const source: MultipleSources = options.withModule ? { 'index.ts': 'export * as submod from "./submodule/module";', 'submodule/module.ts': payload, 'submodule/.jsiirc.json': JSON.stringify({ targets: { python: { module: 'example_test_demo.boop', }, java: { package: 'example.test.demo.boop', }, dotnet: { namespace: 'Example.Test.Demo.Boop', }, }, }), } : { 'index.ts': payload, }; return TestJsiiModule.fromSource(source, { name: 'my_assembly', jsii: DUMMY_JSII_CONFIG, }); } // The implementation part of the Java code is always the same const DEFAULT_JAVA_CODE = [ 'MyClass obj = MyClass.Builder.create("value")', ' .myStruct(MyStruct.builder()', ' .value("v")', ' .build())', ' .build();', ]; // The implementation part of the CSharp code is always the same const DEFAULT_CSHARP_CODE = [ 'MyClass obj = new MyClass("value", new MyClassProps {', ' MyStruct = new MyStruct {', ' Value = "v"', ' }', '});', ]; /** * Verify the output in the given language. All expected outputs look the same. */ function expectTranslation(trans: TranslatedSnippet, lang: TargetLanguage, expected: string[]) { expect(trans.get(lang)?.source.split('\n')).toEqual(expected); }
<gh_stars>0 import { CreatedAccountEvent } from './created-account.event'; export class CreatedAccountsEvent { constructor( public readonly accounts: CreatedAccountEvent[], ) {} }
<gh_stars>0 package net.n2oapp.framework.autotest.impl.component.region; import net.n2oapp.framework.autotest.N2oSelenide; import net.n2oapp.framework.autotest.api.collection.Widgets; import net.n2oapp.framework.autotest.api.component.region.SimpleRegion; /** * Простой регион для автотестирования */ public class N2oSimpleRegion extends N2oRegion implements SimpleRegion { @Override public Widgets content() { return N2oSelenide.collection(element().$$(".n2o-standard-widget-layout"), Widgets.class); } }
On Monday, members of the Electoral College will cast their historic votes for the next president of the United States. In the meantime, they are under siege. The nation’s 538 presidential electors have been thrust into the political foreground like never before in American history. In the aftermath of a uniquely polarizing presidential contest, the once-anonymous electors are squarely in the spotlight, targeted by death threats, harassing phone calls and reams of hate mail. One Texas Republican elector said he’s been bombarded with more than 200,000 emails. Story Continued Below “I never can imagine harassing people like this. It’s just f----- up,” said Jim Rhoades, a Republican elector from Michigan who runs a home inspection service. “I’ve lost a bunch of business.” In recent decades, the Electoral College had become such a reliable rubber stamp of Election Day results that it was viewed as an afterthought. But with many Democrats desperate to block the all-but-certain ascension of Donald Trump to the White House, this long-neglected body has been gripped by turmoil, and its members have been subjected to pleas to upend centuries of tradition by casting their votes for someone other than the president-elect. There have been ad campaigns targeting electors and op-eds assailing their role. One Democratic member of Congress has called to delay the vote for president while an investigation of Russian involvement in the election is underway. Two others have pleaded with electors to consider Russia’s role when deciding how to vote. Progressive groups are preparing protests across the country at sites where electors will meet to cast their ballots. Personal contact information for many electors has been posted publicly — and it’s been used to bury them with massive email campaigns. Last week saw the release of a video of celebrities like Martin Sheen pleading with Republican electors to vote for someone other than Trump. On Saturday, Unite for America — the group behind the video — began sending personalized versions to electors in which Sheen and more than a dozen others call them out by name. The body’s 306 Republicans have faced the most acute pressure of all. Several, like Rhoades, told POLITICO they receive thousands of emails a day from anti-Trump advocates, much of it auto-generated from forms available online. Others say they’re receiving pressure from national Republicans and the Trump campaign to make sure they remain loyal. In this Dec. 12 photo, Hector Maldonado poses in St. Louis. Although pestered to abandon Donald Trump, Republican electors appear to be in no mood for an insurrection in the presidential campaign'’s last voting ritual. Maldonado backed Ted Cruz in the primaries but will cast his vote for Trump with conviction. "“I took an oath once to become a U.S. citizen,”" he said, “"and on Aug. 14, 1995, that was the first oath that I've taken to support the U.S. Constitution. A year later I took the oath again, to support the duties of being an officer in the U.S. Army. This was the third oath that I've taken to execute what I promised to do." | AP Photo “The Trump campaign is calling. The Republican Party of Texas is calling. They’re trying to lock down the votes,” said Texas GOP elector Alexander Kim, who estimated he has received at least 30 such calls. One RNC insider, he said, called him three times in one hour to get a response. There’s a reason electors like Kim make Republicans nervous. While he insists he’s voting for Trump when the body meets on Monday and that nothing can shake him from that position, there is a caveat: “unless Trump does something to violate the compact that he created with American citizens.” Just that eyelash of doubt, Kim suspects, has led to his barrage of calls from the party. The tumultuous 2016 primary campaign is in part responsible for the manic lobbying efforts. Dozens of electors have some degree of hostility to Trump and Democratic nominee Hillary Clinton, both of whom won their party nominations after contentious primaries. Most of the Republican electors have since vowed to support Trump, but their presence has fueled the Democratic resistance and given it hope. In this image from video, Electoral College voter Jim Skaggs looks through his mail from people writing him about being an elector in Bowling Green, Ky., on Dec. 13. Although pestered to abandon Donald Trump, Republican electors appear to be in no mood for an insurrection in the presidential campaign’'s last voting ritual. "I hope he is far better than I think he is,”" Skaggs said. "Even so, “I fully intend to vote for Donald Trump," he said. “"I think it’'s a duty." | AP Photo Chris Suprun of Texas, the only GOP elector to publicly oppose Trump, has been especially battered by criticism — mainly from fellow Republicans, including party leaders who have questioned his integrity. Suprun announced his intention to vote for someone other than Trump in a New York Times op-ed, recalling his service on Sept. 11, 2001, as a first responder to the attack on the Pentagon. On Friday, a Texas television station ran a story accusing Suprun of inventing his 9/11 role, the story that Suprun built his career around. The charge, based on a discrepancy with Suprun’s LinkedIn page, featured an anonymous former colleague accusing Suprun of “stolen valor.” Suprun has vehemently denied the story. Suprun is the only Republican in a coalition of 10 electors who have launched a desperate, long-shot effort to convince GOP electors to reject Trump. They need at least 36 more to join them in order to prevent Trump from earning enough support to be officially elected president. If they were to succeed, the election would be thrown to the GOP-controlled House of Representatives for a final vote. Rex Teter poses at his home in Pasadena, Texas, on Dec. 13. Teter, 59, a music teacher and preacher, received about 35,000 emails and 200 letters urging him not to support Donald Trump. It took him several hours to delete them the day after Thanksgiving. A Marco Rubio supporter in the primaries, he is solidly for Trump. "Some have been very personal letters. Some threatening. One was very funny. They view President-elect Trump as a threat so it'’s personal for them and I can empathize. But I'm not changing my vote as an elector." | AP Photo Suprun is also the only Republican who joined 79 Democratic electors in calling for an intelligence briefing on Russia’s role in the election ahead of Monday’s vote. The effort, spearheaded by California Democratic elector Christine Pelosi — daughter of House Minority Leader Nancy Pelosi — was rebuffed Friday by Director of National Intelligence James Clapper. "Recently, the Office of the Director of National Intelligence has received requests from Members of Congress, several electors of the Electoral College and the general public for additional information on Russian interference in the 2016 presidential election," Clapper’s office said in a statement, noting that President Barack Obama has called for a full review of Russian interference amid reports that President Vladimir Putin directed a hacking campaign aimed at Democrats in order to aid Trump’s election. "Once the review is complete in the coming weeks, the intelligence community stands ready to brief Congress and will make those findings available to the public consistent with protecting intelligence sources and methods.”
Kaytranada turned 25-years-old a couple months back and it’s hard to fathom all he’s done from such a young age. The Canadian bred producer began officially releasing music in 2010 and he’s amassed a gigantic back catalog of beats, remixes, mixes and original songs, most of which are still buried on his Soundcloud page. Kaytra was of the first generations to really start a career in music off of Soundcloud, uploading new tunes of all variations to the platform at a consistent rate. That page is a treasure, it’s a timeline of Kaytra’s progression as an artist and it truly demonstrates the path he took to find his sound, a sound that in my personal subjective opinion is one of the best in music right now period. Kaytranada truly found a signature sound and it’s quite recognizable, especially to the trained ear. While Kaytranada isn’t all over the Billboard Top 100 like Metro Boomin or some of these other producers, he’s still making a significant splash with dense, groovy production that’s caught the eyes of quite a few greats. Kaytra’s already worked with big name artists like Mary J. Blige, Alicia Keys, Chance The Rapper among many others and it’s only up from here. We decided to take a stab at ranking the songs of one of our best current producers. It was an arduous task but we’re happy with our final list of Kaytranada‘s 25 best songs. These songs were ranked subjectively based on how good the song is, not just strictly on how good the beat itself is. We didn’t include any of his remixes or his instrumentals, unless it appeared on his album 99.9%. Take a look at our ranks below and whether you agree or disagree, I think we can all agree on how incredible an artist Kaytranada is. 25. Goldlink – Have You Seen That Girl? (2017) Quite frankly, I love this song and the fact that it’s all the way at 25, the last spot on this list is a testament to just how strong Kaytranada‘s discography is. “Have You Seen That Girl?” was featured on Goldlink‘s latest album At What Cost and as you’re reading the production credits before listening to the album, you’re to expect a dose of future bounce, as the two have delivered together many times in the past. This record however takes a different path and it ends up fitting the go-go inspired hip hop album pretty well. It’s a scattered, retro sounding beat that’s immediately reminiscent of Drake‘s “Feel No Ways”. It feels brilliantly analog, a sound I’d love to hear Kaytra delve into more. – Trixx 24. Mick Jenkins – Communicate (feat. Ravyn Lenae) (2016) I’m just going to go right out and say it, I’m not a huge fan of when Kaytranada and Mick Jenkins collaborate. These two have worked together many of times and while I don’t think the songs are ever bad, there’s only just a couple of songs that really standout, one of those being “Communicate”. This song was featured smack in the middle of Mick’s latest album The Healing Component and boy did this one take my breath away. This song is signature Kaytranada. He’s not doing anything experimental here, he’s just relying on the patented bouncy sound that he mastered. The bass is knocking, the kicks are punching through and the song’s ultimately riding. Not to mention this one’s bolstered by a couple of unsurprisingly dope verses from Mick and an angelic hook from none other than Ravyn Lenae. This song’s a hidden gem on an album that I feel was panned by many people and kind of just glossed over. – Trixx 23. The Celestics – Charles Barkley (2013) I tossed and turned trying to decide whether this one deserved to stay but after some deep soul searching and a cheesy long shot movie scene of me staring into some beautiful landscapes, I knew this needed to make the list. 2013 was when I stumbled upon Kaytranada, it was still very early in his career but he had a few remixes making significant noise on Soundcloud. This was also when he first introduced his brother Lou Phelps to us as the two brothers formed The Celestics. “Charles Barkley” was their first song on Soundcloud and the song’s just as vicious and banging as the wonderful cover art suggests. This was one of those in constant whip rotation for me in college and there were quite a few people I put onto this record off that alone. This fun song just has so many memories for me and still I can’t help but smile when I hear this one. – Trixx 22. Aminé – La Danse (2015) Before “Caroline” blew up and became and a hit and before the rap internet called him an industry plant, Aminé broke major ground with this record right here “La Danse”. Aminé‘s mysterious success has been called into question numerous times and even how he acquired three beats from Kaytranada for his debut project was pretty baffling. But as I recall, someone told me that they began working because of a freestyle Aminé had sent to Kaytra over Twitter I believe. Kaytra liked what he heard and put stock into the kid. Now don’t quote me on that story because my memories foggy and I couldn’t find any internet receipts but it seems logical. The lead single from that 2015 debut project Calling Brion was this song called “La Danse” that featured a driving, upbeat Kaytranada beat. The beat itself’s one of Kaytra’s simpler productions but it’s matched by a super catchy hook that really served as proof to A&Rs and music guys that maybe there’s something special about this Portland kid. – Trixx 21. Shay Lia – What’s Your Problem? (2017) Like with all artists, you’ve got those few local people you really came up with and built together. A consistent feature on Kaytranada music has been Shay Lia a name that really only has become somewhat known due to her work with Kaytra. She’s released a few singles on her own as well with her last one “What’s Your Problem?” being the most impressive to me. It really seems like she dug into Kaytra’s hard drive and found the nastiest thing he’d been working on. This beat sounds experimental and bold yet it definitely packs that Kaytranada charm we’ve come to love. I’m not the biggest fan of Shay’s voice; she’s a little rough around the edges but the beat here makes this a fantastic track. – Trixx 20. Goldlink – Meditation f. Jazmine Sullivan & Kaytranada (2017) Kaytranada produced 3 songs on Goldlink‘s last album At What Cost and we’ve got the 2nd one to appear on this list with “Meditation”. Prior to the album dropping, Goldink dropped quite a few different singles, most of which ended up being loosies except for “Crew”. Of all of those, “Meditation” was the last to be released and when I saw the single teased, my anticipation levels went through the roof because I knew the heights Goldlink and Kaytranada were capable of reaching plus they had Jazmine Sullivan?!? I though it was a wrap that this would take song of the year. And then I heard the song and I was a bit disappointed. I set myself with the highest expectations, thus why I was underwhelmed on my first couple listens. That’s what made this song turn into a grower for me and once I heard At What Cost in full, I really came to appreciate “Meditation”. – Trixx 19. Freddie Gibbs – Insecurities (2015) In today’s hip hop landscape, songs are typically littered with co-producers. Travis Scott for example is very famous for doing that and bringing together a lot of the best producers just to collaborate on one track. However it’s rare that there’s ever any co-producers on Kaytranada‘s work. He’s typically a one man machine but he benefit from some help on Freddie Gibbs‘ “Insecurities” from Frank Dukes and Sid “Speakerbomb” Miller. Kaytranada has a light, feathery electronic-tinged sound that you wouldn’t typically think of with the gruff stylings of Freddie Gibbs but they’ve really developed a good working relationship, having done a few different songs. At the top of the heap though has to be “Insecurities”. Like the title suggests, Freddie’s being very open on this song, which is especially remarkable for a rapper that commonly refers to himself as “Gangsta Gibbs”. – Trixx 18. Kaytranada – One Too Many f. Phonte (2016) Phonte and Little Brother have an indelible mark on my heart and when I saw this old meets new collaboration I was instantly excited. Phonte‘s been working with Nicolay as The Foreign Exchange for almost a decade now and at times, some of Nicolay’s airy beats sound like a stripped down version of what Kaytranada may do. And because of that, I had a lot of faith that this record would work. And surely it did work as it’s landed at number 18 on our countdown. This was another collaboration that all began from a Twitter DM but this record almost didn’t make the cut for 99.9%, the time cut that is. Phonte took a while to send this record back and finish his part but thankfully he finished it in the nick of time. – Trixx 17. Mobb Deep – Block Deep (2014) Of all of the songs that made this list, this one is perhaps the most surprising. I say that because for one, who expected these two to even work together? And secondly because Mobb Deep‘s sound has always been gangster and gritty and Kaytranada‘s has always been more vibrant and danceable. Well this song ended up working so well primarily because Kaytra catered to their sound and melded his sound with their sound. – Trixx 16. Anderson .Paak – Lite Weight (2016) Some of the best beats and songs ever are indescribable; those kind of odd sounds that seem impossible to put into words. That most certainly describes this beat for Anderson .Paak‘s song “Lite Weight”. It’s a woozy beat that leaves a lot of room for Anderson to spread his wings and fly. Unlike most of Kaytranada‘s work, this one is minimal as it’s focused on that one woozy sample and a very simple drum pattern. That leaves it all up to Anderson to carry the song further and that he surely does. Hopefully these two have some more cooking up because both of their collaborations together thus far have been spot on. – Trixx 15. Buddy – Find Me (2017) Most recently, Kaytranada put out a strong new EP with west coast rapper Buddy and the lead single was “Find Me” an unequivocally bouncy track. This beat is one of those that you can point at Kaytranada as the culprit behind it immediately when you hear it. It’s signature Kaytra at his best and it’s truly what us fans have come to appreciate from him. This song almost made me dislike Buddy because of how good the beat was. There was just so much going on behind the vocals and Buddy was getting in the way of that. Let me now point out that I wrote those couple of sentences in past tense because it was truly just an initial feeling. I came to appreciate Buddy‘s contributions to the song more and more and he really does a good job of riding a hectic beat that has a lot going on. Most rappers can’t do that. Most of the hip hop hits are atop simple 8-bar loop beats that only feature one main melody along with drums and bass. As good as Kaytranada is, there’s plenty rappers that couldn’t handle a complex beat of his but Buddy can. – Trixx 14. Chance The Rapper – All Night (2016) This song just had to be on here, seeing that “All Night” is Kaytranada‘s most successful mainstream song. Chance is a superstar and he used a Kaytra beat on his last album Coloring Book and while he maintains his independent shtick, he was still able to generate some radio play for the album. “No Problem” was the main single but following behind it “All Night” got a lot of radio adds. There’s a certain signature bounce on this one as well with the song’s pounding upbeat rhythm even though the drums take a unique direction for the verses. These drums sound like they were sampled and interpolated from an African street corner musician. – Trixx 13. Mick Jenkins – P’s & Q’s (2015) There’s a couple of songs on this list that don’t feature a signature Kaytranada bounce and don’t include a lot of his signature sounds and “P’s & Q’s” is very notably a different sounding song for the producer. This song maintains an analog sound featuring a gritty, hypnotic guitar riff that carries the weight of the beat. As great as the beat is, Mick Jenkins really comes through on this cut as he flexes just how talented a lyricist and rapper he is by using alliteration throughout the song, using mostly words beginning with the letters “P” or “Q”. It’s truly an example of lyrical wizardry that ought to go down with some of the great melding of literary devices in rap. – Trixx 12. Goldlink – Celebration Freestyle (2016) This feels almost like cheating including this song on the list because it’s not truly an original collaboration but regardless of original intentions, this one’s fantastic. As the story goes, this was originally released to the world as a Kaytranada instrumental called “A Loser’s Celebration” but Goldlink picked it up a few months after it dropped to add some raps to it and turned it into “Celebration Freestyle”. This beat itself is an incredible, frenetic masterpiece with intermingling 808s and chanting vocal chops. This was a go-to speaker knocker last summer and that’s exactly what it’s perfect for. I’d kill for a collaborative project from Goldlink and Kaytranada where they’re having fun with the music and creating fun, uptempo bangers like this. – Trixx 11. Kaytranada – All We Do f. JMSN (2013) “All We Do” was one of the very early vocal tracks from Kaytranada and it was the only cut with original vocals included in his early 2013 project Kaytra Todo. At this point Kaytra had already found his signature sound, he was just fine tuning it and refining it all. “All We Do” was an incredible record and it always sticks with me just how hard that driving kick drum hits. In fact, it’s probably too hard. The song’s incredible but it’s one of those early songs that I bet if you asked Kaytra about, he’d wish he could go back to change so many things. Regardless there’s so many notable things happening here, particularly JMSN‘s infectious and lasting vocal performance. It’s such a viable collab and it’s truly a shame that these two haven’t worked together again. – Trixx 10. Kaytranada – You’re The One f. Syd (2016) Syd released her debut solo album away from her band The Internet earlier this year and if you ask me, it all sounds like a derivative of this song. “You’re The One” is airy and dreamy and the production really allows Syd to float and take a ride along this steady moving puffy musical cloud. This song was probably created at the same time the sessions were happening for her album Fin and this song truly would’ve felt right at home there. This would’ve been a standout if it were included on Fin *insert eyes emoji*. – Trixx 9. The Celestics – Funeral f. Goldlink (2014) This song is actually perfectly described by the fire emoji. This brotherly song brings in Goldlink and the final product is just a banger. Kaytra grabbed a sample from the film Evil Dead, thus why it sounds so cinematic but the sample’s indeed very simple. It’s just such an eery tone those sampled strings give off matched with great added layers that make this tune so undeniable. I can always have fun listening to this song and I’ll still enjoy it ten years down the road just as much as I do now. – Trixx 8. Goldlink – Fall In Love (2016) I mentioned on Twitter a little while back about how this was perhaps my favorite beat of 2016. In hindsight, that’s still very true and ultimately this song as a whole is super impressive to me. It might be surprisingly high on this list because technically it was just a loosie, a single before At What Cost that didn’t land on the album for whatever reason. Thus, this song is overlooked but the beat is absolutely remarkable. I’m a sucker for good vocal usage in beats and man the ascending and descending vocal samples on this song are divine. But aside from that there’s a lot of layers to this beat, not to mention Goldlink really outdid himself and delivered a couple dope verses as well as a memorable hook. – Trixx 7. Towkio – Reflection (2015) Before this song or rather before this album .Wav Theory, Towkio was still just Tokyo Shawn to me, one of many members of the SAVEMONEY crew. This album established him and it established his sound, a electronic infused, hip hop hybrid sound, something that our guy Kaytranada‘s a master at. This was one of the singles and certainly it was my favorite, led by a hypnotizing combination hook. Towkio yelling “COCAINE, ON THE MIRROR, SEE YOURSELF, LOOK AT YOU I’M RIGHT HERE, RIGHT HERE” along with the hypnotizing synths and bassline from Kaytra really set this track apart from the pack. And as those lyrics suggest, this cut’s deep. In that hook alone we’ve got Towkio speaking as the psyche of a young cocaine addict, an uber real topic that’s not touched on enough. Rap these days more than ever is about consuming drugs so such a real song like this that tells the truth about these glamorous drugs is a nice change of pace. Not to mention how hard it is to create an anti-drug song without sounding preachy and Towkio really did that on “Reflection”. – Trixx 6. Goldlink – Sober Thoughts (2015) Kaytranada has had a significant influence on Goldlink‘s career, probably more than any other rapper he’s worked with. Now Goldlink is starting to make a mainstream impact as “Crew” steadily moves up spots on the Billboard Hot 100 each week. One of the couple of songs that really catapulted him was “Sober Thoughts. The God Complex single features an unmatchable knock, with kick drums that could blow out your speakers. The drums are Norbit levels of fat and just like you keep her away from your good, more fragile chairs, you keep this away from your delicacies that you don’t want to break while raging to this track. Not to mention how incredible the bass line is on this song. It truly just features all the great elements that have made Kaytranada so iconic, a unique, slapping drum pattern, an incredible bass line and irreplicable synths. – Trixx 5. Kaytranada – Glowed Up f. Anderson .Paak (2016) We’re really into classic territory now, songs that are at least going to go down as classics for me. 99.9% was our #2 album for all of 2016, only trailing behind Frank Ocean‘s Blonde for good reason. That’s saying a lot already so it’s safe to say we really loved Kaytranada‘s debut album. I really hope he’s in the process of cooking up the follow-up but I’m still plentifully eating on the bountiful sounds of 99.9%. Before the album even dropped and we just had a couple singles and a tracklist, this track seemingly had a golden spotlight on it. Kaytra and Anderson .Paak make a good team and that was never more present than on this song. If Kaytra’s not the synth god, I don’t know who is. This song rattles off with Anderson going acapella for the first bar, only to be met with a beat drop promptly at the start of bar 2, immediately setting the tone for this track. This song’s iconic in every damn way, even the title “Glowed Up” is iconic. I try to find situations in conversation where I can utter the phrase “Glowed Up” because it’s just that cool. Back to the song though, which itself is the image of cool and anyone who doesn’t enjoy this song likely doesn’t have a soul. – Trixx 4. The Internet – Girl (2015) The Internet began as a group spawned from the Odd Future collective and it certainly took them some time to develop not only their sound but their following. The group has hit their peak thus far with their latest album Ego Death and one of the two singles from the album is the Kaytranada produced “Girl”. This song felt like a preview of Syd‘s debut solo album Fin. It’s bouncy and electronically flavored and it strays away from The Internet‘s more analog sound. The song stands out a bit sonically from its neighbors on the album but this song truly is gorgeous in its own special way. The beat packs a phenomenal melody in its synths and Syd absolutely slays on the vocals. This is one of those songs that will live on for a while, it’s the song that people will point you to when they try to put you onto The Internet. – Trixx 3. Kaytranada – Lite Spots (2016) I’ve kind of almost broken the rules. “Lite Spots” doesn’t feature a vocalist and it would’ve been much too hard to really rank and give each production fair due if I had to sift through the hundreds of instrumentals he has out as well. But I gave the few instrumentals on his studio album 99.9% a fair chance. Really though there was one truly special instrumental track and that was the album’s lead single “Lite Spots”. Even though I ought to stop calling it instrumental because this song doesn’t feel like that at all. Kaytranada utilizes a Brazilian vocal sample on this one which provides those perfectly on tempo, bouncy vocals atop the track that really bring this one to life. They’re so perfect and the rest of the beat is peak, bouncy Kaytranada. Not to mention, this song features one of the greatest and most memorable music videos in recent memory. Listening to this song without the video is like eating french fries without ketchup. Kaytra and his robot buddy are simply inseparable. – Trixx 2. Vic Mensa – Wimme Nah (2014) This song’s got a lot of resonance for me as I’m someone whose been a big Vic Mensa fan and believer ever since he was the front man of Kids These Days. Vic’s career has been quite the roller coaster ride and I truly feel there’s been a lot of missed opportunities in it. Between his highly lauded mixtape INNANETAPE and his There’s Alot Going On EP stood nearly three years. During that time Vic did a lot of changing and it’s evident based on the numerous loose songs he put out during that period. Early on, around 2014 Vic was big into electronic sounds. Not only did he release “Wimme Nah” but he also put out “Down On My Luck” and “Feel That” which all had a similar bouncy, electronic vibe. I truly wish he would’ve kept with that sound from a selfish fan’s point of view but those songs were coming from a dark point in Vic’s life. He outlines it well on “There’s A Lot Going On” as he talks about that period of his life bluntly and details he troubles with depression, addiction and more. To this day “Wimme Nah”‘s a go-to in the whip anthem. If I need a song that’ll really rattle the car then “Wimme Nah” will do it. The kicks are divine and the bounce is exquisite. This song will have the car bouncing like it’s got hydraulics. There’s plenty of dream collaboration projects I’ve got in my mental and an EP from KAYTRANADA and Vic Mensa is surely a realistic one that I really hope could happen one day. – Trixx 1. Kaytranada – Got It Good f. Craig David (2016) Queue the drum roll, we’ve finally made it to number one. That is, if you’re even reading this chronologically. Odds are you scrolled right down to the bottom of this list to see what songs took the top few spots. Well leading the charge is “Got It Good”, Kaytranada‘s collaboration with longtime British singer Craig David. This collaboration broke David’s hiatus, spanning back to 2012 which was when he was last featured on a song before this. This song sparked Craig David‘s comeback trail like no other song could. The two did a couple of songs together for David’s album as well but neither stood out quite like “Got It Good”. The song features a airy, almost spooky sound that leads the way for the first couple bars before the slaps bass and kicks come in to truly transform the song. This song just sounds beautiful from start to finish; all elements of the song are equally dope. Even the damn verses of this song are catchy for real. – Trixx
from wh_parser.funcat.context import ExecutionContext class CtxSpace: """ 拥有一个独立上下文的空间 """ def __init__(self, ctx:ExecutionContext=None): if ctx is None: ctx = ExecutionContext.get_active() self.ctx = ctx def ctx_wrapper(self, f): """ 上下问装饰器 :param f: :return: """ def func(*args, **kwargs): self.ctx._push() res = f(*args, **kwargs) self.ctx._pop() return res return func @classmethod def ctx_import(cls, freq, n): ctx = ExecutionContext.get_active().copy() ctx.set_current_freq(freq) return cls(ctx) @classmethod def ctx_call(cls, code): ctx = ExecutionContext.get_active().copy() ctx._order_book_id = code
/** * This class is generated by jOOQ */ package org.jooq.test.mysql.generatedclasses.tables.pojos; /** * This class is generated by jOOQ. */ @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class T_725LobTest implements java.io.Serializable { private static final long serialVersionUID = -217169107; private final java.lang.Integer id; private final byte[] lob; public T_725LobTest( java.lang.Integer id, byte[] lob ) { this.id = id; this.lob = lob; } public java.lang.Integer getId() { return this.id; } public byte[] getLob() { return this.lob; } }
import { Asset } from "../Asset"; import { GObject } from "../GObject"; import { Vector2 } from "../Utils"; export class Line extends Asset { draw(ctx: CanvasRenderingContext2D, parent: GObject) { ctx.beginPath(); ctx.strokeStyle = this.color; ctx.lineWidth = this.thickness; ctx.moveTo(...this.p1.getCoords()); ctx.lineTo(...this.p2.getCoords()); ctx.stroke(); } constructor( private p1: Vector2, private p2: Vector2, private color: string, private thickness: number ) { super(); } }
/** * Created by shivam on 29/5/17. */ @Singleton public class DataManager { private PlayerService mPlayerService; @Inject public DataManager(PlayerService playerService) { this.mPlayerService = playerService; } public Single<List<HeroesPlayed>> getHeroesPlayedList(long steamId) { String parameter = String.valueOf(steamId); return mPlayerService.getHeroesPlayedList(parameter) .toObservable() .flatMapIterable(item -> item) .map(item -> new HeroesPlayed(item)) .toList(); } public Single<PlayerProfile> getPlayerProfile(long steamId) { String parameter = String.valueOf(steamId); return mPlayerService.getPlayerProfile(parameter); } public Single<WinLoss> getPlayerWinLoss(long steamId) { String parameter = String.valueOf(steamId); return mPlayerService.getPlayerWinLoss(parameter); } }
import { Component, Host, Element, Prop, Watch, h } from '@stencil/core'; import Prism from 'prismjs'; import cssCoy from 'prismjs/themes/prism-coy.css'; import cssTomorrow from 'prismjs/themes/prism-tomorrow.css'; @Component({ tag: 'doc-html', styleUrl: 'html.css', shadow: true }) export class DocHtml { @Element() el: HTMLElement; @Prop() config: any = {}; @Prop() isDark?: boolean; @Prop() settings = []; @Watch('settings') settingsHandler() { this.init(); } get htmlCode() { const { element, slot } = this.config; return ` <${element} ${this.propsString}> ${slot || ''} </${element}> `; } get propsString() { return this.settings.map(d => { if (!d.value) { return ''; } return `${d.name}="${d.value}"`; }).filter(d => d).join(` `); } componentDidLoad() { this.init(); } render() { return ( <Host> {this.isDark && ( <style>{cssTomorrow}</style> )} {!this.isDark && ( <style>{cssCoy}</style> )} <arv-flex direction="column"> <arv-spacer></arv-spacer> <h2>Html</h2> <arv-divider></arv-divider> <arv-spacer></arv-spacer> <pre> <code class="language-html"> </code> </pre> </arv-flex> </Host> ); } private init() { const html = Prism.highlight(this.htmlCode, Prism.languages.html, 'html'); this.el.shadowRoot.querySelector('code').innerHTML = html; } }
package k8s import ( "fmt" "github.com/bwplotka/mimic" "github.com/bwplotka/mimic/abstractions/kubernetes/volumes" "github.com/bwplotka/mimic/encoding" "github.com/go-openapi/swag" "github.com/thanos-io/thanosbench/configs/abstractions/dockerimage" "github.com/thanos-io/thanosbench/configs/abstractions/secret" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" ) type StoreGatewayOpts struct { Namespace string Name string Img dockerimage.Image Resources corev1.ResourceRequirements IndexCacheBytes string // Defaults: 250MB ChunkCacheBytes string // Defaults: 2GB StoreAPILabelSelector string ObjStoreSecret secret.File ReadinessPath string } // NOTE: No persistent volume on purpose to simplify testing. It is must-have on the production setup. func GenThanosStoreGateway(gen *mimic.Generator, opts StoreGatewayOpts) { const ( replicas = 1 dataPath = "/data" httpPort = 19190 grpcPort = 19090 ) srv := corev1.Service{ TypeMeta: metav1.TypeMeta{ Kind: "Service", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: opts.Name, Namespace: opts.Namespace, Labels: map[string]string{ selectorName: opts.Name, }, }, Spec: corev1.ServiceSpec{ Type: corev1.ServiceTypeClusterIP, Selector: map[string]string{ selectorName: opts.Name, }, Ports: []corev1.ServicePort{ { Name: "http", Port: httpPort, TargetPort: intstr.FromInt(httpPort), }, { Name: "grpc", Port: grpcPort, TargetPort: intstr.FromInt(grpcPort), }, }, }, } sharedVM := volumes.VolumeAndMount{ VolumeMount: corev1.VolumeMount{ Name: opts.Name, MountPath: dataPath, }, } storeContainer := corev1.Container{ Name: "thanos", Image: opts.Img.String(), Command: []string{"thanos"}, Args: []string{ "store", "--log.level=debug", "--debug.name=$(POD_NAME)", fmt.Sprintf("--objstore.config-file=%s", opts.ObjStoreSecret.Path()), fmt.Sprintf("--index-cache-size=%s", opts.IndexCacheBytes), fmt.Sprintf("--chunk-pool-size=%s", opts.ChunkCacheBytes), fmt.Sprintf("--http-address=0.0.0.0:%d", httpPort), fmt.Sprintf("--grpc-address=0.0.0.0:%d", grpcPort), fmt.Sprintf("--data-dir=%s", dataPath), }, Env: []corev1.EnvVar{ // NOTE: Add following env var for old go memory management: {Name: "GODEBUG", Value:"madvdontneed=1"}. {Name: "POD_NAME", ValueFrom: &corev1.EnvVarSource{ FieldRef: &corev1.ObjectFieldSelector{ FieldPath: "metadata.name", }, }}, }, ReadinessProbe: &corev1.Probe{ Handler: corev1.Handler{ HTTPGet: &corev1.HTTPGetAction{ Port: intstr.FromInt(httpPort), Path: func() string { if opts.ReadinessPath == "" { return "/-/ready" } return opts.ReadinessPath }(), }, }, InitialDelaySeconds: 120, SuccessThreshold: 3, TimeoutSeconds: 10, FailureThreshold: 3, }, //LivenessProbe: &corev1.Probe{ // Handler: corev1.Handler{ // HTTPGet: &corev1.HTTPGetAction{ // Path: "/-/healthy", // Port: intstr.FromInt(httpPort), // }, // }, // InitialDelaySeconds: 350, // TimeoutSeconds: 30, // FailureThreshold: 3, //}, Ports: []corev1.ContainerPort{ { Name: "http", ContainerPort: httpPort, }, { Name: "grpc", ContainerPort: grpcPort, }, }, VolumeMounts: volumes.VolumesAndMounts{sharedVM, opts.ObjStoreSecret.VolumeAndMount}.VolumeMounts(), SecurityContext: &corev1.SecurityContext{ RunAsNonRoot: swag.Bool(false), RunAsUser: swag.Int64(1000), }, Resources: opts.Resources, } set := appsv1.StatefulSet{ TypeMeta: metav1.TypeMeta{ Kind: "StatefulSet", APIVersion: "apps/v1", }, ObjectMeta: metav1.ObjectMeta{ Name: opts.Name, Namespace: opts.Namespace, Labels: map[string]string{ selectorName: opts.Name, }, }, Spec: appsv1.StatefulSetSpec{ Replicas: swag.Int32(replicas), ServiceName: opts.Name, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: func() map[string]string { if opts.StoreAPILabelSelector == "" { return map[string]string{selectorName: opts.Name} } return map[string]string{ selectorName: opts.Name, opts.StoreAPILabelSelector: "true", } }(), Annotations: map[string]string{ "version": opts.Img.String(), }, }, Spec: corev1.PodSpec{ Containers: []corev1.Container{storeContainer}, Volumes: volumes.VolumesAndMounts{sharedVM, opts.ObjStoreSecret.VolumeAndMount}.Volumes(), }, }, Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ selectorName: opts.Name, }, }, }, } gen.Add(opts.Name+".yaml", encoding.GhodssYAML(set, srv)) }