content
stringlengths 10
4.9M
|
---|
// Adds instances for all test things
public void addTestTingInstances() {
for (GeneralTestInputOutput inputOutput : inputoutputs) {
if (inputOutput.instance == null) {
Instance instance = ThingMLFactory.eINSTANCE.createInstance();
instance.setName(inputOutput.name);
instance.setType(inputOutput.type);
config.getInstances().add(instance);
inputOutput.instance = instance;
}
}
for (GeneralTestInputOutput inputOutput : inputoutputs) {
boolean first = true;
for (GeneralTestInputOutput.Test test : inputOutput.getTests()) {
if (first) {
test.setInstance(inputOutput.instance);
first = false;
} else {
test.setInstance(copyInstanceConfiguration(inputOutput.instance, test));
}
}
}
} |
<reponame>WojciechKo/asgardex-electron
import { BCHChain, BNBChain, BTCChain, Chain, DOGEChain, ETHChain, LTCChain, THORChain } from '@xchainjs/xchain-util'
import * as O from 'fp-ts/lib/Option'
import * as Rx from 'rxjs'
import * as RxOp from 'rxjs/operators'
import * as BNC from '../binance'
import * as BTC from '../bitcoin'
import * as BCH from '../bitcoincash'
import { XChainClient$ } from '../clients'
import * as DOGE from '../doge'
import * as ETH from '../ethereum'
import * as LTC from '../litecoin'
import { selectedPoolChain$ } from '../midgard/common'
import * as THOR from '../thorchain'
import { Chain$ } from './types'
export const clientByChain$ = (chain: Chain): XChainClient$ => {
switch (chain) {
case BNBChain:
return BNC.client$
case BTCChain:
return BTC.client$
case BCHChain:
return BCH.client$
case ETHChain:
return ETH.client$
case THORChain:
return THOR.client$
case LTCChain:
return LTC.client$
case DOGEChain:
return DOGE.client$
// TODO (@veado) Add LUNA client
default:
return Rx.of(O.none)
}
}
export const getClientByChain$: (chain$: Chain$) => XChainClient$ = (chain$) =>
chain$.pipe(
RxOp.switchMap(
O.fold(
() => Rx.EMPTY,
(chain) => clientByChain$(chain)
)
)
)
/**
* Client depending on selected pool chain
*/
export const client$ = getClientByChain$(selectedPoolChain$)
|
def render_rect(self, box: Box, color: ColorType, projection: Matrix) -> None:
if not isinstance(color, ffi.CData):
color = ffi.new("float[4]", color)
lib.wlr_render_rect(self._ptr, box._ptr, color, projection._ptr) |
<reponame>foundations/futuquant<gh_stars>1-10
# -*- coding: utf-8 -*-
from futuquant import *
from .data_acquisition import *
from .config import config
from .check_config import CheckConfig
import sys
cc = CheckConfig()
ret, msg = cc.check_all()
if ret != RET_OK:
print(ret, msg)
sys.exit(1)
big_sub_codes = ['HK.02318', 'HK.02828', 'HK.00939', 'HK.01093', 'HK.01299', 'HK.00175',
'HK.01299', 'HK.01833', 'HK.00005', 'HK.00883', 'HK.00388', 'HK.01398',
'HK.01114', 'HK.02800', 'HK.02018', 'HK.03988', 'HK.00386', 'HK.01211']
ret, msg = quote_test(big_sub_codes, config.host, config.port)
if ret != RET_OK:
print(ret, msg)
sys.exit(1)
|
An end-to-end deep learning model can detect the gist of the abnormal in prior mammograms as perceived by experienced radiologists
This study investigated the possibility of building an end-to-end deep learning-based model for the prediction of a future breast cancer based on prior negative mammograms. We explored whether the probability of abnormal class membership given by the model was correlated with the gist of the abnormal as perceived by radiologists in negative prior mammograms. To build the model, an end-to-end network, previously developed for breast cancer detection, was fine-tuned for breast cancer prediction by using a dataset containing 650 prior mammograms from women, who were diagnosed with breast cancer in a subsequent screening and 1000 cancer-free women. On a set of 630 test images, the model achieved an AUC of 0.73. For extracting gist responses, 17 experienced radiologists were recruited, viewed mammograms for 500 milliseconds and gave a score showing whether they would categorize the case as normal or abnormal on the scale of 0- 100. The image set contained 40 normal, 40 current cancer images along with 72 prior mammograms from women who would eventually develop a breast cancer. We averaged the scores from 17 readers and produced a single score per image. The network achieved an AUC of 0.75 for differentiating prior images from normal images. For 72 prior mammograms, the output of the network was significantly correlated with the strength of the gist of the abnormal as perceived by experienced radiologists (Spearman’s correlation=0.84, p<0.01). This finding suggested that the network successfully learned the representation of the gist of the abnormal in prior mammograms as perceived by experienced radiologists. |
import { ErrorItem } from './error';
export interface RepositoryOkResponse<D> {
ok: true;
data: D;
errors: [];
}
export interface RepositoryErrorResponse {
ok: false;
data: undefined;
errors: ErrorItem[];
}
export type RepositoryResponse<D> =
| RepositoryOkResponse<D>
| RepositoryErrorResponse;
|
<filename>helpers/getTxnsUrl.ts
import moment from "moment";
export const DATE_FORMAT = "YYYYMMDD";
export function getTxnsUrl(
apiSiteUrl: string,
accountNumber: string,
startDate?: Date
) {
const defaultStartMoment = moment().subtract(1, "years").add(1, "day");
if (!startDate) {
startDate = defaultStartMoment.toDate();
}
const startMoment = moment.max(defaultStartMoment, moment(startDate));
const startDateStr = startMoment.format(DATE_FORMAT);
const endDateStr = moment().format(DATE_FORMAT);
return `${apiSiteUrl}/current-account/transactions?accountId=${accountNumber}&numItemsPerPage=150&retrievalEndDate=${endDateStr}&retrievalStartDate=${startDateStr}&sortCode=1`;
}
|
/**
* Class for loading Textures from drive<br>
* <br>
* Supported Formats (From STB):<br>
* <br>
* JPEG baseline and progressive (12 bpc/arithmetic not supported, same as stock
* IJG lib<br>
* PNG 1/2/4/8/16-bit-per-channel<br>
* TGA (not sure what subset, if a subset)<br>
* BMP non-1bpp, non-RLE<br>
* PSD (composited view only, no extra channels, 8/16 bit-per-channel)<br>
* GIF (*desired_channels always reports as 4-channel)<br>
* HDR (radiance rgbE format)<br>
* PIC (Softimage PIC)<br>
* PNM (PPM and PGM binary only)<br>
* <br>
*
* @author Darius Dinger
*/
public class TextureLoader {
/**
* Load TextureData file and store into TextureData object
*
* @param textureFile Path to TextureData relative to application
* @param mipmap Uses this TextureData mipmapping/anisotropic filtering (if
* supported)
* @param filtering Wich filtering mathod (GL_NEARES, GL_LINEAR, ...)
* @param asResource Loading TextureData from resources
* @return TextureData object
*/
public static TextureData loadTextureFileMeta(String textureFile, boolean mipmap, int filtering,
boolean asResource) {
// Define window icon variables
ByteBuffer textureData = null;
int textureWidth = 0, textureHeight = 0;
// Try to load icon
try (MemoryStack stack = MemoryStack.stackPush()) {
// Allocate memory
IntBuffer comp = stack.mallocInt(1);
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
if (asResource) {
// Load resource
ByteBuffer buffer = BufferUtils.ioResourceToByteBuffer(textureFile, 8 * 1024);
if (buffer == null) {
Logger.warn("Error by loading TextureData",
"The TextureData file " + textureFile + " could not be found! Returning null!");
return null;
}
// Load TextureData and throw exception at error
textureData = STBImage.stbi_load_from_memory(buffer, w, h, comp, 4);
} else {
// Load TextureData and throw exception at error
textureData = STBImage.stbi_load(textureFile, w, h, comp, 4);
}
if (textureData == null) {
Logger.warn("Error by loading TextureData",
"The TextureData file " + textureFile + " could not be loaded! Returning null!");
return null;
}
// Set width and height from buffer
textureWidth = w.get();
textureHeight = h.get();
} catch (IOException e) {
Logger.err("Error by loading TextureData",
"An IO Error occurs while " + "loading TextureData " + textureFile + "!");
Game.exit(1);
}
// Create texture data
TextureData texture = new TextureData();
texture.data = textureData;
texture.width = textureWidth;
texture.height = textureHeight;
return texture;
}
/**
* Loading a TextureData file into an opengl texture and storing into asset
* database
*
* @param textureFile Path to TextureData relative to application
* @param mipmap Uses this TextureData mipmapping/anisotropic filtering (if
* supported)
* @param filtering Wich filtering mathod (GL_NEARES, GL_LINEAR, ...)
* @param asResource Loading TextureData from resources
*/
public static void loadTextureFile(String textureFile, boolean mipmap, int filtering, boolean asResource) {
if (AssetDatabase.getTexture(textureFile) != 0)
return;
TextureData textureData = loadTextureFileMeta(textureFile, mipmap, filtering, asResource);
if (textureData != null)
textureData.generateKey(textureFile, mipmap, filtering);
else
AssetDatabase.addTexture(textureFile, AssetDatabase.getTexture(Material.TEXTURE_WHITE));
}
/**
* Loading cube map texture from abstract path and extension and storing into
* asset database. The cube map file names will be generated by:<br>
* path + ['_lf', '_rt', '_up', '_dn', '_ft', '_bk'] + '.' + ext
*
* @param path Abstract path to the cubemap
* @param ext Extension of the cube map Textures
* @param asResource Loading cube map Textures from resources
*/
public static void loadCubeMap(String path, String ext, boolean asResource) {
loadCubeMap(path, path + "_lf." + ext, path + "_rt." + ext, path + "_up." + ext, path + "_dn." + ext,
path + "_ft." + ext, path + "_bk." + ext, asResource);
}
/**
* Loadig cubemap texture from 6 texture files and storing into asset database
*
* @param key Key in the asset database
* @param left Left sube map texture
* @param right Right sube map texture
* @param top Top sube map texture
* @param bottom Bottom sube map texture
* @param front Front sube map texture
* @param back Back sube map texture
* @param asResource Loading cube map Textures from resources
*/
public static void loadCubeMap(String key, String left, String right, String top, String bottom, String front,
String back, boolean asResource) {
if (AssetDatabase.getTexture(key) != 0)
return;
// Loading cube map Textures
TextureData imgL = loadTextureFileMeta(left, false, GL11.GL_LINEAR, asResource);
TextureData imgR = loadTextureFileMeta(right, false, GL11.GL_LINEAR, asResource);
TextureData imgT = loadTextureFileMeta(top, false, GL11.GL_LINEAR, asResource);
TextureData imgB = loadTextureFileMeta(bottom, false, GL11.GL_LINEAR, asResource);
TextureData imgF = loadTextureFileMeta(front, false, GL11.GL_LINEAR, asResource);
TextureData imgBa = loadTextureFileMeta(back, false, GL11.GL_LINEAR, asResource);
// Gen and bind cube map texture
int tex = GL11.glGenTextures();
MemoryDumper.addTexture(tex);
GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, tex);
GL11.glEnable(GL13.GL_TEXTURE_CUBE_MAP);
// Apply textures to TextureData
GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL11.GL_RGBA, imgL.width, imgL.height, 0,
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imgL.data);
GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL11.GL_RGBA, imgR.width, imgR.height, 0,
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imgR.data);
GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL11.GL_RGBA, imgT.width, imgT.height, 0,
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imgT.data);
GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL11.GL_RGBA, imgB.width, imgB.height, 0,
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imgB.data);
GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL11.GL_RGBA, imgF.width, imgF.height, 0,
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imgF.data);
GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL11.GL_RGBA, imgBa.width, imgBa.height, 0,
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imgBa.data);
// Adding filtering
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
// Set edge wrap
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, 0);
AssetDatabase.addTexture(key, tex);
}
} |
<gh_stars>0
import { db } from "@firestore";
import { HttpError } from "@http-error";
import { autoId } from "@nicollite/utils";
import { Chopp } from "shared";
export const choppCollection = db.collection("chopps");
/**
* Add a the chop doc, if don't exists create a new doc
* @param chopps A Chopp object or array
*/
export async function addUpdateChoppInDb(chopps: Chopp | Chopp[]): Promise<Chopp | Chopp[]> {
const addChopp = async (chopp: Chopp) => {
chopp.id = chopp.id ? chopp.id : autoId();
await choppCollection.doc(chopp.id).set(chopp, { merge: true });
};
if (Array.isArray(chopps)) {
const choppsPromises = chopps.map(addChopp);
await Promise.all(choppsPromises);
} else {
await addChopp(chopps);
}
return chopps;
}
/**
* Get a chopp with the passed id
* @param id The chopp id
*/
export async function getChoppsInDb(id: string): Promise<Chopp>;
/** Get all chopps */
export async function getChoppsInDb(): Promise<Chopp[]>;
export async function getChoppsInDb(id?: string) {
if (id)
return choppCollection
.doc(id)
.get()
.then(docSnap => {
if (!docSnap.exists) throw new HttpError(404, `chopp with id ${id} not found`);
return docSnap.data();
});
return choppCollection.get().then(querySnap => querySnap.docs.map(docSnap => docSnap.data()));
}
/**
* Removes the chopp with the given id
* @param id The chopp id
*/
export async function deleteChoppInDb(id: string): Promise<void> {
await choppCollection.doc(id).delete();
}
|
Oncogenic Role of miR-15a-3p in 13q Amplicon-Driven Colorectal Adenoma-to-Carcinoma Progression
Progression from colorectal adenoma to carcinoma is strongly associated with an accumulation of genomic alterations, including gain of chromosome 13. This gain affects the whole q arm and is present in 40%–60% of all colorectal cancers (CRCs). Several genes located at this amplicon are known to be overexpressed in carcinomas due to copy number dosage. A subset of these genes, including the mir-17~92 cluster, are functionally involved in CRC development. The present study set out to explore whether apart from mir-17~92, other miRNAs located at the 13q amplicon show a copy number dependent dosage effect that may contribute to 13q-driven colorectal adenoma-to-carcinoma progression. Integration of publically available miRNA expression, target mRNA expression and DNA copy number data from 125 CRCs yielded three miRNAs, miR-15a, -17, and -20a, of which high expression levels were significantly correlated with a 13q gain and which influenced target mRNA expression. These results could be confirmed by qRT-PCR in a series of 100 colon adenomas and carcinomas.Functional analysis of both mature miRNAs encoded by mir-15a, i.e. miR-15a-5p and miR-15a-3p, showed that silencing of miR-15a-3p significantly inhibited viability of CRC cells. Integration of miR-15a expression levels with mRNA expression data of predicted target genes identified mitochondrial uncoupling protein 2 (UCP2) and COP9 signalosome subunit 2 (COPS2) as candidates with significantly decreased expression in CRCs with 13q gain. Upon silencing of miR-15a-3p, mRNA expression of both genes increased in CRC cells, supporting miR-15a-3p mediated regulation of UPC2 and COPS2 expression. In conclusion, significant overexpression of miR-15a-3p due to gain of 13q is functionally relevant in CRC, with UCP2 and COPS2 as candidate target genes. Taken together our findings suggest that miR-15a-3p may contribute to adenoma-to-carcinoma progression.
Introduction
The development of colorectal cancer (CRC) is marked by the accumulation of several recurrent chromosomal alterations, including gains of 8q, 13q, and 20q and losses of 8p, 15q, 17p and 18q , which can lead to altered expression of oncogenes and tumour suppressor genes . In fact, for a number of genes identified to be differentially expressed in a copy number dependent manner, functional relevance has been demonstrated. For instance, DIS3, LNX2 and CDK8 at 13q were recently described to play a role in CRC development due to 13q gaindependent overexpression . The same holds true for AURKA and TPX2 located at 20q, which were found to promote 20q amplicon-driven colorectal adenoma to carcinoma progression .
In addition to protein-encoding genes, DNA copy number changes may also affect expression of microRNAs (miRNAs) . MiRNAs are a family of small non-coding RNA molecules that play an important role in the regulation of many cellular processes by targeting the 3' UTR of mRNA molecules, thereby leading to gene silencing . Dysregulation of miRNA expression has been shown to play an important role in several human diseases, including cancer .
In CRC, altered expression of a number of miRNAs, due to chromosomal alterations or other mechanisms like epigenetic modifications, has been described. A well-documented example is the altered expression of the oncogenic miRNA cluster, mir-17~92 . We previously showed that increased mir-17~92 expression was linked to copy number gain of 13q and increased c-MYC expression during colorectal adenoma to carcinoma progression . Moreover, upregulation of mir-17~92 by c-MYC showed pro-angiogenic activity in colonocytes .
Chromosome 13 is gained in 40-60% of CRCs and is strongly associated with colorectal adenoma to carcinoma progression . This gain mostly encompasses the entire q-arm of chromosome 13 , raising the question whether next to coding genes and the mir-17~92 cluster, expression of other miRNAs located at this region is also affected by copy number dosage and may contribute to colorectal adenoma to carcinoma progression.
The present study aimed to identify additional candidate oncomiRs located at 13q in CRC. To this end, as an unbiased approach, we analysed all miRNAs mapping at 13q. Following validation of DNA copy number-dependent overexpression of 13q miRNAs by integrative analysis of DNA copy number and expression data-sets, the functional role of selected miRNAs was investigated in CRC cell lines using loss-of-function assays. Candidate target genes were identified by integration of miRNA expression levels with mRNA expression levels.
Integration of expression and copy number data
To investigate 13q miRNAs of which expression was regulated by DNA copy number changes, associations between DNA copy number and miRNA expression levels were studied. To this end we used an integrated approach, based on the use of covariate sets rather than single covariates, to determine subtle consistent associations with copy number alterations of a chromosomal region. The covariate set was defined by considering each miRNA probe individually and all copy number measurements within a 2Mb-window around the genomic start position of the miRNA. The analysis pipeline and definition of the covariate set is graphically presented in Fig 1 (association 1). The method used is implemented in the BioConductor package SIM . This procedure finds miRNAs of which expression is likely to be regulated by DNA copy number changes within this 2MB-window, by assigning one p-value to each miRNA. Multiple testing correction was done using the false-discovery rate (FDR) step-down procedure of Benjamini & Hoghberg . This analysis yielded a list of FDR values for miRNAs, of which expression is likely to be regulated by copy number changes in these samples. MiRNAs with FDR<0.05 were considered significant.
Target mRNA and miRNA expression integration
To identify which miRNAs are more likely to be functional, we studied their association with expression of predicted target mRNAs in the 125 CRC TCGA samples. To this end we used the approach developed by van Iterson et al . In short, for each miRNA, results of 4 target-prediction tools, namely TargetScan, PITA, microCosm and Mirtarbase , were combined to yield a list of possible mRNA targets. For further (i.e. second) analysis, candidate mRNA targets that were predicted by three or more prediction tools were selected. This list of target mRNAs defined the covariate set for this second analysis (Fig 1, association 2). Subsequently, a global test was used to test for associations between miRNA and mRNA expression, yielding one p-value per miRNA. Here the same statistical test was used as for the miRNA-copy number analysis, but now using the mRNA target list as covariate set. These p-values were corrected for multiple testing using the Benjamini & Hochberg FDR . FDR values <0.05 were considered significant. For each significant miRNA, we subsequently prioritised the mRNA targets using the p-value derived from an additional global test applied to the miRNA and each individual mRNA target. We selected for further analyses mRNA targets that had an individual p-value of <0.01.
In order to analyse expression patterns of several selected target mRNAs, previously generated expression data were used of a panel of colorectal adenomas (n = 37) and carcinomas (n = 31), available at GEO under accession number GSE8067 . Expression levels in both groups were compared using the Mann-Whitney U-test, considering p-values <0.05 as significant.
Tumour samples
A series of 100 snap-frozen colorectal tumour samples (48 adenomas and 52 carcinomas) prospectively collected at the VU University Medical Center in Amsterdam was used in this study. RNA from these samples was isolated using TRIzol (Invitrogen, Life technologies, Bleiswijk, The Netherlands), following the supplier's instructions. For a subset of these samples (12 adenomas and 15 carcinomas) whole genome DNA copy number status was known (5). For the remaining samples copy number status of chromosome 13q was determined by multiplex ligation-dependent probe amplification (MLPA) as described previously .
In cell lines miRNA expression levels of miR-15a-3p, miR-15a-5p and miR-17 were analysed using the miRCURY LNA Universal RT microRNA PCR (Exiqon, Vedbaek, Denmark) following the manufacturer's instructions. PCRs were run on an ABI 7500 Fast Real-time PCR system (Life technologies). Relative miRNA expression levels were determined using the 2(-ΔΔCt)method . Data were normalised using the small nucleolar RNA transcript RNU43 as a reference gene (Exiqon).
Cell viability
Cell viability was measured using the 3-(4,5-dimethylthiazolyl-2)-2,5-diphenyl tetrazolium bromide assay (MTT; MP Biomedicals, Eindhoven, The Netherlands). Twenty-four hours post-transfection with the antagomirs, cells were seeded in 96-wells culture plates for the MTT assay. Simultaneously, RNA was extracted from a subset of the cells to determine the miRNA expression levels. MTT measurements were performed at t = 0 and subsequently after 3 and 6 days. The relative viability was determined by subtracting the measurement at day 0 from subsequent time points. All measurements were performed in triplicate (technical replicates) and at least 2 independent experiments were performed (biological replicates). Relative viability of cells was compared using Student's t-test, with p-values <0.05 considered significant.
Results
MiR-15a shows copy number-associated differential expression in CRC In the present study, publically available TCGA data from 125 CRC samples were used to analyse both miRNA expression levels and DNA copy number levels of the loci involved on chromosome 13 . According to miRBase release 21 (www.mirbase.org), there are 40 miRNA located at chromosome 13 . For 14 out of these 40 miRNAs on 13q, expression data were available, and 6 of these were significantly overexpressed in CRCs due to copy number gain of 13q, i.e. miR-15a, -17, -19a, -20a, 19b-1 and -92a-1 (Table 1; FDR<0.05). These miRNAs all belong to two well-known clusters of miRNAs on chromosome 13, i.e. mir-15a/16 and mir-17~92.
Next to miRNA expression data, mRNA expression data were also available for the same panel of 125 CRCs. Using these data we examined whether overexpression of these miRNAs on 13q resulted in changes in the expression of predicted target genes . This analysis showed that, for miR-15a, -17 and -20a, overexpression due to copy number also significantly influenced predicted target mRNA expression (Table 1; FDR<0.05).
Next we analysed by qRT-PCR the expression levels of the top candidate miRNAs found in the in silico analyses in a series of 100 colon adenoma and carcinoma samples. Given the fact that mir-15a encodes for two mature miRNA strands, miR-15a-5p and miR-15a-3p, both were studied using strand-specific qRT-PCR. In line with the in silico data, expression levels of miR-15a-3p, miR-17 and miR-20a, were significantly higher in carcinomas compared to adenomas (Fig 2A). However, expression of miR-15a-5p was not significantly increased. Comparison of tumours with 13q gain with tumours without 13q gain showed that expression levels of all four miRNAs were significantly higher in tumours with gain (Fig 2B), corroborating the results from the in silico analysis.
MiR-15a-3p inhibits viability of CRC cells
Based on these analyses, miR-15a, -17 and -20a were identified as candidate oncogenic miR-NAs involved in CRC. Of these, both miR-17 and -20a have recently been described as oncogenes in CRC and prostate cancer , confirming the validity of the approach. MiR-15a on the other hand has been described to function as a tumour suppressor in chronic lymphocytic leukaemia (CLL) and, more recently, in CRC . To further support our current observations pointing to an oncogenic role of miR-15a in CRC, we set out to determine the functional relevance of miR-15a overexpression in CRC. Both strands of miR-15a, miR-15a-5p and miR-15a-3p, were studied using strand-specific miRNA inhibitors (antagomirs). An antagomir directed against miR-17, silencing of which was shown to decrease viability of CRC cells, was included as a positive control . A non-targeting antagomir was included as a negative control. The antagomirs were introduced into the SW480 CRC cell line, which has a gain of 13q encompassing the miR-15a locus. Efficiency of silencing varied per experiment between 75%-97%, 60-80% and 94%-96% for miR-15a-5p, miR-15a-3p and miR-17, respectively (Fig 3A). Silencing of miR-15a-3p and miR-17 led to a significant decrease in cell viability (Fig 3B). Silencing of miR-15a-5p also decreased cell viability significantly, although results were less consistent throughout replicate experiments (data not shown).
UCP2 and COPS2 as potential targets of miR-15a-3p in CRC By integrating miRNA expression profiles with mRNA expression profiles of predicted targets in 125 CRCs, we identified candidate target genes of miR-15a . The top five are shown in Table 2 (p <0.01). Of these five candidate target genes, four genes (TYRO3, UCP2, COPS2, RASGEF1B) were negatively associated with miR-15a expression, whereas (RNF125) was positively associated.
Since copy number gain of chromosome 13 has been associated with progression from colorectal adenoma-to-carcinoma, and current data show that this gain is associated with overexpression of miR-15a, we next evaluated whether the expression levels of the top five predicted target genes would show a decrease in carcinomas compared to adenomas, in conjunction with 13q gain. To this end, previously obtained array-CGH and mRNA expression microarray data of a panel of 37 colon adenomas and 31 carcinomas were used . In this set, expression of UCP2 was significantly decreased in carcinomas compared to adenomas (Fig 4A). Both UCP2 and COPS2 were significantly decreased in adenomas and carcinomas with a 13q gain compared to those without (Fig 4B). The comparison of adenomas without 13q gain to carcinomas with 13q gain, showed for both UCP2 and COPS2 significantly decreased expression in carcinomas with 13q gain (Fig 4C). In the case of TYRO3, a significant increase in expression was observed in both carcinomas (compared to adenomas), and in samples with 13q gain (compared to tumours without 13q gain). RNF125 and RASGEF1B expression levels were not related to progression or 13q copy number gain.
To further establish a role of miR-15a overexpression in UCP2 and COPS2 downregulation in CRC, mRNA expression levels of both genes were determined in SW480 cells, in which either miR15a-3p, miR15a-5p or control miR-17 were silenced. Compared to the non-targeting control, mRNA expression levels of UCP2 and, to a lesser extent, COPS2 were increased upon silencing of miR-15a-3p (Fig 5). Hardly any effect was seen when using antagomirs against miR-15a-5p or miR-17 (Fig 5). These results indicate that miR-15a-3p indeed targets both UCP2 and COPS2 in SW480 CRC cells.
Discussion
Here we investigated miRNAs that are overexpressed in CRC due to copy number gain of chromosome 13q. Analysis of publicly available TCGA miRNA expression and DNA copy number data of 125 CRC samples revealed that miR-15a, -17 and -20a were significantly upregulated in CRC in association with copy number gain of 13q, and that miR-15a, -17 and -20a significantly influenced expression of target genes. For both miR-20a and -17, an oncogenic role in CRC has been established . Interestingly, for miR-15a actually a tumour suppressor role has been claimed . The present results however indicate that miR-15a, in particular miR-15a-3p, functions as an oncogenic miRNA in CRC. Silencing of miR-15a-3p significantly decreased viability of CRC cells.
MiR-15a-3p in CRC Progression
MiR-15a is part of the mir-15a/16-1 cluster located at chromosome 13q14, which is encoded by its host gene deleted in leukaemia 2 (DLEU2) . To date, members of the mir-15a/16-1 cluster have been described as tumour suppressor miRNAs in several types of cancer . In chronic lymphocytic leukaemia, inactivation of these miRNAs occurs through a chromosomal loss at the locus of the mir-15a/16-1 cluster . In multiple myeloma, expression of mir-15a/16-1 was decreased whereas expression of its target gene VEGF-A was increased. Moreover, in these tumours expression of mir-15a/16-1 was shown to inhibit tumour formation by targeting pro-angiogenic factor VEGF-A . Similarly, in prostate cancer the expression of the miRNA cluster was downregulated, which was associated with upregulation of target genes BCL2, CCND1 and WNT3A. Knockdown of miR-15a and miR-16 in an in vitro model enhanced cancer progression by affecting cell survival, proliferation and invasion .
In CRC, miR-16 of this cluster had already been described to have a function as tumour suppressor . More recently however, the entire mir-15a/16-1 cluster was investigated and found to target AP4 in CRC, downregulation of which resulted in induction of mesenchymalepithelial transition (MET), inhibition of migration and invasion, and induction of cell cycle arrest . Additionally, expression of DLEU2, the gene encoding the mir-15a/16-1 cluster, was repressed in CRC samples compared to normal colon tissue and inversely correlated to AP4 expression. Altogether, those data suggest that miR-15a expression is decreased in CRC compared to normal tissue, which seems contradictory to the findings in the current study. In fact, the TCGA data presented here, also show that in CRC samples the expression of miR-15a actually increases in association with a DNA copy number gain of chromosome 13q. This gain is a common event in CRC, and in particular, in the progression from colorectal adenoma to carcinoma .
With respect to the role of the mir-15a/16-1 cluster in CRC, it is important to realize that the present study specifically focused on the association with a 13q gain involved in adenoma to carcinoma progression, whereas the above mentioned study of Shi et al. focused on CRC metastasis, representing a later event in the carcinogenic process . More importantly, we specifically identified miR-15a-3p as the driver strand and did not find evidence for the whole cluster to be involved. Recent research also showed that miR-15a-3p plays a tumour suppressor role in several cancer cell lines by targeting BCL-X L . However, no significant effect was seen in CRC cell lines . It is known that both the 5p and 3p strands of a miRNA can be expressed in cells and regulate target gene expression . The expression of either strand can also be tissue-specific . We therefore speculate that expression of different mature miRNAs from the mir-15a/16-1 cluster may have different roles in CRC, perhaps depending on the stage of CRC.
Evaluation of miR-15a-3p expression in a series of 48 adenomas and 52 carcinomas, for which 13q copy number status was known, showed that miR-15a-3p was significantly higher expressed in carcinomas compared to adenomas in a DNA copy number-dependent manner. These results corroborate an oncogenic role for increased miR-15a-3p expression on the 13q amplicon.
By combining the results of target prediction algorithms with mRNA expression profile data of CRCs, UCP2 and COPS2 were identified as candidate target genes of miR-15a. In support of this observation, upregulation of UCP2 and, to a lesser extent, of COPS2 was found in CRC cells when miR-15a-3p was silenced, compared to control transfectants. The absence of a similar effect in miR-15a-5p silenced CRC cells is consistent with our functional data showing that both strands seem to act independently. The present data indicate that UCP2, and potentially also COPS2, may function as tumour suppressors in CRC. Interestingly, overexpression of UCP2 in human pancreatic cancer and glioblastoma cell lines was recently described to repress malignancy by controlling mitochondrial function and redirecting energy production away from glycolysis . Also COPS2 was described as a putative tumour suppressor gene in a panel of different cancer types, where loss-of-function showed partial bypass of cellular senescence . Altogether, one could hypothesize that tumour cells would benefit from the inhibition of these genes through miRNA-mediated modulation.
According to the most recent release of the miRNA database (miRBase release 21), there are 40 miRNAs located at chromosome 13q. However, for this study we only had expression data of 14 13q-mapping miRNAs available, as expression levels of the remaining miRNAs were undetectable or not measured. Therefore, it cannot be excluded that additional miRNAs located at 13q may also be involved in CRC.
In summary, miR-15a-3p is gained and overexpressed in CRC, and this overexpression affects cell viability, supporting an oncogenic role of this miRNA in CRC. As a consequence, miR-15a-3p may play a role in the 13q gain-driven colorectal adenoma-to-carcinoma progression.
Supporting Information S1 Table. Overview of all the TCGA cases used in this study. Additional information on the data of 125 cases used from the TCGA. For all cases the sample ID, type of data (platform type), platform used, data level and the corresponding file names are listed. More information on the data used can be found at the TCGA Data Portal (https://tcga-data.nci.nih.gov/tcga/ tcgaDataType.jsp). (DOC) |
-- Compile with O2; SpecConstr should fire nicely
-- and eliminate all allocation in inner loop
module Main where
foo :: Int -> Maybe (Double,Double) -> Double
foo _ Nothing = 0
foo 0 (Just (x,y)) = x+y
foo n (Just (x,y)) = let r = f x y in r `seq` foo (n-1) (Just r)
where
f x y | x <= y = (x,y)
| otherwise = (y,x)
main = print (foo 1000000 (Just (1,2)))
|
/**
* find person with all names that have.
*/
@Override
public Person find(Long id) throws SQLException {
Person person = null;
List<Person_Name> person_names = new ArrayList<Person_Name>();
List<Person_Identifier> person_identifiers = new ArrayList<Person_Identifier>();
PreparedStatement preparedStatement = this.connect.prepareStatement(READ_QUERY_PERSON_BY_ID),
preparedStatement1 = this.connect.prepareStatement(READ_QUERY_PERSON_NAME_BY_ID),
preparedStatement2 = this.connect.prepareStatement(READ_QUERY_PERSON_IDENTIFIER_BY_ID);
try {
preparedStatement.setLong(1, id);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
person = new Person(
id,
rs.getString("p.title"),
rs.getString("p.photo"),
rs.getString("p.url"),
rs.getString("p.email"),
rs.getString("p.phone"),
new ArrayList<Person_Identifier>(),
new ArrayList<Person_Name>()
);
preparedStatement1.setLong(1, id);
ResultSet rs1 = preparedStatement1.executeQuery();
Person_Name pn = null;
while (rs1.next()) {
try {
pn = new Person_Name(
rs1.getLong("pn.person_nameID"),
id,
rs1.getString("pn.fullname"),
rs1.getString("pn.forename"),
rs1.getString("pn.middlename"),
rs1.getString("pn.surname"),
rs1.getString("pn.title"),
Utilities.parseStringDate(rs1.getString("pn.lastupdate_date")));
if (!person_names.contains(pn))
person_names.add(pn);
} catch (ParseException ex) {
Logger.getLogger(PersonDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
person.setPerson_names(person_names);
preparedStatement2.setLong(1, id);
ResultSet rs2 = preparedStatement2.executeQuery();
while (rs2.next()) {
person_identifiers.add(new Person_Identifier(rs2.getString("pi.ID"), rs2.getString("pi.Type")));
}
person.setPerson_identifiers(person_identifiers);
}
} catch (SQLException ex) {
logger.error(ex.getMessage());
} finally {
closeQuietly(preparedStatement);
closeQuietly(preparedStatement1);
closeQuietly(preparedStatement2);
}
return person;
} |
#include <stdio.h>
#include <stdlib.h>
void calcu(int ,int);
void ncalcu(int,int);
int main()
{
int n,m,count,count1,count2;
scanf("%d%d",&n,&m);
if(n%2==0){
calcu(n,m);
}
if(n%2!=0)
{
ncalcu(n,m);
}
return 0;
}
void calcu(int n,int m)
{
int count1,count2,count;
count1=n/2;
count2=m;
count=count1*count2;
printf("%d",count);
}
void ncalcu(int n,int m)
{
int count,count1,count2,t;
count1=n/2;
count2=m;
count=count1*count2;
t=m/2;
count=count+t;
printf("%d",count);
}
|
// helper to load a MathFont Property File
static nsresult
LoadProperties(const nsString& aName,
nsCOMPtr<nsIPersistentProperties>& aProperties)
{
nsAutoString uriStr;
uriStr.AssignLiteral("resource://gre/res/fonts/mathfont");
uriStr.Append(aName);
uriStr.StripWhitespace();
uriStr.AppendLiteral(".properties");
return NS_LoadPersistentPropertiesFromURISpec(getter_AddRefs(aProperties),
NS_ConvertUTF16toUTF8(uriStr));
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/time.h>
#include <math.h>
#include "error.h"
#include "file.h"
#include "gpio.h"
#include "task.h"
#include "kinematics.h"
const tasks_table_t tasks[] = { \
{ "gpio", &task_gpio }, \
{ "core", &task_core }, \
{ "kinematics", &task_kinematics }, \
{ NULL, NULL } /* end */
};
const tasks_table_t tasks_gpio[] = { \
{ "test_speed", &task_gpio_test_speed }, \
{ "test_poll", &task_gpio_test_poll }, \
{ NULL, NULL } /* end */
};
const tasks_table_t tasks_core[] = { \
{ "run", &task_core_run }, \
{ NULL, NULL } /* end */
};
const tasks_table_t tasks_kinematics[] = { \
{ "ik", *task_kinematics_ik }, \
{ "line", *task_kinematics_line }, \
{ "arc", *task_kinematics_arc }, \
{ NULL, NULL } /* end */
};
int task_parse(int level, int argc, char *argv[]) {
int i;
int (*function)(int argc, char *argv[]);
if (argc < level + 1) {
goto TASK_PARSE_USAGE;
}
function = task_lookup(tasks, level, argc, argv);
if (function) {
return function(argc, argv);
}
TASK_PARSE_USAGE:
warning("usage: %s <task> [<task parameters>]\n", argv[0]);
warning("supported tasks are:\n", argv[0]);
for (i = 0; tasks[i].name != NULL; ++i)
warning("\t%s\n", tasks[i].name);
return EXIT_FAILURE;
}
int (*task_lookup(const tasks_table_t *lookup_table, int argv_index, int argc, char *argv[]))(int argc, char *argv[]) {
int i;
if (argv_index >= argc) {
warning("%s: argv index %d is out of range (0 to %d)\n", __PRETTY_FUNCTION__, argv_index, argc - 1);
return NULL;
}
for (i = 0; lookup_table[i].name != NULL; ++i) {
if (strcmp(lookup_table[i].name, argv[argv_index]) == 0) {
return lookup_table[i].function;
break;
}
}
warning("%s: unhandled token '%s'\n", __PRETTY_FUNCTION__, argv[argv_index]);
return NULL;
}
|
def histogram(mass, h, w):
table = [[0]*w for i in range(h)]
for i in range(h):
for j in range(w):
if mass[i][j] == '*':
table[i][j] = 0
else:
table[i][j] = table[i-1][j] + 1
return table
def get_rectangle_area(table, w):
maxv = 0
stack = []
table.append(0)
for i, rect in enumerate(table):
if stack == []:
stack.append((rect, i))
elif stack[-1][0] < rect:
stack.append((rect, i))
elif stack[-1][0] == rect:
pass
elif stack[-1][0] > rect:
while stack != [] and stack[-1][0] >= rect:
high, pos = stack.pop()
maxv = max(maxv, high*(i-pos))
stack.append((rect, pos))
return maxv
while True:
h, w = map(int, raw_input().split())
if h == w == 0:
break
mass = [raw_input() for i in range(h)]
table = histogram(mass, h, w)
ans = 0
for tab in table:
ans = max(ans, get_rectangle_area(tab, w))
print ans |
def read(self):
msg = None
max_tries = 4
for attempt in range(1, max_tries + 1):
try:
while not isinstance(msg, pynmea2.GGA):
msg = pynmea2.parse(self.ser.readline())
except pynmea2.ParseError:
if attempt == max_tries:
raise GpsReadError('max number of parse attempts reached', attempt)
else:
pass
else:
break
return GpsReading(msg.latitude, msg.longitude, msg.altitude,
msg.timestamp) |
from collections import Counter
import sys
sys.setrecursionlimit(4100000)
n, m, k = map(int, input().split())
#友達関係
F = [[] for i in range(n)] #Friend
for i in range(m):
a, b = map(int, input().split())
F[a-1].append(b)
F[b-1].append(a)
#DFSで連結部分ごとのグループに分ける
G = [0] * n #Group
gid = 0 #group id
#DFSを行うための関数
def using_DFS(p):
if G[p] == 0:
G[p] = gid
for j in F[p]:
if G[j-1] == 0:
using_DFS(j-1)
else: #すでに登場
pass
else:
pass
for i in range(n):
if G[i] == 0:
gid += 1
using_DFS(i)
else:
pass
#print('G=',G)
#print('S=',S)
#ブロック関係
BinG = [[] for i in range(n)] #Block in Group
for i in range(k):
c, d = map(int, input().split())
if G[c-1] == G[d-1]:
BinG[c-1].append(d)
BinG[d-1].append(c)
else:
pass
#print('F=',F)
#print('B=',B)
GS = Counter(G) #Group Size
for i in range(n):
ans = GS[G[i]] - 1 - len(F[i]) - len(BinG[i])
print(ans) |
<reponame>trapchain/go-perun<filename>backend/ethereum/channel/contractbackend_test.go
// Copyright 2019 - See NOTICE file for copyright holders.
//
// 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 channel_test
import (
"context"
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
ethchannel "perun.network/go-perun/backend/ethereum/channel"
"perun.network/go-perun/backend/ethereum/channel/test"
ethwallet "perun.network/go-perun/backend/ethereum/wallet"
pkgtest "perun.network/go-perun/pkg/test"
"perun.network/go-perun/wallet"
)
func fromEthAddr(a common.Address) wallet.Address {
return (*ethwallet.Address)(&a)
}
func Test_calcFundingIDs(t *testing.T) {
tests := []struct {
name string
participants []wallet.Address
channelID [32]byte
want [][32]byte
}{
{"Test nil array, empty channelID", nil, [32]byte{}, make([][32]byte, 0)},
{"Test nil array, non-empty channelID", nil, [32]byte{1}, make([][32]byte, 0)},
{"Test empty array, non-empty channelID", []wallet.Address{}, [32]byte{1}, make([][32]byte, 0)},
// Tests based on actual data from contracts.
{"Test non-empty array, empty channelID", []wallet.Address{ðwallet.Address{}},
[32]byte{}, [][32]byte{{173, 50, 40, 182, 118, 247, 211, 205, 66, 132, 165, 68, 63, 23, 241, 150, 43, 54, 228, 145, 179, 10, 64, 178, 64, 88, 73, 229, 151, 186, 95, 181}}},
{"Test non-empty array, non-empty channelID", []wallet.Address{ðwallet.Address{}},
[32]byte{1}, [][32]byte{{130, 172, 39, 157, 178, 106, 32, 109, 155, 165, 169, 76, 7, 255, 148, 10, 234, 75, 59, 253, 232, 130, 14, 201, 95, 78, 250, 10, 207, 208, 213, 188}}},
{"Test non-empty array, non-empty channelID", []wallet.Address{fromEthAddr(common.BytesToAddress([]byte{}))},
[32]byte{1}, [][32]byte{{130, 172, 39, 157, 178, 106, 32, 109, 155, 165, 169, 76, 7, 255, 148, 10, 234, 75, 59, 253, 232, 130, 14, 201, 95, 78, 250, 10, 207, 208, 213, 188}}},
}
for _, _tt := range tests {
tt := _tt
t.Run(tt.name, func(t *testing.T) {
got := ethchannel.FundingIDs(tt.channelID, tt.participants...)
assert.Equal(t, got, tt.want, "FundingIDs not as expected")
})
}
}
func Test_NewTransactor(t *testing.T) {
rng := pkgtest.Prng(t)
s := test.NewSimSetup(rng)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
tests := []struct {
name string
ctx context.Context
gasLimit uint64
}{
{"Test without context", nil, uint64(0)},
{"Test valid transactor", ctx, uint64(0)},
{"Test valid transactor", ctx, uint64(12345)},
}
for _, _tt := range tests {
tt := _tt
t.Run(tt.name, func(t *testing.T) {
transactor, err := s.CB.NewTransactor(tt.ctx, tt.gasLimit, s.TxSender.Account)
assert.NoError(t, err, "Creating Transactor should succeed")
assert.Equal(t, s.TxSender.Account.Address, transactor.From, "Transactor address not properly set")
assert.Equal(t, tt.ctx, transactor.Context, "Context not set properly")
assert.Equal(t, tt.gasLimit, transactor.GasLimit, "Gas limit not set properly")
})
}
}
func Test_NewWatchOpts(t *testing.T) {
rng := pkgtest.Prng(t)
s := test.NewSimSetup(rng)
watchOpts, err := s.CB.NewWatchOpts(context.Background())
require.NoError(t, err, "Creating watchopts on valid ContractBackend should succeed")
assert.Equal(t, context.Background(), watchOpts.Context, "context should be set")
assert.Equal(t, uint64(1), *watchOpts.Start, "startblock should be 1")
key := "foo"
ctx := context.WithValue(context.Background(), &key, "bar")
watchOpts, err = s.CB.NewWatchOpts(ctx)
require.NoError(t, err, "Creating watchopts on valid ContractBackend should succeed")
assert.Equal(t, context.WithValue(context.Background(), &key, "bar"), watchOpts.Context, "context should be set")
assert.Equal(t, uint64(1), *watchOpts.Start, "startblock should be 1")
}
|
<reponame>sriharshachilakapati/SilenceEngine
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.shc.silenceengine.utils;
import com.shc.silenceengine.core.SilenceEngine;
/**
* A standard Time Utility class
*
* @author <NAME>
* @author Josh "ShadowLordAlpha"
*/
public final class TimeUtils
{
private static final double STARTING_MILLIS = System.currentTimeMillis();
private TimeUtils()
{
}
public static double currentNanos()
{
try
{
return SilenceEngine.display.nanoTime();
}
catch (Exception e)
{
// Can only occur if the time is called without a runtime, that is in class init
// So to prevent crashes there, we just ignore the exception and return time based
// on the System.currentTimeMillis(), which is a low resolution timer.
return convert(System.currentTimeMillis() - STARTING_MILLIS, Unit.MILLIS, Unit.NANOS);
}
}
public static double currentMicros()
{
return currentNanos() / 1000.0;
}
public static double currentMillis()
{
return currentMicros() / 1000.0;
}
public static double currentSeconds()
{
return currentMillis() / 1000.0;
}
public static double currentTime(Unit unit)
{
switch (unit)
{
case NANOS:
return currentNanos();
case MICROS:
return currentMicros();
case MILLIS:
return currentMillis();
default:
return currentSeconds();
}
}
public static double currentTime()
{
return currentTime(getDefaultTimeUnit());
}
public static double convert(double time, Unit source)
{
return convert(time, source, getDefaultTimeUnit());
}
public static double convert(double time, Unit source, Unit target)
{
if (source == target)
return time;
double factor = 1;
if (source == Unit.SECONDS)
{
if (target == Unit.MILLIS)
factor = 1000.0;
else if (target == Unit.MICROS)
factor = 1000000.0;
else
factor = 1000000000.0;
}
else if (source == Unit.MILLIS)
{
if (target == Unit.SECONDS)
factor = 1 / 1000.0;
else if (target == Unit.MICROS)
factor = 1000.0;
else
factor = 1000000.0;
}
else if (source == Unit.MICROS)
{
if (target == Unit.SECONDS)
factor = 1 / 1000000.0;
else if (target == Unit.MILLIS)
factor = 1 / 1000.0;
else
factor = 1000.0;
}
else
{
if (target == Unit.SECONDS)
factor = 1 / 1000000000.0;
else if (target == Unit.MILLIS)
factor = 1 / 1000000.0;
else if (target == Unit.MICROS)
factor = 1 / 1000.0;
}
return time * factor;
}
public static Unit getDefaultTimeUnit()
{
return Unit.SECONDS;
}
public enum Unit
{
NANOS, MICROS, MILLIS, SECONDS
}
}
|
// This is the latest version of AWS WAF, named AWS WAFV2, released in November,
// 2019. For information, including how to migrate your AWS WAF resources from the
// prior release, see the AWS WAF Developer Guide
// (https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html).
// Retrieves the WebACL for the specified resource.
func (c *Client) GetWebACLForResource(ctx context.Context, params *GetWebACLForResourceInput, optFns ...func(*Options)) (*GetWebACLForResourceOutput, error) {
if params == nil {
params = &GetWebACLForResourceInput{}
}
result, metadata, err := c.invokeOperation(ctx, "GetWebACLForResource", params, optFns, addOperationGetWebACLForResourceMiddlewares)
if err != nil {
return nil, err
}
out := result.(*GetWebACLForResourceOutput)
out.ResultMetadata = metadata
return out, nil
} |
<reponame>adityadani/go-replace-tag
package main
import (
"bytes"
"flag"
"fmt"
"go/parser"
"go/token"
"go/printer"
"go/ast"
"strings"
"os"
"github.com/Sirupsen/logrus"
)
const (
ReplaceTag = "// @replace-tag "
)
func replaceTagsInFile(input string) {
fset := token.NewFileSet() // positions are relative to fset
// Parse the file containing protobuf definitions
f, err := parser.ParseFile(fset, input, nil, parser.ParseComments)
if err != nil {
fmt.Println(err)
return
}
replacedTags := false
for _, d := range f.Decls {
// Get General Declaration
gDecl, ok := d.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range gDecl.Specs {
// Get Type Declaration
tSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
// Get Struct Declaration
sDecl, ok := tSpec.Type.(*ast.StructType)
if !ok {
continue
}
for _, field := range sDecl.Fields.List {
if field.Doc == nil {
continue
}
for _, comment := range field.Doc.List {
if strings.Contains(comment.Text, ReplaceTag) {
// Found a field
commentTag := strings.TrimPrefix(comment.Text, ReplaceTag)
commentTagKey := strings.Split(commentTag, ":")[0]
fieldTagTokens := strings.Split(strings.Trim(field.Tag.Value, "`"), " ")
foundFlt := ""
for _, flt := range fieldTagTokens {
if strings.HasPrefix(flt, commentTagKey) {
// Found the tag
foundFlt = flt
}
}
if foundFlt == "" {
continue
}
fmt.Printf("Replacing tag (%v) -> (%v) \n", foundFlt, commentTag)
r := strings.NewReplacer(foundFlt, commentTag)
field.Tag.Value = r.Replace(field.Tag.Value)
replacedTags = true
}
}
}
}
}
if replacedTags {
var buf bytes.Buffer
printer.Fprint(&buf, fset, f)
f, err := os.Create(input)
if err != nil {
fmt.Println("Unable to write protobuf files: ", err)
return
}
f.WriteString(buf.String())
}
}
func main() {
var input string
flag.StringVar(&input, "input", "", "path to input protobuf file")
flag.Parse()
if len(input) == 0 {
logrus.Errorf("input file not provided")
return
}
replaceTagsInFile(input)
}
|
import itertools
def luckygen():
count = 1
while True:
for i in itertools.product("47", repeat=count):
yield int("".join(i))
count += 1
num = input()
for i in luckygen():
if i > num:
break
if num % i == 0:
print "YES"
exit()
print "NO" |
<reponame>anirudhts/github-api-cli
package types
//UserInfo encapsulates user information
type UserInfo struct {
Name string `json:"name"`
Location string `json:"location"`
PublicRepos int `json:"public_repos"`
}
//Follower encapsulates follower meta
type follower struct {
Name string `json:"login"`
HTMLURL string `json:"html_url"`
}
//Followers represents list of followers
type Followers []follower
//RepoInfo is the description of a repo
type RepoInfo struct {
Name string `json:"name"`
}
|
<reponame>Grom1799/pathfinder
#include "libmx.h"
void *mx_memcpy(void *restrict dst, const void *restrict src, size_t n) {
unsigned char *p1 = dst;
unsigned char *p2 = (unsigned char *)src;
while (n--)
*p1++ = *p2++;
return dst;
}
|
/**
* Populate distinct keys part of cachedKeys for a particular row.
* @param row the row
* @param index the cachedKeys index to write to
*/
private void populateCachedDistinctKeys(Object row, int index) throws HiveException {
StandardUnion union;
cachedKeys[index][numDistributionKeys] = union = new StandardUnion(
(byte)index, new Object[distinctColIndices.get(index).size()]);
Object[] distinctParameters = (Object[]) union.getObject();
for (int distinctParamI = 0; distinctParamI < distinctParameters.length; distinctParamI++) {
distinctParameters[distinctParamI] =
keyEval[distinctColIndices.get(index).get(distinctParamI)].evaluate(row);
}
union.setTag((byte) index);
} |
#include "util/file.h"
#include "framework/log.h"
#include "util/memory.h"
#include <windows.h>
#include "util/platform/win/error.h"
#include "util/string.h"
/* ------------------------------------------------------------------------- */
uint32_t
file_load_into_memory(const char* file_name, void** buffer, file_opts_e opts)
{
HANDLE hFile;
LARGE_INTEGER buffer_size;
DWORD bytes_read;
/* open file */
hFile = CreateFile(TEXT(file_name), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "CreateFile() failed for file \"%s\"\n", file_name);
return 0;
}
for(;;)
{
/* get file size in bytes */
#ifdef ENABLE_WINDOWS_EX
if(!GetFileSizeEx(hFile, &buffer_size))
#else
DWORD high_part;
if((buffer_size.LowPart = GetFileSize(hFile, &high_part)) == INVALID_FILE_SIZE)
#endif
{
char* error = get_last_error_string();
fprintf(stderr, "GetFileSizeEx() failed for file \"%s\"\n", file_name);
fprintf(stderr, "error: %s\n", error);
free_string(error);
break;
}
#ifndef ENABLE_WINDOWS_EX
buffer_size.HighPart = (LONG)high_part;
#endif
/* unlikely to happen */
if(buffer_size.HighPart != 0)
{
fprintf(stderr, "GetFileSize() returned a file larger than a 32-bit integer, file \"%s\"\n", file_name);
break;
}
/* allocate buffer to copy file into */
if(opts & FILE_BINARY)
*buffer = MALLOC(buffer_size.LowPart);
else
*buffer = MALLOC(buffer_size.LowPart + sizeof(char));
if(*buffer == NULL)
{
fprintf(stderr, "malloc() failed in function file_load_into_memory()\n");
break;
}
/* copy file into buffer */
ReadFile(hFile, *buffer, buffer_size.LowPart, &bytes_read, NULL);
if(buffer_size.LowPart != bytes_read)
{
fprintf(stderr, "ReadFile() failed for file \"%s\"\n", file_name);
break;
}
CloseHandle(hFile);
/* append null terminator if not in binary mode */
if((opts & FILE_BINARY) == 0)
((char*)(*buffer))[buffer_size.LowPart] = '\0';
return (uint32_t)buffer_size.LowPart;
}
CloseHandle(hFile);
return 0;
}
/* ------------------------------------------------------------------------- */
void
free_file(void* ptr)
{
FREE(ptr);
}
|
import { fourDaysAgo, oneDayAgo, oneWeekAgo } from './dates';
/* eslint-disable max-len */
import {
CalendarItem,
Child,
Notification,
ScheduleItem,
User,
} from '@skolplattformen/api';
import { oneDayForward, oneWeekForward, twoDaysForward } from './dates';
const data: any = {
'39b59e-bf4b9f-f68ac25321-977218-bf0': {
calendar: [
{
title: 'Terminslut',
id: 73,
description: null,
location: null,
startDate: '2020-12-18',
endDate: '2020-12-18',
allDay: true,
},
{
title: 'Terminen börjar',
id: 74,
description: null,
location: null,
startDate: '2021-01-12',
endDate: '2021-01-12',
allDay: true,
},
{
title: 'APT - fritids stänger 15:45',
id: 75,
description: null,
location: null,
startDate: '2021-01-21',
endDate: '2021-01-21',
allDay: true,
},
{
title: 'Utvecklingsamtal',
id: 76,
description: null,
location: null,
startDate: '2021-02-04',
endDate: '2021-02-04',
allDay: true,
},
{
title: 'Vänliga veckan',
id: 77,
description: null,
location: null,
startDate: '2021-02-08',
endDate: '2021-02-12',
allDay: true,
},
{
title: 'Utvecklingsamtal',
id: 79,
description: null,
location: null,
startDate: '2021-02-09',
endDate: '2021-02-09',
allDay: true,
},
{
title: 'Trygghetsdag',
id: 78,
description: null,
location: null,
startDate: '2021-02-12',
endDate: '2021-02-12',
allDay: true,
},
{
title: 'APT fritids stänger 15:45',
id: 80,
description: null,
location: null,
startDate: '2021-02-25',
endDate: '2021-02-25',
allDay: true,
},
{
title: 'Sportlov',
id: 81,
description: null,
location: null,
startDate: '2021-03-01',
endDate: '2021-03-05',
allDay: true,
},
{
title: 'Studiedag',
id: 82,
description: null,
location: null,
startDate: oneWeekForward.startOf('day').toISODate(),
endDate: oneWeekForward.endOf('day').toISODate(),
allDay: true,
},
{
title: 'APT - fritids stänger 15:45',
id: 83,
description: null,
location: null,
startDate: '2021-04-01',
endDate: '2021-04-01',
allDay: true,
},
{
title: 'Långfredag',
id: 84,
description: null,
location: null,
startDate: '2021-04-02',
endDate: '2021-04-02',
allDay: true,
},
{
title: 'Påsklov',
id: 85,
description: null,
location: null,
startDate: '2021-04-05',
endDate: '2021-04-09',
allDay: true,
},
{
title: 'Föräldraråd',
id: 86,
description: null,
location: null,
startDate: '2021-04-20',
endDate: '2021-04-20',
allDay: true,
},
{
title: 'Prao åk 8',
id: 97,
description: null,
location: null,
startDate: '2021-04-26',
endDate: '2021-05-12',
allDay: true,
},
{
title: '<NAME>',
id: 87,
description: null,
location: null,
startDate: '2021-05-13',
endDate: '2021-05-13',
allDay: true,
},
{
title: 'Lov',
id: 88,
description: null,
location: null,
startDate: '2021-05-14',
endDate: '2021-05-14',
allDay: true,
},
{
title: 'APT Fritids stänger 15:45',
id: 90,
description: null,
location: null,
startDate: '2021-05-20',
endDate: '2021-05-20',
allDay: true,
},
{
title: 'Läsårsslut',
id: 91,
description:
"<html><head><style>\r\np.MsoNormal, li.MsoNormal, div.MsoNormal {\nmargin:0cm;\nmargin-bottom:.0001pt;\nfont-size:11.0pt;\nfont-family:'Calibri',sans-serif;\n}\n\na:link, span.MsoHyperlink {\ncolor:#0563C1;\ntext-decoration:underline;\n}\n\nspan.MsoHyperlinkFollowed {\ncolor:#954F72;\ntext-decoration:underline;\n}\n\nspan.E-postmall17 {\nfont-family:'Calibri',sans-serif;\ncolor:windowtext;\n}\n\n.MsoChpDefault {\nfont-family:'Calibri',sans-serif;\n}\n\ndiv.WordSection1 {\n}\n\r\n</style></head><body lang='SV' link='#0563C1' vlink='#954F72' style=''><div class='WordSection1'><p class='MsoNormal'> </p></div></body></html>",
location: null,
startDate: '2021-06-11',
endDate: '2021-06-11',
allDay: true,
},
{
title: 'Fritids stängt',
id: 92,
description:
"<html><head><style>\r\np.MsoNormal, li.MsoNormal, div.MsoNormal {\nmargin:0cm;\nmargin-bottom:.0001pt;\nfont-size:11.0pt;\nfont-family:'Calibri',sans-serif;\n}\n\na:link, span.MsoHyperlink {\ncolor:#0563C1;\ntext-decoration:underline;\n}\n\nspan.MsoHyperlinkFollowed {\ncolor:#954F72;\ntext-decoration:underline;\n}\n\nspan.E-postmall17 {\nfont-family:'Calibri',sans-serif;\ncolor:windowtext;\n}\n\n.MsoChpDefault {\nfont-family:'Calibri',sans-serif;\n}\n\ndiv.WordSection1 {\n}\n\r\n</style></head><body lang='SV' link='#0563C1' vlink='#954F72' style=''><div class='WordSection1'><p class='MsoNormal'> </p></div></body></html>",
location: null,
startDate: '2021-06-14',
endDate: '2021-06-14',
allDay: true,
},
],
schedule: [
{
title: 'Läsläxan tillbaka',
description: 'Ta med boken tillbaka till skolan',
location: '',
allDayEvent: false,
startDate: oneDayForward.startOf('day').toISO(),
endDate: oneDayForward.endOf('day').toISO(),
oneDayEvent: true
} as ScheduleItem
],
notifications: [
{
id: 'bfe19b-766db3-b38d99d321-bbed3d-506',
sender: 'Plan<NAME>',
dateCreated: oneDayAgo.minus({months: 6}).toISO(),
dateModified: fourDaysAgo.toISO(),
message: 'Ett nytt inlägg i en lärlogg har skapats.',
url:
'https://www.breakit.se/artikel/21423/har-ar-it-bolaget-bakom-haveriet-pa-skolplattformen',
category: 'Lärlogg',
type: 'avisering',
},
{
id: '9025f9-a1e685-d7c4668f09-e14bc5-0ab',
sender: 'Elevdokumentation',
dateCreated: '2020-12-10T14:31:29.966Z',
message:
'Nu kan du ta del av ditt barns dokumentation av utvecklingssamtal',
url:
'https://www.breakit.se/artikel/21404/kodaren-slog-larm-nu-akutstoppas-skolplattformen-i-stockholm',
category: null,
type: 'webnotify',
},
{
id: 'a24061-1c9a4e-83dc479d7c-f44fe9-376',
sender: 'Plan<NAME>',
dateCreated: '2020-06-10T12:18:00.000Z',
message: 'Nu finns det en bedömning att titta på.',
url:
'https://www.svt.se/nyheter/lokalt/stockholm/skolplattformen-i-stockholm-beratta-om-era-erfarenheter',
category: 'Bedömning',
type: 'avisering',
},
{
id: '79d65c-1f8240-35c94296ec-9f4bdc-cea',
sender: 'Plan<NAME>',
dateCreated: '2020-03-24T14:28:00.000Z',
message: 'Nu finns det en bedömning att titta på.',
url:
'https://www.breakit.se/artikel/18120/skolplattformen-kostade-700-miljoner-strid-med-entreprenor-om-varumarket',
category: 'Bedömning',
type: 'avisering',
},
{
id: '9c5b7b-52c16d-b9fc2e8248-e4de76-279',
sender: 'Plan<NAME>',
dateCreated: '2020-03-24T13:48:00.000Z',
message: 'Nu finns det en bedömning att titta på.',
url:
'https://www.mitti.se/nyheter/forskolans-tur-att-fa-kritiserade-skolplattformen-app/lmsau!5338007/',
category: 'Bedömning',
type: 'avisering',
},
],
},
'eea96a-a3e045-caab589391-ed7d17-029': {
calendar: [
{
title: 'Terminslut',
id: 73,
description: null,
location: null,
startDate: '2020-12-18',
endDate: '2020-12-18',
allDay: true,
},
{
title: 'Terminen börjar',
id: 74,
description: null,
location: null,
startDate: '2021-01-12',
endDate: '2021-01-12',
allDay: true,
},
{
title: 'APT - fritids stänger 15:45',
id: 75,
description: null,
location: null,
startDate: oneWeekForward.startOf('day').toISODate(),
endDate: oneWeekForward.endOf('day').toISODate(),
allDay: true,
},
{
title: 'Utvecklingsamtal',
id: 76,
description: null,
location: null,
startDate: '2021-02-04',
endDate: '2021-02-04',
allDay: true,
},
{
title: 'Vänliga veckan',
id: 77,
description: null,
location: null,
startDate: '2021-02-08',
endDate: '2021-02-12',
allDay: true,
},
{
title: 'Utvecklingsamtal',
id: 79,
description: null,
location: null,
startDate: '2021-02-09',
endDate: '2021-02-09',
allDay: true,
},
{
title: 'Trygghetsdag',
id: 78,
description: null,
location: null,
startDate: '2021-02-12',
endDate: '2021-02-12',
allDay: true,
},
{
title: 'APT fritids stänger 15:45',
id: 80,
description: null,
location: null,
startDate: '2021-02-25',
endDate: '2021-02-25',
allDay: true,
},
{
title: 'Sportlov',
id: 81,
description: null,
location: null,
startDate: '2021-03-01',
endDate: '2021-03-05',
allDay: true,
},
{
title: 'Studiedag',
id: 82,
description: null,
location: null,
startDate: '2021-03-22',
endDate: '2021-03-22',
allDay: true,
},
{
title: 'APT - fritids stänger 15:45',
id: 83,
description: null,
location: null,
startDate: '2021-04-01',
endDate: '2021-04-01',
allDay: true,
},
{
title: 'Långfredag',
id: 84,
description: null,
location: null,
startDate: '2021-04-02',
endDate: '2021-04-02',
allDay: true,
},
{
title: 'Påsklov',
id: 85,
description: null,
location: null,
startDate: '2021-04-05',
endDate: '2021-04-09',
allDay: true,
},
{
title: 'Föräldraråd',
id: 86,
description: null,
location: null,
startDate: '2021-04-20',
endDate: '2021-04-20',
allDay: true,
},
{
title: '<NAME>',
id: 97,
description: null,
location: null,
startDate: '2021-04-26',
endDate: '2021-05-12',
allDay: true,
},
{
title: '<NAME>',
id: 87,
description: null,
location: null,
startDate: '2021-05-13',
endDate: '2021-05-13',
allDay: true,
},
{
title: 'Lov',
id: 88,
description: null,
location: null,
startDate: '2021-05-14',
endDate: '2021-05-14',
allDay: true,
},
{
title: 'APT Fritids stänger 15:45',
id: 90,
description: null,
location: null,
startDate: '2021-05-20',
endDate: '2021-05-20',
allDay: true,
},
],
schedule: [
{
title: 'Läxförhör franska',
description: 'Läxförhör, glosor samt verben!',
location: 'Klassrummet',
allDayEvent: false,
startDate: twoDaysForward.startOf('day').toISO(),
endDate: twoDaysForward.endOf('day').toISO(),
oneDayEvent: false
} as ScheduleItem
],
notifications: [
{
id: 'e1b5bc-597fa8-5511794939-3614e1-615',
sender: 'Planering och Bedömning',
dateCreated: fourDaysAgo.toISO(),
dateModified: fourDaysAgo.toISO(),
message: 'Ett nytt inlägg i en lärlogg har skapats.',
url:
'https://www.mitti.se/nyheter/rekorddyr-skolplattform-kostar-258-miljoner-till/lmsao!5381301/',
category: 'Lärlogg',
messageType: 'avisering',
},
{
id: '7dbc20-bfa1ac-e20171b865-82c1f7-f3c',
sender: 'Planering och Bedömning',
dateCreated: '2020-12-01T12:43:00.000Z',
message: 'Ett nytt inlägg i en lärlogg har skapats.',
url:
'https://computersweden.idg.se/2.2683/1.722561/lacka-skolplattformen-datainspektionen',
category: 'Lärlogg',
messageType: 'avisering',
},
{
id: 'a6829b-ecf912-b71582e8fb-b6dc14-f60',
sender: 'Plan<NAME>',
dateCreated: '2020-11-24T13:34:00.000Z',
message: 'Ett nytt inlägg i en lärlogg har skapats.',
url: 'https://www.dagensarena.se/redaktionen/en-systemkramare-ger-upp/',
category: 'Lärlogg',
messageType: 'avisering',
},
{
id: '3cedb4-767d24-8ccd6ac3ac-c05cb7-a3a',
sender: 'Plan<NAME>',
dateCreated: '2020-11-16T13:24:00.000Z',
message: 'Ett nytt inlägg i en lärlogg har skapats.',
url:
'https://www.breakit.se/artikel/27075/skolplattformen-kostade-1-miljard-att-bygga-nu-tvingas-stockholm-bota',
category: 'Lärlogg',
messageType: 'avisering',
},
{
id: '6ace13-5f99da-d1d50ac7a6-4a6108-d8e',
sender: 'Plan<NAME>',
dateCreated: '2020-11-12T13:27:00.000Z',
message: 'Ett nytt inlägg i en lärlogg har skapats.',
url:
'https://www.nyteknik.se/sakerhet/ygeman-om-datalackan-i-skolplattformen-det-ar-upprorande-6968853',
category: 'Lärlogg',
messageType: 'avisering',
},
],
},
}
export const user = (): User => ({
personalNumber: '195001182046', // Test personal number from Skatteverket
firstName: 'Namn',
lastName: 'Namnsson',
isAuthenticated: true
})
export const calendar = (child: Child): CalendarItem[] =>
data[child.id].calendar
export const schedule = (child: Child): ScheduleItem[] =>
data[child.id].schedule
export const notifications = (child: Child): Notification[] =>
data[child.id].notifications
|
/**
* Switches the left-side valve on the analyte collector to the
* "TO COLUMN" position.
*/
public void leftColumnPulse() {
if (!checkPort()) {
return;
}
println("C-");
controller.sendToVnmr("lcColumnValve=1");
} |
// this inner class cannot be static because it uses member variable(s) in JCmdLineApp
public class SysConsoleInput extends ConsoleInputStream {
public void doBeforeInput() {
}
public String inputString() throws InterruptedException {
String strInput = "";
try {
// mBufferedReader cannot be null
strInput = mBufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return strInput;
}
public void doAfterInput() {
}
} |
<reponame>surgefm/v2land-redstone
import * as bcrypt from 'bcrypt';
import { RedstoneRequest, RedstoneResponse } from '@Types';
import { Client, sequelize } from '@Models';
import { ClientService, RecordService } from '~/api/services';
async function changePassword(req: RedstoneRequest, res: RedstoneResponse) {
const data = req.body;
let salt;
let hash;
if (
typeof data.id === 'undefined' ||
typeof data.password === 'undefined'
) {
return res.status(404).json({
message: '参数错误',
});
}
ClientService.validatePassword(data.password);
const { clientId } = req.session;
const targetId = data.id;
const selfClient = req.currentClient;
await sequelize.transaction(async transaction => {
const targetClient = await Client.findOne({
where: {
id: targetId,
},
transaction,
});
if (typeof targetClient === 'undefined') {
return res.status(500).json({
message: '找不到目标用户',
});
}
if (targetId !== clientId && selfClient.isAdmin) {
return res.status(500).json({
message: '您没有修改此用户密码的权限',
});
}
try {
salt = await bcrypt.genSalt(10);
hash = await bcrypt.hash(data.password, salt);
} catch (err) {
req.log.error(err);
return res.status(500).json({
message: '服务器发生未知错误,请联系开发者',
});
}
targetClient.password = <PASSWORD>;
await targetClient.save({ transaction });
await RecordService.update({
model: 'Client',
action: 'updateClientPassword',
client: targetId,
target: targetId,
}, { transaction });
res.status(201).send({
message: '更新密码成功',
});
});
}
export default changePassword;
|
/**
* Omakase REST Application
*
* @author Richard Lucas
*/
@ApplicationPath("api")
public class OmakaseApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new HashSet<>();
resources.addAll(getProviders());
resources.addAll(getInterceptorsAndFilters());
resources.addAll(getOmakaseAPIResources());
resources.addAll(getExceptionMappers());
return resources;
}
private Set<Class<?>> getOmakaseAPIResources() {
Set<Class<?>> resources = new HashSet<>();
resources.add(ContentResource.class);
resources.add(JobManagementResource.class);
resources.add(RepositoryResource.class);
resources.add(LocationResource.class);
resources.add(BrokerResource.class);
resources.add(StatusResource.class);
resources.add(VersionResource.class);
return resources;
}
private Set<Class<?>> getExceptionMappers() {
Set<Class<?>> resources = new HashSet<>();
resources.add(ThrowableExceptionMapper.class);
resources.add(WebApplicationExceptionMapper.class);
resources.add(EJBExceptionMapper.class);
resources.add(NotAuthorizedExceptionMapper.class);
resources.add(NotFoundExceptionMapper.class);
resources.add(InvalidPropertyExceptionMapper.class);
resources.add(JaxRsNotFoundExceptionMapper.class);
resources.add(JsonMappingExceptionMapper.class);
resources.add(JsonParseExceptionMapper.class);
resources.add(InvalidSearchConditionExceptionMapper.class);
resources.add(RepositoryConfigurationExceptionMapper.class);
resources.add(NotUpdateableExceptionMapper.class);
resources.add(InvalidUUIDExceptionMapper.class);
resources.add(JobConfigurationExceptionMapper.class);
return resources;
}
private Set<Class<?>> getProviders() {
Set<Class<?>> resources = new HashSet<>();
resources.add(JsonProvider.class);
return resources;
}
private Set<Class<?>> getInterceptorsAndFilters() {
Set<Class<?>> resources = new HashSet<>();
resources.add(JsonPatchInterceptor.class);
resources.add(PostJobInterceptor.class);
resources.add(PutJobConfigInterceptor.class);
resources.add(PutRepositoryConfigInterceptor.class);
resources.add(PutLocationConfigInterceptor.class);
resources.add(APIVersionRequestFilter.class);
return resources;
}
} |
/**
* Common superclass for classes that update the jobs hierarchy by subscribing toJMX notifications from the drivers.
* @author Laurent Cohen
* @since 5.1
* @exclude
*/
abstract class AbstractJobNotificationsHandler implements NotificationListener, JobMonitoringHandler {
/**
* Logger for this class.
*/
private static Logger log = LoggerFactory.getLogger(AbstractJobNotificationsHandler.class);
/**
* Determines whether the debug level is enabled in the log configuration, without the cost of a method call.
*/
private static boolean debugEnabled = log.isDebugEnabled();
/**
* The default maximum number of pending JMX notifications.
*/
private static final int DEFAULT_MAX_NOTIFICATIONS = 5_000;
/**
* the associated job monitor.
*/
final JobMonitor monitor;
/**
* Used to queue the JMX notifications in the same order they are received with a minimum of interruption.
*/
final QueueHandler<JobNotification> notificationsQueue;
/**
* Mapping of driver uuids to takss initializing and regstering a driver job management notifications listener.
*/
final Map<String, JmxInitializer> initializerMap = new HashMap<>();
/**
* Listens for drivers joining or leaving the grid.
*/
final DriverListener driverListener;
/**
* Initialize with the specified job monitor.
* @param monitor an instance of {@link JobMonitor}.
*/
AbstractJobNotificationsHandler(final JobMonitor monitor) {
if (debugEnabled) log.debug("initializing {} with {}", getClass().getSimpleName(), monitor);
this.monitor = monitor;
monitor.getTopologyManager().addTopologyListener(driverListener = new DriverListener());
final int capacity = monitor.getTopologyManager().getJPPFClient().getConfig().getInt("jppf.job.monitor.max.notifications", DEFAULT_MAX_NOTIFICATIONS);
final int cap = (capacity <= 0) ? DEFAULT_MAX_NOTIFICATIONS : capacity;
notificationsQueue = QueueHandler.<JobNotification>builder()
.named("JobNotificationsHandler")
.withCapacity(cap)
.handlingElementsAs(this::handleNotificationAsync)
.handlingPeakSizeAs(n -> {
if (debugEnabled && (n >= cap)) log.debug("maximum peak job notifications: {}", n);
})
.usingSingleDequuerThread()
.build();
}
@Override
public void handleNotification(final Notification notification, final Object handback) {
if (log.isTraceEnabled()) log.trace("got jmx notification: {}", notification);
try {
notificationsQueue.put((JobNotification) notification);
} catch (final Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* Handle a notification asynchronously.
* @param notif the notification to handle.
*/
abstract void handleNotificationAsync(final JobNotification notif);
@Override
public void close() {
monitor.getTopologyManager().removeTopologyListener(driverListener);
notificationsQueue.close();
synchronized(initializerMap) {
initializerMap.clear();
}
}
/**
* Listens to driver added/removed events.
*/
private class DriverListener extends TopologyListenerAdapter {
@Override
public void driverAdded(final TopologyEvent event) {
final TopologyDriver driver = event.getDriver();
final JmxInitializer jinit = new JmxInitializer(driver);
synchronized(initializerMap) {
initializerMap.put(driver.getUuid(), jinit);
}
ThreadUtils.startDaemonThread(jinit, driver.toString());
}
@Override
public void driverRemoved(final TopologyEvent event) {
final String uuid = event.getDriver().getUuid();
if (uuid != null) {
JmxInitializer jinit = null;
synchronized(initializerMap) {
jinit = initializerMap.remove(uuid);
}
if (jinit != null) jinit.setStopped(true);
}
}
}
/**
* Initializer running in a separate thread for each driver, until it gets a working (connected) proxy to the job management MBean.
*/
private class JmxInitializer extends ThreadSynchronization implements Runnable {
/**
* The driver to connect to.
*/
final TopologyDriver driver;
/**
* Create this initializer witht he specified driver.
* @param driver the driver to connect to.
*/
JmxInitializer(final TopologyDriver driver) {
this.driver = driver;
}
@Override
public void run() {
if (debugEnabled) log.debug("starting jmx intializer for " + driver);
boolean done = false;
while (!done && !isStopped()) {
try {
final DriverJobManagementMBean mbean = driver.getJobManager();
if (mbean != null) {
done = true;
mbean.addNotificationListener(AbstractJobNotificationsHandler.this, null, null);
if (debugEnabled) log.debug("registered jmx listener for " + driver);
synchronized(initializerMap) {
initializerMap.remove(driver.getUuid());
}
} else goToSleep(10L);
} catch (final Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
} |
Contact-induced doping in aluminum-contacted molybdenum disulfide
The interface between two-dimensional semiconductors and metal contacts is an important topic of research of nanoelectronic devices based on two-dimensional semiconducting materials such as molybdenum disulfide (MoS2). We report transport properties of thin MoS2 flakes in a field-effect transistor geometry with Ti/Au and Al contacts. In contrast to widely used Ti/Au contacts, the conductance of flakes with Al contacts exhibits a smaller gate-voltage dependence, which is consistent with a substantial electron doping effect of the Al contacts. The temperature dependence of two-terminal conductance for the Al contacts is also considerably smaller than for the Ti/Au contacts, in which thermionic emission and thermally assisted tunneling play a dominant role. This result is explained in terms of the assumption that the carrier injection mechanism at an Al contact is dominated by tunneling that is not thermally activated. |
What do you want to happen to your body once you die? Do you want to be buried? Perhaps in a graveyard with the rest of your family? Or maybe you’d rather be cremated and have your ashes scattered about your favourite site? Whatever you want, it’s going to be something pretty ‘normal’, isn’t it? Well, how about this? Why not be turned into a diamond?! An ever-lasting gem to be treasured and even worn by the loved ones you leave behind?
Intrigued?
The Swiss company Algordanza is making that bizarre dream very much a reality. ‘Memorial diamonds’ might just be the next big thing…
Diamonds are, basically, created from carbon. Us human beings are made of carbon. ‘All’ you need to do (in a very scientific and exact way) is extract the carbon from someone’s remains, convert it to graphite, heat and press. Et voila! A human diamond!
What colour will you be? Well, that all depends on the amount of boron in your remains. The more you have in you, the bluer your diamond will appear!
It’s not a cheap process, though. On top of whatever your cremation costs are, the price of diamonding you starts at around $4,500…
Would you do it??? |
<gh_stars>1-10
#include "LaplacesDemon.h"
#include <RcppArmadilloExtensions/sample.h>
using namespace Rcpp;
using namespace arma;
SEXP mcmcamwg(SEXP MODEL, SEXP DATA, SEXP ITERATIONS, SEXP STATUS,
SEXP THINNING, SEXP SPECS, SEXP ACCEPTANCE, SEXP DEV, SEXP DIAGCOVAR,
SEXP liv, SEXP MON, SEXP MO0, SEXP SCALEF, SEXP THINNED, SEXP TUNING) {
Function Model(MODEL);
Rcpp::List Data(DATA), Specs(SPECS), Mo0(MO0);
int Iterations = as<int>(ITERATIONS), Status = as<int>(STATUS),
Thinning = as<int>(THINNING), LIV = as<int>(liv),
ScaleF = as<int>(SCALEF), Periodicity = as<int>(Specs["Periodicity"]),
ACCEPT = as<int>(ACCEPTANCE);
Rcpp::IntegerVector Acceptance(LIV, ACCEPT);
Rcpp::NumericMatrix Dev(DEV), Mon(MON), thinned(THINNED);
Rcpp::NumericVector tuning(TUNING);
int a_iter = 0, t_iter = 0, fins = 0, mcols = Mon.ncol();
double log_alpha = 0;
Rcpp::NumericMatrix DiagCovar(floor(Iterations / Periodicity), LIV);
Rcpp::List Mo1 = clone(Mo0);
RNGScope scope;
for (int iter = 0; iter < Iterations; iter++) {
// Print Status
if ((iter + 1) % Status == 0) {
Rcpp::Rcout << "Iteration: " << iter + 1 <<
", Proposal: Componentwise, LP: " <<
floor(as<double>(Mo0["LP"]) * 100) / 100 << std::endl;
}
// Save Thinned Samples
if ((iter + 1) % Thinning == 0) {
t_iter = floor((iter) / Thinning) + 1;
thinned(t_iter,_) = as<Rcpp::NumericVector>(Mo0["parm"]);
Dev(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Dev"]);
Mon(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Monitor"]);
}
// Random-Scan Componentwise Estimation
Rcpp::NumericVector u = log(runif(LIV));
Rcpp::NumericVector z = rnorm(LIV);
Rcpp::IntegerVector LIVseq = Rcpp::Range(1, LIV);
Rcpp::IntegerVector s = Rcpp::RcppArmadillo::sample(LIVseq, LIV,
false, NumericVector::create());
s = s - 1;
for (int j = 0; j < LIV; j++) {
// Propose new parameter values
Rcpp::List Mo0_ = clone(Mo0);
Rcpp::NumericVector prop = Mo0_["parm"];
prop[s[j]] += z[s[j]] * tuning[s[j]];
// Log-Posterior of the proposed state
Rcpp::List Mo1 = Model(prop, Data);
fins = ::R_finite(Mo1["LP"]) + ::R_finite(Mo1["Dev"]);
for (int m = 0; m < mcols; m++) {
fins += ::R_finite(as<Rcpp::NumericVector>(Mo1["Monitor"])[m]);
}
if (fins < (mcols + 2)) Mo1 = Mo0;
// Accept/Reject
double LP0 = Mo0_["LP"];
double LP1 = Mo1["LP"];
log_alpha = LP1 - LP0;
if (u[s[j]] < log_alpha) {
Mo0 = Mo1;
Acceptance[s[j]] += 1.0;
}
}
if ((iter + 1) % Thinning == 0) {
thinned(t_iter,_) = as<Rcpp::NumericVector>(Mo0["parm"]);
Dev(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Dev"]);
Mon(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Monitor"]);
}
// Adapt the Proposal Variance
if ((iter + 1) % Periodicity == 0) {
double sqiter = pow(iter + 1.0, 0.5);
if (sqiter > 100) sqiter = 100.0;
double size = 1.0 / sqiter;
Rcpp::NumericVector AcceptanceRate(Rcpp::clone(Acceptance));
AcceptanceRate = AcceptanceRate / iter;
Rcpp::NumericVector logtuning(log(tuning));
for (int k = 0; k < LIV; k++) {
if (AcceptanceRate[k] > 0.44) logtuning[k] += size;
else logtuning[k] -= size;
tuning = exp(logtuning);
a_iter = floor(iter / Periodicity);
DiagCovar(a_iter,_) = tuning;
}
}
}
int sumAccept = 0;
for (int k = 0; k < LIV; k++) {
sumAccept += Acceptance[k];
}
double acceptance = sumAccept / (LIV * 1.0);
return wrap(Rcpp::List::create(Rcpp::Named("Acceptance") = acceptance,
Rcpp::Named("Dev") = Dev,
Rcpp::Named("DiagCovar") = DiagCovar,
Rcpp::Named("Mon") = Mon,
Rcpp::Named("thinned") = thinned,
Rcpp::Named("VarCov") = tuning));
}
SEXP mcmcmwg(SEXP MODEL, SEXP DATA, SEXP ITERATIONS, SEXP STATUS,
SEXP THINNING, SEXP SPECS, SEXP ACCEPTANCE, SEXP DEV, SEXP DIAGCOVAR,
SEXP liv, SEXP MON, SEXP MO0, SEXP SCALEF, SEXP THINNED, SEXP TUNING) {
Function Model(MODEL);
Rcpp::List Data(DATA), Specs(SPECS), Mo0(MO0);
int Iterations = as<int>(ITERATIONS), Status = as<int>(STATUS),
Thinning = as<int>(THINNING), LIV = as<int>(liv),
ScaleF = as<int>(SCALEF);
double Acceptance = as<double>(ACCEPTANCE);
Rcpp::NumericMatrix Dev(DEV), DiagCovar(DIAGCOVAR), Mon(MON),
thinned(THINNED);
Rcpp::NumericVector tuning(TUNING);
int t_iter = 0, fins = 0, mcols = Mon.ncol();
double log_alpha = 0;
Rcpp::List Mo1 = clone(Mo0);
RNGScope scope;
for (int iter = 0; iter < Iterations; iter++) {
// Print Status
if ((iter + 1) % Status == 0) {
Rcpp::Rcout << "Iteration: " << iter + 1 <<
", Proposal: Componentwise, LP: " <<
floor(as<double>(Mo0["LP"]) * 100) / 100 << std::endl;
}
// Save Thinned Samples
if ((iter + 1) % Thinning == 0) {
t_iter = floor((iter) / Thinning) + 1;
thinned(t_iter,_) = as<Rcpp::NumericVector>(Mo0["parm"]);
Dev(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Dev"]);
Mon(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Monitor"]);
}
// Random-Scan Componentwise Estimation
Rcpp::NumericVector u = log(runif(LIV));
Rcpp::NumericVector z = rnorm(LIV);
Rcpp::IntegerVector LIVseq = Rcpp::Range(1, LIV);
Rcpp::IntegerVector s = Rcpp::RcppArmadillo::sample(LIVseq, LIV,
false, NumericVector::create());
s = s - 1;
for (int j = 0; j < LIV; j++) {
// Propose new parameter values
Rcpp::List Mo0_ = clone(Mo0);
Rcpp::NumericVector prop = Mo0_["parm"];
prop[s[j]] += z[s[j]] * tuning[s[j]];
// Log-Posterior of the proposed state
Rcpp::List Mo1 = Model(prop, Data);
fins = ::R_finite(Mo1["LP"]) + ::R_finite(Mo1["Dev"]);
for (int m = 0; m < mcols; m++) {
fins += ::R_finite(as<Rcpp::NumericVector>(Mo1["Monitor"])[m]);
}
if (fins < (mcols + 2)) Mo1 = Mo0;
// Accept/Reject
double LP0 = Mo0_["LP"];
double LP1 = Mo1["LP"];
log_alpha = LP1 - LP0;
if (u[s[j]] < log_alpha) {
Mo0 = Mo1;
Acceptance += 1.0 / LIV;
}
}
if ((iter + 1) % Thinning == 0) {
thinned(t_iter,_) = as<Rcpp::NumericVector>(Mo0["parm"]);
Dev(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Dev"]);
Mon(t_iter,_) = as<Rcpp::NumericVector>(Mo0["Monitor"]);
}
}
return wrap(Rcpp::List::create(Rcpp::Named("Acceptance") = Acceptance,
Rcpp::Named("Dev") = Dev,
Rcpp::Named("DiagCovar") = DiagCovar,
Rcpp::Named("Mon") = Mon,
Rcpp::Named("thinned") = thinned,
Rcpp::Named("VarCov") = tuning));
}
|
/**
* Created by shidawei on 16/3/14.
*/
public class UTime {
public static Date addMinute(Date date,int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, amount);
return cal.getTime();
}
public static Date addYear(Date date,int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, amount);
return cal.getTime();
}
public static Date addMonth(Date date,int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, amount);
return cal.getTime();
}
public static Date addDate(Date date,int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, amount);
return cal.getTime();
}
public static Date addHour(Date date,int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, amount);
return cal.getTime();
}
public static String getDateStr(String pattern,Date date){
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
public static Date getDateFromStr(String pattern,String dateStr)throws Exception{
if(dateStr == null){
return null;
}
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.parse(dateStr);
}
public interface Pattern{
String y_m_d = "yyyy-MM-dd";
String y_m_d_h_m_s = "yyyy-MM-dd HH:mm:ss";
}
} |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "application/impl/local_key_storage.hpp"
#include <boost/property_tree/json_parser.hpp>
#include "application/impl/config_reader/error.hpp"
#include "application/impl/config_reader/pt_util.hpp"
#include "common/hexutil.hpp"
namespace kagome::application {
outcome::result<std::shared_ptr<LocalKeyStorage>> LocalKeyStorage::create(
const std::string &keystore_path) {
auto storage = LocalKeyStorage();
OUTCOME_TRY(storage.loadFromJson(keystore_path));
return std::make_shared<LocalKeyStorage>(std::move(storage));
}
kagome::crypto::SR25519Keypair LocalKeyStorage::getLocalSr25519Keypair()
const {
return sr_25519_keypair_;
}
kagome::crypto::ED25519Keypair LocalKeyStorage::getLocalEd25519Keypair()
const {
return ed_25519_keypair_;
}
libp2p::crypto::KeyPair LocalKeyStorage::getP2PKeypair() const {
return p2p_keypair_;
}
outcome::result<void> LocalKeyStorage::loadFromJson(const std::string &file) {
namespace pt = boost::property_tree;
pt::ptree tree;
try {
pt::read_json(file, tree);
} catch (pt::json_parser_error &e) {
return ConfigReaderError::PARSER_ERROR;
}
OUTCOME_TRY(loadSR25519Keys(tree));
OUTCOME_TRY(loadED25519Keys(tree));
OUTCOME_TRY(loadP2PKeys(tree));
return outcome::success();
}
outcome::result<void> LocalKeyStorage::loadSR25519Keys(
const boost::property_tree::ptree &tree) {
OUTCOME_TRY(sr_tree, ensure(tree.get_child_optional("sr25519keypair")));
OUTCOME_TRY(sr_pubkey_str,
ensure(sr_tree.get_optional<std::string>("public")));
OUTCOME_TRY(sr_privkey_str,
ensure(sr_tree.get_optional<std::string>("private")));
// get rid of 0x from beginning
OUTCOME_TRY(sr_pubkey_buffer, common::unhexWith0x(sr_pubkey_str));
OUTCOME_TRY(sr_privkey_buffer, common::unhexWith0x(sr_privkey_str));
OUTCOME_TRY(sr_pubkey,
crypto::SR25519PublicKey::fromSpan(sr_pubkey_buffer));
OUTCOME_TRY(sr_privkey,
crypto::SR25519SecretKey::fromSpan(sr_privkey_buffer));
sr_25519_keypair_.public_key = sr_pubkey;
sr_25519_keypair_.secret_key = sr_privkey;
return outcome::success();
}
outcome::result<void> LocalKeyStorage::loadED25519Keys(
const boost::property_tree::ptree &tree) {
auto ed_tree_opt = tree.get_child_optional("ed25519keypair");
if (not ed_tree_opt) return ConfigReaderError::MISSING_ENTRY;
const auto &ed_tree = ed_tree_opt.value();
OUTCOME_TRY(ed_pubkey_str,
ensure(ed_tree.get_optional<std::string>("public")));
OUTCOME_TRY(ed_privkey_str,
ensure(ed_tree.get_optional<std::string>("private")));
// get rid of 0x from beginning
OUTCOME_TRY(ed_pubkey_buffer, common::unhexWith0x(ed_pubkey_str));
OUTCOME_TRY(ed_privkey_buffer, common::unhexWith0x(ed_privkey_str));
OUTCOME_TRY(ed_pubkey,
crypto::ED25519PublicKey::fromSpan(ed_pubkey_buffer));
OUTCOME_TRY(ed_privkey,
crypto::ED25519PrivateKey::fromSpan(ed_privkey_buffer));
ed_25519_keypair_.public_key = ed_pubkey;
ed_25519_keypair_.private_key = ed_privkey;
return outcome::success();
}
outcome::result<void> LocalKeyStorage::loadP2PKeys(
const boost::property_tree::ptree &tree) {
auto p2p_tree_opt = tree.get_child_optional("p2p_keypair");
if (not p2p_tree_opt) return ConfigReaderError::MISSING_ENTRY;
const auto &p2p_tree = p2p_tree_opt.value();
OUTCOME_TRY(p2p_type,
ensure(p2p_tree.get_optional<std::string>("p2p_type")));
using KeyType = libp2p::crypto::Key::Type;
if (p2p_type == "ed25519") {
p2p_keypair_.publicKey.type = KeyType::Ed25519;
p2p_keypair_.privateKey.type = KeyType::Ed25519;
} else if (p2p_type == "rsa") {
p2p_keypair_.publicKey.type = KeyType::RSA;
p2p_keypair_.privateKey.type = KeyType::RSA;
} else if (p2p_type == "secp256k1") {
p2p_keypair_.publicKey.type = KeyType::Secp256k1;
p2p_keypair_.privateKey.type = KeyType::Secp256k1;
} else if (p2p_type == "ecdsa") {
p2p_keypair_.publicKey.type = KeyType::ECDSA;
p2p_keypair_.privateKey.type = KeyType::ECDSA;
} else {
p2p_keypair_.publicKey.type = KeyType::UNSPECIFIED;
p2p_keypair_.privateKey.type = KeyType::UNSPECIFIED;
}
auto p2p_keypair_tree_opt = p2p_tree.get_child_optional("keypair");
if (not p2p_keypair_tree_opt) return ConfigReaderError::MISSING_ENTRY;
const auto &p2p_keypair_tree = p2p_keypair_tree_opt.value();
OUTCOME_TRY(p2p_public_key_str,
ensure(p2p_keypair_tree.get_optional<std::string>("public")));
OUTCOME_TRY(p2p_private_key_str,
ensure(p2p_keypair_tree.get_optional<std::string>("private")));
// get rid of 0x from beginning
OUTCOME_TRY(p2p_public_key, common::unhexWith0x(p2p_public_key_str));
OUTCOME_TRY(p2p_private_key, common::unhexWith0x(p2p_private_key_str));
p2p_keypair_.publicKey.data = p2p_public_key;
p2p_keypair_.privateKey.data = p2p_private_key;
return outcome::success();
}
} // namespace kagome::application
|
# coding: utf-8
# @File: model.py
# @Author: <NAME>.
# @Email: <EMAIL>
# @Time: 2020/10/10 17:12:56
# @Description:
import torch
import torch.nn as nn
from transformers import BertModel
# Bert
class BertClassifier(nn.Module):
def __init__(self, bert_config, num_labels):
super().__init__()
self.bert = BertModel(config=bert_config)
self.classifier = nn.Linear(bert_config.hidden_size, num_labels)
def forward(self, input_ids, attention_mask, token_type_ids):
bert_output = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
pooled = bert_output[1]
logits = self.classifier(pooled)
return torch.softmax(logits, dim=1)
# Bert+BiLSTM,用法与BertClassifier一样,可直接在train里面调用
class BertLstmClassifier(nn.Module):
def __init__(self, bert_config):
super().__init__()
self.bert = BertModel(config=bert_config)
self.lstm = nn.LSTM(input_size=bert_config.hidden_size, hidden_size=bert_config.hidden_size, num_layers=2, batch_first=True, bidirectional=True)
self.classifier = nn.Linear(bert_config.hidden_size*2, bert_config.num_labels) # 双向LSTM 需要乘以2
self.softmax = nn.Softmax(dim=1)
def forward(self, input_ids, attention_mask, token_type_ids):
output, pooled = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
out, _ = self.lstm(output)
logits = self.classifier(out[:, -1, :]) # 取最后时刻的输出
return self.softmax(logits)
|
/**
* creates and runs the whole game
*
* @param args arguments array
*/
public static void main(String[] args) {
Chess gm = new Chess();
Scanner scan = new Scanner(System.in);
Pattern p1 = Pattern.compile("(?:[[A-h][a-h]])(?:[1-8]) (?:[[A-h][a-h]])(?:[1-8])");
<N||R||B||Q>
Pattern p2 = Pattern.compile("(?:[[A-h][a-h]])(?:[1-8]) (?:[[A-h][a-h]])(?:[1-8]) (?:[R,N,B,Q])");
Pattern p3 = Pattern.compile("(?:[[A-h][a-h]])(?:[1-8]) (?:[[A-h][a-h]])(?:[1-8]) (?<name>draw[?])");
Pattern p4 = Pattern.compile("(?<name>draw)");
Pattern p5 = Pattern.compile("(?<name>!help)");
String input = null;
String[] arr = null;
int currCol, currRow;
int newCol, newRow;
boolean drawOffer = false;
boolean endedByDraw = false;
boolean inValidMove = false;
while (!gm.gameOver) {
if (!inValidMove) {
System.out.println();
gm.printBoard();
System.out.println();
}
gm.printPlayerTurn();
input = scan.nextLine();
input = input.trim();
if (input.equals("resign")) {
gm.gameOver = true;
if (gm.playerTurn == 0)
gm.whoWon = 1;
else
gm.whoWon = 0;
break;
}
if (p1.matcher(input).matches() && !drawOffer) {
arr = input.split(" ");
currCol = gm.getFileIndex(arr[0].charAt(0));
currRow = Character.getNumericValue(arr[0].charAt(1)) - 1;
newCol = gm.getFileIndex(arr[1].charAt(0));
newRow = Character.getNumericValue(arr[1].charAt(1)) - 1;
if (gm.handleInput(currRow, currCol, newRow, newCol, 'Q')) {
gm.nextPlayerTurn();
inValidMove = false;
} else {
inValidMove = true;
}
}
<N||R||B||Q>
else if (p2.matcher(input).matches() && !drawOffer) {
char upgrade = 0;
arr = input.split(" ");
currCol = gm.getFileIndex(arr[0].charAt(0));
currRow = Character.getNumericValue(arr[0].charAt(1)) - 1;
newCol = gm.getFileIndex(arr[1].charAt(0));
newRow = Character.getNumericValue(arr[1].charAt(1)) - 1;
upgrade = arr[2].charAt(0);
if (gm.handleInput(currRow, currCol, newRow, newCol, upgrade)) {
gm.nextPlayerTurn();
inValidMove = false;
} else {
inValidMove = true;
}
}
<draw?>
else if (p3.matcher(input).matches() && !drawOffer) {
arr = input.split(" ");
currCol = gm.getFileIndex(arr[0].charAt(0));
currRow = Character.getNumericValue(arr[0].charAt(1)) - 1;
newCol = gm.getFileIndex(arr[1].charAt(0));
newRow = Character.getNumericValue(arr[1].charAt(1)) - 1;
if (gm.handleInput(currRow, currCol, newRow, newCol, 'Q')) {
drawOffer = true;
gm.nextPlayerTurn();
inValidMove = false;
} else {
inValidMove = true;
}
}
else if (p4.matcher(input).matches() && drawOffer) {
gm.gameOver = true;
endedByDraw = true;
}
else if (p5.matcher(input).matches() && !drawOffer) {
System.out.print("List of commands:\n"
+"\tMove Pieces: row1column1 row2column2\n"
+"\tMove Pawn Pieces to Promote: row1column1 row2column2 N, Q, B, or R\n"
+"\tResign: resign\n"
+"\tAccept Draw: draw\n"
+"\tMake Move Then Offer Draw: row1column1 row2column2 draw?\n");
}
else {
inValidMove = true;
System.out.println(ILLEGALMOVEERROR);
System.out.println("Type !help to see all possible commands");
}
}
if (!endedByDraw)
gm.printWinner();
} |
// Bootstrap yargs for Deno platform:
import denoPlatformShim from './lib/platform-shims/deno.ts';
import {YargsFactory} from './build/lib/yargs-factory.js';
const Yargs = YargsFactory(denoPlatformShim);
export default Yargs;
|
// Copyright 2019 The vault713 Developers
//
// 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.
use crate::common::ErrorKind;
use crate::wallet::types::{InitTxArgs, InitTxSendArgs};
use clap::ArgMatches;
use grin_core::core::amount_from_hr_string;
use std::str::FromStr;
macro_rules! usage {
( $r:expr ) => {
return Err(ErrorKind::Usage($r.usage().to_owned()));
};
}
#[derive(Clone, Debug)]
pub enum AccountArgs<'a> {
Create(&'a str),
Switch(&'a str),
}
#[derive(Clone, Debug)]
pub enum SendCommandType<'a> {
Estimate,
File(&'a str),
Address,
}
#[derive(Clone, Debug)]
pub enum ProofArgs<'a> {
Export(u32, &'a str),
Verify(&'a str),
}
#[derive(Clone, Debug)]
pub enum ContactArgs<'a> {
Add(&'a str, &'a str),
Remove(&'a str),
}
#[derive(Clone, Debug)]
pub enum AddressArgs {
Display,
Next,
Prev,
Index(u32),
}
#[derive(Clone, Debug)]
pub enum SeedArgs {
Display,
Recover,
}
fn required<'a>(args: &'a ArgMatches, name: &str) -> Result<&'a str, ErrorKind> {
args.value_of(name)
.ok_or_else(|| ErrorKind::Argument(name.to_owned()))
}
fn parse<T>(arg: &str) -> Result<T, ErrorKind>
where
T: FromStr,
{
arg.parse::<T>()
.map_err(|_| ErrorKind::ParseNumber(arg.to_owned()))
}
pub fn account_command<'a>(args: &'a ArgMatches) -> Result<AccountArgs<'a>, ErrorKind> {
let account_args = match args.subcommand() {
("create", Some(args)) => AccountArgs::Create(required(args, "name")?),
("switch", Some(args)) => AccountArgs::Switch(required(args, "name")?),
(_, _) => {
usage!(args);
}
};
Ok(account_args)
}
pub fn send_command<'a>(
args: &'a ArgMatches,
) -> Result<(SendCommandType<'a>, InitTxArgs), ErrorKind> {
let mut init_args = InitTxArgs::default();
let amount = required(args, "amount")?;
init_args.amount =
amount_from_hr_string(amount).map_err(|_| ErrorKind::ParseNumber(amount.to_owned()))?;
if let Some(confirmations) = args.value_of("confirmations") {
init_args.minimum_confirmations = parse(confirmations)?;
}
if let Some(change_outputs) = args.value_of("change_outputs") {
init_args.num_change_outputs = parse(change_outputs)?;
}
init_args.selection_strategy_is_use_all = match args.value_of("strategy") {
Some("all") => true,
_ => false,
};
init_args.message = args.value_of("message").map(|m| m.to_owned());
if let Some(version) = args.value_of("version") {
init_args.target_slate_version = Some(parse(version)?);
}
let cmd_type = if let Some(address) = args.value_of("address") {
init_args.send_args = Some(InitTxSendArgs {
method: None,
dest: address.to_owned(),
finalize: true,
post_tx: true,
fluff: args.is_present("fluff"),
});
SendCommandType::Address
} else if let Some(file) = args.value_of("file_name") {
SendCommandType::File(file)
} else if args.is_present("estimate") {
init_args.estimate_only = Some(true);
SendCommandType::Estimate
} else {
usage!(args);
};
Ok((cmd_type, init_args))
}
pub fn finalize_command<'a>(args: &'a ArgMatches) -> Result<(&'a str, bool), ErrorKind> {
Ok((required(args, "file_name")?, args.is_present("fluff")))
}
pub fn repost_command(args: &ArgMatches) -> Result<(u32, bool), ErrorKind> {
Ok((parse(required(args, "index")?)?, args.is_present("fluff")))
}
pub fn cancel_command(args: &ArgMatches) -> Result<u32, ErrorKind> {
Ok(parse(required(args, "index")?)?)
}
pub fn repair_command(args: &ArgMatches) -> Result<bool, ErrorKind> {
Ok(args.is_present("delete_unconfirmed"))
}
pub fn listen_command<'a>(args: &'a ArgMatches) -> Result<(&'a str, bool), ErrorKind> {
Ok((
args.value_of("type").unwrap_or(""),
args.is_present("owner"),
))
}
pub fn receive_command<'a>(args: &'a ArgMatches) -> Result<(&'a str, Option<&'a str>), ErrorKind> {
Ok((required(args, "file_name")?, args.value_of("message")))
}
pub fn proof_command<'a>(args: &'a ArgMatches) -> Result<ProofArgs<'a>, ErrorKind> {
let proof_args = match args.subcommand() {
("export", Some(args)) => ProofArgs::Export(
parse(required(args, "index")?)?,
required(args, "file_name")?,
),
("verify", Some(args)) => ProofArgs::Verify(required(args, "file_name")?),
(_, _) => {
usage!(args);
}
};
Ok(proof_args)
}
pub fn contact_command<'a>(args: &'a ArgMatches) -> Result<ContactArgs<'a>, ErrorKind> {
let contact_args = match args.subcommand() {
("add", Some(args)) => {
ContactArgs::Add(required(args, "name")?, required(args, "address")?)
}
("remove", Some(args)) => ContactArgs::Remove(required(args, "name")?),
(_, _) => {
usage!(args);
}
};
Ok(contact_args)
}
pub fn address_command(args: &ArgMatches) -> Result<AddressArgs, ErrorKind> {
let address_args = if args.is_present("next") {
AddressArgs::Next
} else if args.is_present("prev") {
AddressArgs::Prev
} else if let Some(index) = args.value_of("index") {
AddressArgs::Index(parse(index)?)
} else {
AddressArgs::Display
};
Ok(address_args)
}
pub fn seed_command(args: &ArgMatches) -> Result<SeedArgs, ErrorKind> {
let seed_args = match args.subcommand() {
("display", _) => SeedArgs::Display,
("recover", _) => SeedArgs::Recover,
(_, _) => {
usage!(args);
}
};
Ok(seed_args)
}
|
#include<bits/stdc++.h>
#define ll long long
#define N 100007
using namespace std;
ll dp[N];
// Keeps upper hull for maximums.
// add lines with -m and -b and return -ans to
// make this code working for minimums.
typedef long double ld;
const ld inf = 1e18;
struct chtDynamic {
struct line {
ll m, b; ld x;
ll val; bool isQuery;
line(ll _m = 0, ll _b = 0) :
m(_m), b(_b), val(0), x(-inf), isQuery(false) {}
ll eval(ll x) const { return m * x + b; }
bool parallel(const line &l) const { return m == l.m; }
ld intersect(const line &l) const {
return parallel(l) ? inf : 1.0 * (l.b - b) / (m - l.m);
}
bool operator < (const line &l) const {
if(l.isQuery) return x < l.val;
else return m < l.m;
}
};
set<line> hull;
typedef set<line> :: iterator iter;
bool cPrev(iter it) { return it != hull.begin(); }
bool cNext(iter it) { return it != hull.end() && next(it) != hull.end(); }
bool bad(const line &l1, const line &l2, const line &l3) {
return l1.intersect(l3) <= l1.intersect(l2);
}
bool bad(iter it) {
return cPrev(it) && cNext(it) && bad(*prev(it), *it, *next(it));
}
iter update(iter it) {
if(!cPrev(it)) return it;
ld x = it -> intersect(*prev(it));
line tmp(*it); tmp.x = x;
it = hull.erase(it);
return hull.insert(it, tmp);
}
void addLine(ll m, ll b) {
line l(m, b);
iter it = hull.lower_bound(l);
if(it != hull.end() && l.parallel(*it)) {
if(it -> b < b) it = hull.erase(it);
else return;
}
it = hull.insert(it, l);
if(bad(it)) return (void) hull.erase(it);
while(cPrev(it) && bad(prev(it))) hull.erase(prev(it));
while(cNext(it) && bad(next(it))) hull.erase(next(it));
it = update(it);
if(cPrev(it)) update(prev(it));
if(cNext(it)) update(next(it));
}
ll query(ll x) const {
if(hull.empty()) return -inf;
line q; q.val = x, q.isQuery = 1;
iter it = --hull.lower_bound(q);
return it -> eval(x);
}
} ds;
// Short code and faster
// Keeps upper hull for maximums.
// add lines with -m and -b and return -ans to
// make this code working for minimums.
// source: http://codeforces.com/blog/entry/11155?#comment-162462
const ll is_query = -(1LL<<62);
struct Line {
ll m, b;
mutable function<const Line*()> succ;
bool operator<(const Line& rhs) const {
if (rhs.b != is_query) return m < rhs.m;
const Line* s = succ();
if (!s) return 0;
ll x = rhs.m;
return b - s->b < (s->m - m) * x;
}
};
struct HullDynamic : public multiset<Line> {
bool bad(iterator y) {
auto z = next(y);
if (y == begin()) {
if (z == end()) return 0;
return y->m == z->m && y->b <= z->b;
}
auto x = prev(y);
if (z == end()) return y->m == x->m && y->b <= x->b;
return 1.0 * (x->b - y->b)*(z->m - y->m) >= 1.0 * (y->b - z->b)*(y->m - x->m);
}
void insert_line(ll m, ll b) {
auto y = insert({ m, b });
y->succ = [=] { return next(y) == end() ? 0 : &*next(y); };
if (bad(y)) { erase(y); return; }
while (next(y) != end() && bad(next(y))) erase(next(y));
while (y != begin() && bad(prev(y))) erase(prev(y));
}
ll eval(ll x) {
auto l = *lower_bound((Line) { x, is_query });
return l.m * x + l.b;
}
};
ll arr[N], brr[N];
int main()
{
int i,j,k,l,m,n;
scanf("%d",&n);
for(i=0; i<n; i++)
scanf("%lld",&arr[i]);
for(i=0; i<n; i++)
scanf("%lld",&brr[i]);
ll ans= 0;
HullDynamic hull;
dp[0]= 0;
hull.insert_line(-brr[0],0);
for(int i=1; i<n; i++)
{
dp[i]= hull.eval(arr[i]);
hull.insert_line( -brr[i], dp[i] );
}
printf("%lld\n", -dp[n-1]);
return 0;
}
|
<reponame>mcb64/pmgr<filename>pmgr/pmgr_ui.py<gh_stars>0
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pmgr.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(990, 608)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setMinimumSize(QtCore.QSize(0, 0))
self.centralwidget.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.saveButton = QtWidgets.QPushButton(self.centralwidget)
self.saveButton.setObjectName("saveButton")
self.gridLayout.addWidget(self.saveButton, 0, 0, 1, 1)
self.treeWidget = QtWidgets.QTreeWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.treeWidget.sizePolicy().hasHeightForWidth())
self.treeWidget.setSizePolicy(sizePolicy)
self.treeWidget.setMinimumSize(QtCore.QSize(100, 0))
self.treeWidget.setObjectName("treeWidget")
self.treeWidget.headerItem().setText(0, "1")
self.treeWidget.header().setVisible(False)
self.treeWidget.header().setStretchLastSection(True)
self.gridLayout.addWidget(self.treeWidget, 1, 0, 1, 6)
self.revertButton = QtWidgets.QPushButton(self.centralwidget)
self.revertButton.setObjectName("revertButton")
self.gridLayout.addWidget(self.revertButton, 0, 1, 1, 1)
self.applyButton = QtWidgets.QPushButton(self.centralwidget)
self.applyButton.setObjectName("applyButton")
self.gridLayout.addWidget(self.applyButton, 0, 2, 1, 1)
self.debugButton = QtWidgets.QPushButton(self.centralwidget)
self.debugButton.setObjectName("debugButton")
self.gridLayout.addWidget(self.debugButton, 0, 3, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 990, 20))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuView = QtWidgets.QMenu(self.menubar)
self.menuView.setObjectName("menuView")
self.menuFilter = QtWidgets.QMenu(self.menubar)
self.menuFilter.setObjectName("menuFilter")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.objectWidget = QtWidgets.QDockWidget(MainWindow)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(6)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.objectWidget.sizePolicy().hasHeightForWidth())
self.objectWidget.setSizePolicy(sizePolicy)
self.objectWidget.setMinimumSize(QtCore.QSize(600, 100))
self.objectWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea|QtCore.Qt.RightDockWidgetArea)
self.objectWidget.setObjectName("objectWidget")
self.objectTable = FreezeTableView()
self.objectTable.setObjectName("objectTable")
self.objectWidget.setWidget(self.objectTable)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.objectWidget)
self.configWidget = QtWidgets.QDockWidget(MainWindow)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(6)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.configWidget.sizePolicy().hasHeightForWidth())
self.configWidget.setSizePolicy(sizePolicy)
self.configWidget.setMinimumSize(QtCore.QSize(600, 100))
self.configWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea|QtCore.Qt.RightDockWidgetArea)
self.configWidget.setObjectName("configWidget")
self.configTable = FreezeTableView()
self.configTable.setObjectName("configTable")
self.userLabel = QtWidgets.QLabel(self.configTable)
self.userLabel.setGeometry(QtCore.QRect(60, 220, 121, 16))
self.userLabel.setObjectName("userLabel")
self.configWidget.setWidget(self.configTable)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.configWidget)
self.actionObjects = QtWidgets.QAction(MainWindow)
self.actionObjects.setObjectName("actionObjects")
self.actionConfigurations = QtWidgets.QAction(MainWindow)
self.actionConfigurations.setObjectName("actionConfigurations")
self.actionManual = QtWidgets.QAction(MainWindow)
self.actionManual.setCheckable(True)
self.actionManual.setChecked(True)
self.actionManual.setObjectName("actionManual")
self.actionProtected = QtWidgets.QAction(MainWindow)
self.actionProtected.setCheckable(True)
self.actionProtected.setChecked(False)
self.actionProtected.setObjectName("actionProtected")
self.actionTrack = QtWidgets.QAction(MainWindow)
self.actionTrack.setCheckable(True)
self.actionTrack.setObjectName("actionTrack")
self.actionExit = QtWidgets.QAction(MainWindow)
self.actionExit.setObjectName("actionExit")
self.actionAuth = QtWidgets.QAction(MainWindow)
self.actionAuth.setObjectName("actionAuth")
self.menuFile.addAction(self.actionAuth)
self.menuFile.addAction(self.actionExit)
self.menuFilter.addAction(self.actionManual)
self.menuFilter.addAction(self.actionProtected)
self.menuFilter.addAction(self.actionTrack)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuView.menuAction())
self.menubar.addAction(self.menuFilter.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.saveButton.setText(_translate("MainWindow", "Save"))
self.treeWidget.setToolTip(_translate("MainWindow", "Click to select a configuration to display in the Configurations window. \n"
"All ancestors and all children of the selected configuration will be displayed."))
self.revertButton.setText(_translate("MainWindow", "Revert"))
self.applyButton.setText(_translate("MainWindow", "Apply"))
self.debugButton.setText(_translate("MainWindow", "Debug"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuView.setTitle(_translate("MainWindow", "View"))
self.menuFilter.setTitle(_translate("MainWindow", "Filter"))
self.objectWidget.setToolTip(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Sans Serif\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<table border=\"0\" style=\"-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;\">\n"
"<tr>\n"
"<td style=\"border: none;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Black = Value matches configuration.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" color:#0000ff;\">Blue</span> = Value differs from configuration (actual shown).</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" color:#ff0000;\">Red</span> = Unsaved configuration change (new value shown).</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" background-color:#a0a0a0;\">Gray BG</span> = Unconnected</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" background-color:#e0e0e0;\">Lt Gray BG</span> = Configuration value (not editable!)</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" background-color:#ffebcd;\">Almond BG</span> = Derived value</p></td></tr></table></body></html>"))
self.objectWidget.setWindowTitle(_translate("MainWindow", "Objects"))
self.configWidget.setToolTip(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Sans Serif\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<table border=\"0\" style=\"-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;\">\n"
"<tr>\n"
"<td style=\"border: none;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Black = Value is set in configuration.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" color:#ff0000;\">Red</span> = Value is unsaved change.</p></td></tr></table></body></html>"))
self.configWidget.setWindowTitle(_translate("MainWindow", "Configurations"))
self.userLabel.setText(_translate("MainWindow", "User: Guest"))
self.actionObjects.setText(_translate("MainWindow", "Objects"))
self.actionConfigurations.setText(_translate("MainWindow", "Configurations"))
self.actionManual.setText(_translate("MainWindow", "Show Manual"))
self.actionProtected.setText(_translate("MainWindow", "Show Protected"))
self.actionTrack.setText(_translate("MainWindow", "Track Object Config"))
self.actionExit.setText(_translate("MainWindow", "Exit"))
self.actionAuth.setText(_translate("MainWindow", "Authenticate"))
from pmgr.FreezeTableView import FreezeTableView
|
Realistic event rates for detection of supermassive black hole coalescence by LISA
The gravitational waves generated during supermassive black hole (SMBH) coalescence are prime candidates for detection by the satellite LISA. We use the extended Press-Schechter formalism combined with empirically motivated estimates for the SMBH-dark matter halo mass relation and SMBH occupation fraction to estimate the maximum coalescence rate for major SMBH mergers. Assuming efficient binary coalescence, and guided by the lowest nuclear black hole mass inferred in local galactic bulges and nearby low-luminosity active galactic nuclei (10 5 M ○. ), we predict approximately 15 detections per year at a signal-to-noise ratio greater than 5, in each of the inspiral and ringdown phases. Rare coalescences between SMBHs having masses in excess of 10 7 M ○. will be more readily detected via gravitational waves from the ringdown phase. |
def ncon_to_weighted_adj(dims: List[Tuple], labels: List[List[int]]):
N = len(labels)
ranks = [len(labels[i]) for i in range(N)]
flat_labels = np.hstack([labels[i] for i in range(N)])
tensor_counter = np.hstack(
[i * np.ones(ranks[i], dtype=int) for i in range(N)])
index_counter = np.hstack([np.arange(ranks[i]) for i in range(N)])
log_adj = np.zeros([N, N])
unique_labels = np.unique(flat_labels)
for ele in unique_labels:
tnr = tensor_counter[flat_labels == ele]
ind = index_counter[flat_labels == ele]
if len(ind) == 1:
log_adj[tnr[0], tnr[0]] += np.log10(dims[tnr[0]][ind[0]])
elif len(ind) == 2:
if tnr[0] != tnr[1]:
log_adj[tnr[0], tnr[1]] += np.log10(dims[tnr[0]][ind[0]])
log_adj[tnr[1], tnr[0]] += np.log10(dims[tnr[0]][ind[0]])
return log_adj |
// HasValue returns true if the value already exists in any List.
func (l *Lists[K, V, O]) HasValue(value V) (bool, error) {
v, err := l.definition.valueEncoding.Encode(value)
if err != nil {
return false, fmt.Errorf("encode value: %w", err)
}
valuesBucket, err := l.valuesBucket(false)
if err != nil {
return false, fmt.Errorf("values bucket: %w", err)
}
if valuesBucket == nil {
return false, nil
}
if valuesBucket.Bucket(v) == nil {
return false, nil
}
f, _ := valuesBucket.Bucket(v).Cursor().First()
return f != nil, nil
} |
import torch
import torch.nn as nn
import torch.nn.functional as F
from net.ResNet import resnet50
from math import log
from net.Res2Net import res2net50_v1b_26w_4s
class ConvBNR(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False):
super(ConvBNR, self).__init__()
self.block = nn.Sequential(
nn.Conv2d(inplanes, planes, kernel_size, stride=stride, padding=dilation, dilation=dilation, bias=bias),
nn.BatchNorm2d(planes),
nn.ReLU(inplace=True)
)
def forward(self, x):
return self.block(x)
class Conv1x1(nn.Module):
def __init__(self, inplanes, planes):
super(Conv1x1, self).__init__()
self.conv = nn.Conv2d(inplanes, planes, 1)
self.bn = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
class EAM(nn.Module):
def __init__(self):
super(EAM, self).__init__()
self.reduce1 = Conv1x1(256, 64)
self.reduce4 = Conv1x1(2048, 256)
self.block = nn.Sequential(
ConvBNR(256 + 64, 256, 3),
ConvBNR(256, 256, 3),
nn.Conv2d(256, 1, 1))
def forward(self, x4, x1):
size = x1.size()[2:]
x1 = self.reduce1(x1)
x4 = self.reduce4(x4)
x4 = F.interpolate(x4, size, mode='bilinear', align_corners=False)
out = torch.cat((x4, x1), dim=1)
out = self.block(out)
return out
class EFM(nn.Module):
def __init__(self, channel):
super(EFM, self).__init__()
t = int(abs((log(channel, 2) + 1) / 2))
k = t if t % 2 else t + 1
self.conv2d = ConvBNR(channel, channel, 3)
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv1d = nn.Conv1d(1, 1, kernel_size=k, padding=(k - 1) // 2, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, c, att):
if c.size() != att.size():
att = F.interpolate(att, c.size()[2:], mode='bilinear', align_corners=False)
x = c * att + c
x = self.conv2d(x)
wei = self.avg_pool(x)
wei = self.conv1d(wei.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1)
wei = self.sigmoid(wei)
x = x * wei
return x
class CAM(nn.Module):
def __init__(self, hchannel, channel):
super(CAM, self).__init__()
self.conv1_1 = Conv1x1(hchannel + channel, channel)
self.conv3_1 = ConvBNR(channel // 4, channel // 4, 3)
self.dconv5_1 = ConvBNR(channel // 4, channel // 4, 3, dilation=2)
self.dconv7_1 = ConvBNR(channel // 4, channel // 4, 3, dilation=3)
self.dconv9_1 = ConvBNR(channel // 4, channel // 4, 3, dilation=4)
self.conv1_2 = Conv1x1(channel, channel)
self.conv3_3 = ConvBNR(channel, channel, 3)
def forward(self, lf, hf):
if lf.size()[2:] != hf.size()[2:]:
hf = F.interpolate(hf, size=lf.size()[2:], mode='bilinear', align_corners=False)
x = torch.cat((lf, hf), dim=1)
x = self.conv1_1(x)
xc = torch.chunk(x, 4, dim=1)
x0 = self.conv3_1(xc[0] + xc[1])
x1 = self.dconv5_1(xc[1] + x0 + xc[2])
x2 = self.dconv7_1(xc[2] + x1 + xc[3])
x3 = self.dconv9_1(xc[3] + x2)
xx = self.conv1_2(torch.cat((x0, x1, x2, x3), dim=1))
x = self.conv3_3(x + xx)
return x
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.resnet = res2net50_v1b_26w_4s(pretrained=True)
# if self.training:
# self.initialize_weights()
self.eam = EAM()
self.efm1 = EFM(256)
self.efm2 = EFM(512)
self.efm3 = EFM(1024)
self.efm4 = EFM(2048)
self.reduce1 = Conv1x1(256, 64)
self.reduce2 = Conv1x1(512, 128)
self.reduce3 = Conv1x1(1024, 256)
self.reduce4 = Conv1x1(2048, 256)
self.cam1 = CAM(128, 64)
self.cam2 = CAM(256, 128)
self.cam3 = CAM(256, 256)
self.predictor1 = nn.Conv2d(64, 1, 1)
self.predictor2 = nn.Conv2d(128, 1, 1)
self.predictor3 = nn.Conv2d(256, 1, 1)
# def initialize_weights(self):
# model_state = torch.load('./models/resnet50-19c8e357.pth')
# self.resnet.load_state_dict(model_state, strict=False)
def forward(self, x):
x1, x2, x3, x4 = self.resnet(x)
edge = self.eam(x4, x1)
edge_att = torch.sigmoid(edge)
x1a = self.efm1(x1, edge_att)
x2a = self.efm2(x2, edge_att)
x3a = self.efm3(x3, edge_att)
x4a = self.efm4(x4, edge_att)
x1r = self.reduce1(x1a)
x2r = self.reduce2(x2a)
x3r = self.reduce3(x3a)
x4r = self.reduce4(x4a)
x34 = self.cam3(x3r, x4r)
x234 = self.cam2(x2r, x34)
x1234 = self.cam1(x1r, x234)
o3 = self.predictor3(x34)
o3 = F.interpolate(o3, scale_factor=16, mode='bilinear', align_corners=False)
o2 = self.predictor2(x234)
o2 = F.interpolate(o2, scale_factor=8, mode='bilinear', align_corners=False)
o1 = self.predictor1(x1234)
o1 = F.interpolate(o1, scale_factor=4, mode='bilinear', align_corners=False)
oe = F.interpolate(edge_att, scale_factor=4, mode='bilinear', align_corners=False)
return o3, o2, o1, oe |
<filename>src/endpoints/snip.ts
import { client } from '../client'
import { snip } from '../types/snip'
/**
* Represents the collection of fields that can be passed when creating a new snip.
* @see https://snip.hxrsh.in/api-docs.md
*/
type SnipCreateFields = Partial<
Pick<snip, 'slug' | 'content' | 'password' | 'language' | 'author'>
>
/**
* Represents the collection of fields that can be modified when editing an existing snip.
* @see https://snip.hxrsh.in/api-docs.md
*/
type SnipEditFields = Partial<Pick<snip, 'slug' | 'content' | 'password'>>
/**
* Represents an endpoint for managing pastes.
*
* @see https://snip.hxrsh.in/api-docs.md
*/
export class Snip {
/**
* Fetches a snip by its ID.
*
* @remarks
* You cannot fetch snips a password
*
* @see https://snip.hxrsh.in/api-docs.md
*
* @param id The ID of the snip to fetch.
* @returns The fetched snip or undefined if no snip was found.
*/
async getSnip(id: string): Promise<snip | undefined> {
return client.get<snip>(`/snip/${id}`)
}
/**
* Creates a new snip using the specified fields.
*
* @remarks
* Note that if you want the snip to be tied to your account, or want it
* to be private, or want to use tags you need to authorize the request
* using your personal API token.
*
* @see https://snip.hxrsh.in/api-docs.md
*
* @param data The data to use to create the snip.
* @returns The created snip or undefined if something went wrong.
*/
async createSnip(data: SnipCreateFields): Promise<snip | undefined> {
return client.post<snip>('/snip/new', data)
}
/**
* Applies a set of changes to an existing snip.
*
* @remarks
* Note that you can only edit snip tied to your own account. To ensure this,
* you need to authorize the request using your personal API token.
*
* @see https://snip.hxrsh.in/api-docs.md
*
* @param id The ID of the snip to edit.
* @param data The data to modify in the snip.
* @returns The modified snip or undefined if the paste was not found or something went wrong.
*/
async editSnip(id: string, data: SnipEditFields): Promise<snip | undefined> {
return client.patch<snip>(`/snip/${id}/edit`, data)
}
/**
* Deletes the paste with the specified ID.
*
* @remarks
* Note that you can only delete snips tied to your account. To ensure this,
* you need to authorize the request using your personal API token. Additionally,
* note that this action is irreversible.
*
* @param id The ID of the snip to delete.
* @returns Whether or not the snip was successfully deleted.
*/
async deleteSnip(id: string): Promise<boolean> {
return client.del(`/snip${id}/delete`)
}
}
|
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/* Before Node.js v11 the crypto module did not support
* a method to PEM format a ECDH key. It has always supported
* producing such keys: `crypto.createECDH`. But formatting
* these keys as a PEM for use in `crypto.Sign` and
* `crypto.Verify` has not been possible in native `crypto`.
* As Node.js v6, v8, and v10 reach end of life, this code
* can be deleted.
*/
// @ts-ignore
import asn from 'asn1.js'
const Rfc5915Key = asn.define('Rfc5915Key', function (this: any) {
this.seq().obj(
this.key('version').int(),
this.key('privateKey').octstr(),
this.key('parameters').optional().explicit(0).objid({
'1 2 840 10045 3 1 7': 'prime256v1',
'1 3 132 0 34': 'secp384r1',
}),
this.key('publicKey').optional().explicit(1).bitstr()
)
})
const SpkiKey = asn.define('SpkiKey', function (this: any) {
this.seq().obj(
this.key('algorithmIdentifier')
.seq()
.obj(
this.key('publicKeyType').objid({
'1 2 840 10045 2 1': 'EC',
}),
this.key('parameters').objid({
'1 2 840 10045 3 1 7': 'prime256v1',
'1 3 132 0 34': 'secp384r1',
})
),
this.key('publicKey').bitstr()
)
})
export function publicKeyPem(curve: string, publicKey: Buffer) {
const buff: Buffer = SpkiKey.encode(
{
algorithmIdentifier: {
publicKeyType: 'EC',
parameters: curve,
},
publicKey: { data: publicKey },
},
'der'
)
return [
'-----BEGIN PUBLIC KEY-----',
...chunk64(buff),
'-----END PUBLIC KEY-----',
'',
].join('\n')
}
export function privateKeyPem(
curve: string,
privateKey: Buffer,
publicKey: Buffer
) {
const buff: Buffer = Rfc5915Key.encode(
{
version: 1,
privateKey: privateKey,
parameters: curve,
publicKey: { data: publicKey },
},
'der'
)
return [
'-----BEGIN EC PRIVATE KEY-----',
...chunk64(buff),
'-----END EC PRIVATE KEY-----',
'',
].join('\n')
}
export function chunk64(buff: Buffer) {
const chunkSize = 64
const str = buff.toString('base64')
const numChunks = Math.ceil(str.length / chunkSize)
const chunks: string[] = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += chunkSize) {
chunks[i] = str.substr(o, chunkSize)
}
return chunks
}
|
//*****************************************************************************
//
//! Set the global SNEP Packet Pointer and Length
//!
//! \param pui8PacketPtr is the pointer to the first payload to be transmitted.
//! \param ui32PacketLength is the length of the total packet.
//!
//! This function must be called by the main application to initialize the
//! packet to be sent to the SNEP server.
//!
//! \return This function returns \b STATUS_SUCCESS (1) if the packet was
//! queued, else it returns \b STATUS_FAIL (0).
//
//*****************************************************************************
tStatus SNEP_setupPacket(uint8_t * pui8PacketPtr, uint32_t ui32PacketLength)
{
tStatus ePacketSetupStatus;
if(g_eSNEPConnectionStatus == SNEP_CONNECTION_IDLE )
{
g_pui8SNEPTxPacketPtr = pui8PacketPtr;
g_ui32TxIndex = 0;
g_ui32SNEPPacketLength = ui32PacketLength;
g_eSNEPConnectionStatus = SNEP_CONNECTION_IDLE;
ePacketSetupStatus = STATUS_SUCCESS;
}
else
ePacketSetupStatus = STATUS_FAIL;
return ePacketSetupStatus;
} |
/**
* extends the hadoop JobControl to remove the hardcoded sleep(5000)
* as most of this is private we have to use reflection
*
* See {@link https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.20/src/mapred/org/apache/hadoop/mapred/jobcontrol/JobControl.java}
*
*/
public class PigJobControl extends JobControl {
private static final Log log = LogFactory.getLog(PigJobControl.class);
private static Field runnerState;
private static Method checkRunningJobs;
private static Method checkWaitingJobs;
private static Method startReadyJobs;
private static boolean initSuccesful;
static {
try {
runnerState = JobControl.class.getDeclaredField("runnerState");
runnerState.setAccessible(true);
checkRunningJobs = JobControl.class.getDeclaredMethod("checkRunningJobs");
checkRunningJobs.setAccessible(true);
checkWaitingJobs = JobControl.class.getDeclaredMethod("checkWaitingJobs");
checkWaitingJobs.setAccessible(true);
startReadyJobs = JobControl.class.getDeclaredMethod("startReadyJobs");
startReadyJobs.setAccessible(true);
initSuccesful = true;
} catch (Exception e) {
log.warn("falling back to default JobControl (not using hadoop 0.20 ?)", e);
initSuccesful = false;
}
}
// The thread can be in one of the following state
private static final int RUNNING = 0;
private static final int SUSPENDED = 1;
private static final int STOPPED = 2;
private static final int STOPPING = 3;
private static final int READY = 4;
private int timeToSleep;
/**
* Construct a job control for a group of jobs.
* @param groupName a name identifying this group
* @param pigContext
* @param conf
*/
public PigJobControl(String groupName, int timeToSleep) {
super(groupName);
this.timeToSleep = timeToSleep;
}
public int getTimeToSleep() {
return timeToSleep;
}
public void setTimeToSleep(int timeToSleep) {
this.timeToSleep = timeToSleep;
}
private void setRunnerState(int state) {
try {
runnerState.set(this, state);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private int getRunnerState() {
try {
return (Integer)runnerState.get(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* The main loop for the thread.
* The loop does the following:
* Check the states of the running jobs
* Update the states of waiting jobs
* Submit the jobs in ready state
*/
public void run() {
if (!initSuccesful) {
super.run();
return;
}
setRunnerState(PigJobControl.RUNNING);
while (true) {
while (getRunnerState() == PigJobControl.SUSPENDED) {
try {
Thread.sleep(timeToSleep);
}
catch (Exception e) {
}
}
mainLoopAction();
if (getRunnerState() != PigJobControl.RUNNING &&
getRunnerState() != PigJobControl.SUSPENDED) {
break;
}
try {
Thread.sleep(timeToSleep);
}
catch (Exception e) {
}
if (getRunnerState() != PigJobControl.RUNNING &&
getRunnerState() != PigJobControl.SUSPENDED) {
break;
}
}
setRunnerState(PigJobControl.STOPPED);
}
private void mainLoopAction() {
try {
checkRunningJobs.invoke(this);
checkWaitingJobs.invoke(this);
startReadyJobs.invoke(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} |
/**
* Loads the dag, queryId.plan, from disk.
* @param queryId
* @return the dag corresponding to queryId
* @throws IOException
*/
@Override
public AvroDag load(final String queryId) throws IOException {
final File storedFile = getAvroOperatorChainDagFile(queryId);
return loadFromFile(storedFile);
} |
Tikkun Magazine, March/April 2009
The Cynical Psychology of Capitalism
by Allen D. Kanner
Two years ago, three psychologists and an economist published a long journal article on the dubious psychology that underlies American corporate capitalism. The original title of the piece began with the phrase, "A Taboo Topic," but the authors (myself among them) were warned by a sympathetic editor to be as unprovocative as possible to avoid being instantly written off as leftist ideologues. We deleted the phrase, thus assuring that the taboo against criticizing capitalism remained alive and well.
It's time for us all to confront this taboo. Capitalism rests on several key ideas regarding human motivation and development that fly in the face of much of Western psychology. Here I will focus on two of these: that people are primarily self-interested and that the acquisition of material wealth is the key to happiness. If these "insights" prove false or seriously incomplete, then capitalism unravels at the seams.
Are people fundamentally self-interested? Most theories of human development describe a progression of life stages that begins with an infant's preoccupation with self and then expands that awareness outward, first to family and friends, and then to community, society, and future generations. Although self-interest does not disappear, our sympathies become "more tender and more widely diffused, until they are extended to all sentient beings," observed Charles Darwin in The Origin of Species. Many individuals do not reach the latter stages of human development, but the most mature, wise, and fulfilled among us do. In contrast, becoming stuck or fixated at a particular stage leads to unhappiness and psychological problems.
Similarly, many forms of psychopathology are characterized by a preoccupation with the self and an inability to value the needs and wishes of others. This is evident, for example, in narcissism, sociopathy, and most other personality disorders. Psychological health, in contrast, includes a well-developed sense of empathy and the capacity to put other people's needs above one's own, while still caring for oneself. For most clinical approaches, movement in the direction of greater empathy and compassion, combined with a hefty dose of self-love, is a sign of significant progress.
When we apply this general perspective to capitalism's insistence that people are fundamentally selfish, the economic system comes out looking fatalistic, if not downright cynical. It assigns humanity to a low and easily attained level of moral, social, and emotional development and offers scant hope of collective improvement. Proponents of free enterprise argue that it is futile to attempt to alter our self-serving nature. Rather, the marketplace should organize itself based on the premise that everyone is out for her- or himself.
This brings us to the second key assumption we challenged in our article. The free market has as its primary goal the ongoing accumulation of wealth, which is supposed to provide the best opportunity available for attaining happiness. Yet there now exists a large body of cross-cultural research that shows that after people's survival needs are met—housing, food, clothing, and the like—the relationship between wealth and happiness is negligible. In fact, aspiring to be rich can be harmful. Cross-cultural studies also indicate that the adoption of materialistic values is associated with depression, anxiety, substance abuse, poor social skills, low self-esteem, psychosomatic symptoms (headaches, sore throats, etc.), and diminished life satisfaction. Materialistic values are also related to anti-social behaviors such as cheating and petty theft, racism, and environmental abuse. Materialistic individuals are less empathic and have shorter, more conflictual relationships with friends and lovers than their less materialistic peers. This is not good.
These developmental, clinical, and research-based insights might give us pause as to the psychological wisdom that underlies our nation's economic system. But even if we allow that there may be some validity to capitalism's model of the human psyche as selfish and materialistic, we still have to contend with its cynicism, which is built into the system.
The laws and regulations that form the structure of capitalism mandate selfish and materialistic behavior. For example, by law corporate CEOs have to put profit above all else, including the social good. The corporate culture that emerges from such a structure regards greedy behavior as heroic and compassion as foolish. It aggressively opposes the moral, social, and emotional development necessary to move beyond radical self-interest.
In contrast, other American institutions have been more optimistic about the human condition. Consider the legal principle that all citizens are equal under the law. Of course, it is the rare individual who is without prejudice or bias. But the justice system is not organized on the assumption that people are fundamentally prejudiced and incapable of collective change. Rather, it is structured around the democratic ideal of equality. This is a "practical" ideal in that people are capable of becoming more egalitarian. The system is designed, therefore, to encourage human development.
Historically, Americans have called on many of their institutions to promote individual and social advancement. It is exactly this kind of practical idealism that we need at the foundation of our economic institutions.
Allen D. Kanner, Ph.D., is a co-founder of the Campaign for a Commercial-Free Childhood (www.commercialfreechildhood.org). The article discussed above is T. Kasser et al., "Some Costs of American Corporate Capitalism: A Psychological Exploration of Value and Goal Conflicts," Psychological Inquiry 18, no. 1 (2007): 1-22.
Source Citation
Kanner, Allen D. 2009. The Cynical Psychology of Capitalism. Tikkun 24(2): 45. |
Heme Cofactor‐Resembling Fe–N Single Site Embedded Graphene as Nanozymes to Selectively Detect H2O2 with High Sensitivity
Over the past decade, the catalytic activity of nanozymes has been greatly enhanced, but their selectivity is still low and considered a critical issue to overcome. Herein, Fe–N4 single site embedded graphene (Fe–N‐rGO), which resembles the heme cofactor present in natural horseradish peroxidase, shows a marked enhancement in peroxidase‐like catalytic efficiency of up to ≈700‐fold higher than that of undoped rGO as well as excellent selectivity toward target H2O2 without any oxidizing activity. Importantly, when Fe or N is doped alone or when Fe is replaced with another transition metal in the Fe–N4 site, the activity is negligibly enhanced, showing that mimicking the essential cofactor structure of natural enzyme might be essential to design the catalytic features of nanozymes. Density functional theory results for the change in Gibbs free energy during the peroxide decomposition reaction explain the high catalytic activity of Fe–N‐rGO. Based on the high and selective peroxidase‐like activity of Fe–N‐rGO, trace amounts of H2O2 produced from the enzymatic reactions from acetylcholine and cancerous cells are successfully quantified with high sensitivity and selectivity. This work is expected to encourage studies on the rational design of nanozymes pursuing the active site structure of natural enzymes. |
#include <bits/stdc++.h>
using namespace std;
#define st first
#define nd second
#define pb push_back
#define int long long int
#define endl '\n'
#define MOD (int)(1e9 + 7)
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define mid start+(end-start)/2
#define debug(x) cerr << #x << " = " << x << endl
#define binary(x) cerr << #x << " = " << bitset<8>(x) << endl
#define N (int)(2e5)+5
int n, a, t;
int dp[2][N];
int cycle[2][N];
int v[N];
int vis[2][N];
int i;
int rec(bool ek, int wai){
if((wai <= 0) || (wai > n)) return 0;
if(~dp[ek][wai]) return dp[ek][wai];
return dp[ek][wai] = (rec((!ek), wai+((ek)?(v[wai]):(-1*v[wai])))+v[wai]);
}
int cycler(bool ek, int wai){
if((wai <= 0) || (wai > n)) return 0;
if(~cycle[ek][wai]) return cycle[ek][wai];
if(vis[ek][wai] == 1) return 1;
vis[ek][wai] = 1;
if((wai == 1) && ek) return cycle[ek][wai] = 1;
if(wai == 1) return 0;
return cycle[ek][wai] = cycler(!ek, wai+((ek)?(v[wai]):(-1*v[wai])));
}
int32_t main(){
ios_base::sync_with_stdio(false);cin.tie(0); cout.tie(0);
cin >> n;
memset(dp, -1, sizeof dp);
memset(cycle, -1, sizeof cycle);
for(i = 2; i <= n; i++) cin >> v[i];
for(i = 1; i < n; i++){
if(cycler(0, i+1)){
cout << -1 << endl;
continue;
}
cout << rec(0, i+1)+i << endl;
}
} |
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { ShoeService } from 'app/services/shoe.service';
import { ToastComponent } from 'app/shared/toast/toast.component';
import { CompanyService } from 'app/services/company.service';
import { debug } from 'util';
import { ClassificationService } from 'app/services/classification.service';
import { OnDestroy } from '@angular/core/src/metadata/lifecycle_hooks';
import { ActivatedRoute } from '@angular/router';
import {Location} from '@angular/common';
@Component({
selector: 'app-shoe-edit',
templateUrl: './shoeEdit.component.html',
styleUrls: ['./shoeEdit.component.scss']
})
export class ShoeEditComponent implements OnInit, OnDestroy {
currentShoe: any = {};
friendlyId: string;
companies = [];
classifications = [];
sizes = [];
shoes = [];
genders = [
{name: 'ילדות', mark: false},
{name: 'ילדים', mark: false},
{name: 'נשים', mark: false},
{name: 'גברים', mark: false}];
isEditing = false;
currentImageGroup: any = {};
sub; sub1; sub2; sub3; sub4; sub5; sub6; sub7;
isLoading = false;
constructor(private shoeService: ShoeService,
private companyService: CompanyService,
private formBuilder: FormBuilder,
private ClassificationService: ClassificationService,
private http: Http,
public toast: ToastComponent,
public route: ActivatedRoute,
private _location: Location) {
this.sizes = new Array(31).fill(0).map((x, i) => i + 19);
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
if (params['id']) {
this.sub1 = this.shoeService.getShoeById(params['id']).subscribe(data => {
this.currentShoe = data;
this.initForm();
});
} else {
this.addShoe();
}
});
this.getCompanies();
this.getClassifications();
}
initForm() {
this.initGroupImages();
if (this.currentShoe.gender) {
this.genders.forEach(g => {
if (this.currentShoe.gender.indexOf(g.name) > -1) {
g.mark = true;
} else {
g.mark = false;
}
});
if (!this.currentShoe.information || !Array.isArray(this.currentShoe.information)) {
this.currentShoe.information = [];
}
}
}
getCompanies(): any {
this.sub3 = this.companyService.getCompanies().subscribe(
data => {this.companies = data},
error => console.log(error)
)
}
addShoe() {
this.sub2 = this.shoeService.countShoes().subscribe(
data => {
console.log(data);
// count shoes in database * 2 + random number between 10-9900 * 3
this.friendlyId = ((data * 2) + ((Math.floor(Math.random() * 100000) + 10) * 3)).toString();
this.currentShoe = { 'active': true , 'id': this.friendlyId , 'imagesGroup': [], 'information': []};
this.initGroupImages();
},
error => console.log(error),
);
if (!this.currentShoe.information || !Array.isArray(this.currentShoe.information)) {
this.currentShoe.information = [];
}
}
deleteImage(shoe, index, jIndex) {
const image = shoe.imagesGroup[index].images[jIndex];
if (image.urlMedium.indexOf('data:image') !== 0) {
if (!shoe.deleteImages) {
shoe.deleteImages = [];
}
shoe.deleteImages.push(image);
}
shoe.imagesGroup[index].images.splice(jIndex, 1);
}
// On SAVE
doneEditShoe(shoe) {
this.isLoading = true;
this.beforeSubmitting(shoe);
if (!this.currentShoe._id) {
this.sub5 = this.shoeService.addShoe(shoe).subscribe(
res => {
this.toast.setMessage(shoe.id + ' עודכן בהצלחה', 'success');
this.isLoading = false;
this.backClicked();
},
error => console.log(error)
);
} else {
this.sub5 = this.shoeService.editShoe(shoe).subscribe(
res => {
this.toast.setMessage(shoe.id + ' עודכן בהצלחה', 'success');
this.isLoading = false;
this.backClicked();
},
error => {
console.log(error);
}
);
}
}
beforeSubmitting(shoe) {
shoe.gender = this.genders.filter(g => g.mark).map(g => g.name);
this.genders.forEach(g => g.mark = false);
let countStock: Number = 0;
this.currentShoe.imagesGroup.forEach(ig => {
if (ig.sizeOptions) {
ig.sizes = [];
ig.sizeOptions.filter(g => g.mark).forEach(so => {
countStock += so.amount;
ig.sizes.push({'size' : so.name , 'amount' : so.amount});
});
}
});
this.discountCalc(shoe);
this.createSearchWords(shoe);
shoe.stock = countStock;
}
discountCalc(shoe) {
shoe.finalPrice = shoe.price;
if (shoe.discount && shoe.discount.percentage) {
shoe.finalPrice = (shoe.price * (1 - (shoe.discount.percentage / 100))).toFixed(1);
}
if (shoe.discount && shoe.discount.newAmount) {
shoe.finalPrice = shoe.discount.newAmount;
}
}
createSearchWords(shoe) {
const searchWords: String[] = ['נעליים'];
this.classifications.forEach(c => {
if (c._id === shoe.classification) {
searchWords.push(c.name);
shoe.classificationCache = c.name;
}})
shoe.company = this.companies.find(c => c._id === shoe.companyId).name;
searchWords.push(shoe.id);
shoe.company.split(' ').forEach(element => {
searchWords.push(element);
});
shoe.name.split(' ').forEach(element => {
searchWords.push(element);
});
shoe.gender.forEach(g => searchWords.push(g));
shoe.imagesGroup.forEach(ig => {
ig.color.split(' ').forEach(element => {
searchWords.push(element);
});
});
if (shoe.price !== shoe.finalPrice) {
searchWords.push('SALE');
}
shoe.searchWords = searchWords;
}
handleInputChange(e, imageGroup) {
this.currentImageGroup = imageGroup;
const file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];
const pattern = /image-*/;
const reader = new FileReader();
if (!file.type.match(pattern)) {
alert('invalid format');
return;
}
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsDataURL(file);
}
_handleReaderLoaded(e) {
const reader = e.target;
this.currentImageGroup.images.push({ 'urlMedium' : reader.result });
}
getClassifications() {
this.sub4 = this.ClassificationService.getClassifications().subscribe(
data => {
if (data != null) {
this.classifications = data;
}
},
error => console.log(error),
);
}
initGroupImages() {
if (!this.currentShoe.imagesGroup || this.currentShoe.imagesGroup.length === 0) {
this.currentShoe.imagesGroup = [];
this.currentShoe.imagesGroup.push({'sizes': [], 'images': []});
}
this.currentShoe.imagesGroup.forEach(ig => {
ig.sizeOptions = [];
this.sizes.forEach(s => {
const sizeIndex = ig.sizes.map(igs => igs.size).indexOf(s.toString());
if (sizeIndex > -1) {
ig.sizeOptions.push({'name': s, 'mark': true, 'amount': ig.sizes[sizeIndex].amount});
} else {
ig.sizeOptions.push({'name': s, 'mark': false, 'amount': 0});
}
})});
}
addGroupImage() {
this.currentShoe.imagesGroup.push({'sizes': [], 'images': []});
this.initGroupImages();
}
removeGroupImage(index) {
this.currentShoe.imagesGroup[index].images.forEach((img , j) => { this.deleteImage(this.currentShoe, index, j) });
this.currentShoe.imagesGroup.splice(index, 1);
this.initGroupImages();
}
sizeUp(sizeOption) {
sizeOption.amount++;
sizeOption.mark = true;
}
sizeDown(sizeOption) {
if (sizeOption.amount > 0) {
sizeOption.amount--;
if (sizeOption.amount === 0) {
sizeOption.mark = false;
}
}
}
addRemoveDiscount(shoe) {
if (!this.currentShoe.discount) {
this.currentShoe.discount = {};
} else {
this.currentShoe.discount = null;
}
}
backClicked() {
this._location.back();
}
removeInfoIfEmpty(event, index) {
this.currentShoe.information[index] = event.target.value;
if (!event.target.value || event.target.value === '') {
this.currentShoe.information.splice(index, 1);
}
}
deleteShoeConfirm(model) {
model.open();
}
deleteShoe() {
this.sub7 = this.shoeService.deleteShoe(this.currentShoe).subscribe(
res => {
this.toast.setMessage(this.currentShoe.id + ' הוסר בהצלחה', 'success');
this.isLoading = false;
this.backClicked();
},
error => console.log(error)
);
}
ngOnDestroy(): void {
if (this.sub) {
this.sub.unsubscribe();
}
if (this.sub1) {
this.sub1.unsubscribe();
}
if (this.sub2) {
this.sub2.unsubscribe();
}
if (this.sub3) {
this.sub3.unsubscribe();
}
if (this.sub4) {
this.sub4.unsubscribe();
}
if (this.sub5) {
this.sub5.unsubscribe();
}
if (this.sub6) {
this.sub6.unsubscribe();
}
if (this.sub7) {
this.sub7.unsubscribe();
}
}
}
|
/// Fetch the nth word-sized system call argument as a file descriptor
/// and return both the descriptor and the corresponding struct file.
fn argfd<'a>(n: usize, proc: &'a CurrentProc<'a>) -> Result<(i32, &'a RcFile), ()> {
let fd = argint(n, proc)?;
if fd < 0 || fd >= NOFILE as i32 {
return Err(());
}
let f = some_or!(&proc.deref_data().open_files[fd as usize], return Err(()));
Ok((fd, f))
} |
/**
* Find a resolution from a given string representation. Note, this looks
* into all resolutions and does not look into the specific resolutions
* related to a state. Search is by name and by ID of the resolution.
*
* @param value
* - the resolution display text or "" or null;
* @return the resolution object that was found or null if the value is
* empty
* @throws TeamRepositoryException,
* WorkItemCommandLineException
*/
private Identifier<IResolution> findResolution(String value)
throws TeamRepositoryException, WorkItemCommandLineException {
if (value == null) {
return null;
}
if (value.equals("")) {
return null;
}
IWorkflowInfo workflowInfo = getWorkItemCommon().getWorkflow(getWorkItem().getWorkItemType(),
getWorkItem().getProjectArea(), monitor);
Identifier<IResolution>[] resolutions = workflowInfo.getAllResolutionIds();
for (Identifier<IResolution> resolution : resolutions) {
if (workflowInfo.getResolutionName(resolution).equals(value)) {
return resolution;
} else if (resolution.getStringIdentifier().equals(value)) {
return resolution;
}
}
throw new WorkItemCommandLineException("Resolution not found Value: " + value);
} |
//----------------------------------------------------------------------------
// Function: KillTask
//
// Description:
// Kills a task via a jobobject. Outputs the
// appropriate information to stdout on success, or stderr on failure.
//
// Returns:
// ERROR_SUCCESS: On success
// GetLastError: otherwise
DWORD KillTask(PCWSTR jobObjName)
{
HANDLE jobObject = OpenJobObject(JOB_OBJECT_TERMINATE, FALSE, jobObjName);
if(jobObject == NULL)
{
DWORD err = GetLastError();
if(err == ERROR_FILE_NOT_FOUND)
{
return ERROR_SUCCESS;
}
return err;
}
if(TerminateJobObject(jobObject, KILLED_PROCESS_EXIT_CODE) == 0)
{
return GetLastError();
}
CloseHandle(jobObject);
return ERROR_SUCCESS;
} |
// SetConfirmOwnership sets ownership confirming information to db
func (k Keeper) SetConfirmOwnership(ctx sdk.Context, confirmOwnership *types.ConfirmOwnership) {
store := ctx.KVStore(k.storeKey)
key := types.GetConfirmOwnershipKey(confirmOwnership.Product)
store.Set(key, k.cdc.MustMarshalBinaryBare(confirmOwnership))
} |
/* giowin32-private.c - private glib-gio functions for W32 GAppInfo
*
* Copyright 2019 Руслан Ижбулатов
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
static gsize
g_utf16_len (const gunichar2 *str)
{
gsize result;
for (result = 0; str[0] != 0; str++, result++)
;
return result;
}
static gunichar2 *
g_wcsdup (const gunichar2 *str, gssize str_len)
{
gsize str_len_unsigned;
gsize str_size;
g_return_val_if_fail (str != NULL, NULL);
if (str_len < 0)
str_len_unsigned = g_utf16_len (str);
else
str_len_unsigned = (gsize) str_len;
g_assert (str_len_unsigned <= G_MAXSIZE / sizeof (gunichar2) - 1);
str_size = (str_len_unsigned + 1) * sizeof (gunichar2);
return g_memdup2 (str, str_size);
}
static const gunichar2 *
g_utf16_wchr (const gunichar2 *str, const wchar_t wchr)
{
for (; str != NULL && str[0] != 0; str++)
if ((wchar_t) str[0] == wchr)
return str;
return NULL;
}
static gboolean
g_utf16_to_utf8_and_fold (const gunichar2 *str,
gssize length,
gchar **str_u8,
gchar **str_u8_folded)
{
gchar *u8;
gchar *folded;
u8 = g_utf16_to_utf8 (str, length, NULL, NULL, NULL);
if (u8 == NULL)
return FALSE;
folded = g_utf8_casefold (u8, -1);
if (str_u8)
*str_u8 = g_steal_pointer (&u8);
g_free (u8);
if (str_u8_folded)
*str_u8_folded = g_steal_pointer (&folded);
g_free (folded);
return TRUE;
}
/* Finds the last directory separator in @filename,
* returns a pointer to the position after that separator.
* If the string ends with a separator, returned value
* will be pointing at the NUL terminator.
* If the string does not contain separators, returns the
* string itself.
*/
static const gunichar2 *
g_utf16_find_basename (const gunichar2 *filename,
gssize len)
{
const gunichar2 *result;
if (len < 0)
len = g_utf16_len (filename);
if (len == 0)
return filename;
result = &filename[len - 1];
while (result > filename)
{
if ((wchar_t) result[0] == L'/' ||
(wchar_t) result[0] == L'\\')
{
result += 1;
break;
}
result -= 1;
}
return result;
}
/* Finds the last directory separator in @filename,
* returns a pointer to the position after that separator.
* If the string ends with a separator, returned value
* will be pointing at the NUL terminator.
* If the string does not contain separators, returns the
* string itself.
*/
static const gchar *
g_utf8_find_basename (const gchar *filename,
gssize len)
{
const gchar *result;
if (len < 0)
len = strlen (filename);
if (len == 0)
return filename;
result = &filename[len - 1];
while (result > filename)
{
if (result[0] == '/' ||
result[0] == '\\')
{
result += 1;
break;
}
result -= 1;
}
return result;
}
/**
* Parses @commandline, figuring out what the filename being invoked
* is. All returned strings are pointers into @commandline.
* @commandline must be a valid UTF-16 string and not be NULL.
* @after_executable is the first character after executable
* (usually a space, but not always).
* If @comma_separator is TRUE, accepts ',' as a separator between
* the filename and the following argument.
*/
static void
_g_win32_parse_filename (const gunichar2 *commandline,
gboolean comma_separator,
const gunichar2 **executable_start,
gssize *executable_len,
const gunichar2 **executable_basename,
const gunichar2 **after_executable)
{
const gunichar2 *p;
const gunichar2 *first_argument;
gboolean quoted;
gssize len;
gssize execlen;
gboolean found;
while ((wchar_t) commandline[0] == L' ')
commandline++;
quoted = FALSE;
execlen = 0;
found = FALSE;
first_argument = NULL;
if ((wchar_t) commandline[0] == L'"')
{
quoted = TRUE;
commandline += 1;
}
len = g_utf16_len (commandline);
p = commandline;
while (p < &commandline[len])
{
switch ((wchar_t) p[0])
{
case L'"':
if (quoted)
{
first_argument = p + 1;
/* Note: this is a valid commandline for opening "c:/file.txt":
* > "notepad"c:/file.txt
*/
p = &commandline[len];
found = TRUE;
}
else
execlen += 1;
break;
case L' ':
if (!quoted)
{
first_argument = p;
p = &commandline[len];
found = TRUE;
}
else
execlen += 1;
break;
case L',':
if (!quoted && comma_separator)
{
first_argument = p;
p = &commandline[len];
found = TRUE;
}
else
execlen += 1;
break;
default:
execlen += 1;
break;
}
p += 1;
}
if (!found)
first_argument = &commandline[len];
if (executable_start)
*executable_start = commandline;
if (executable_len)
*executable_len = execlen;
if (executable_basename)
*executable_basename = g_utf16_find_basename (commandline, execlen);
if (after_executable)
*after_executable = first_argument;
}
/* Make sure @commandline is a valid UTF-16 string before
* calling this function!
* follow_class_chain_to_handler() does perform such validation.
*/
static void
_g_win32_extract_executable (const gunichar2 *commandline,
gchar **ex_out,
gchar **ex_basename_out,
gchar **ex_folded_out,
gchar **ex_folded_basename_out,
gchar **dll_function_out)
{
gchar *ex;
gchar *ex_folded;
const gunichar2 *first_argument;
const gunichar2 *executable;
const gunichar2 *executable_basename;
gboolean quoted;
gboolean folded;
gssize execlen;
_g_win32_parse_filename (commandline, FALSE, &executable, &execlen, &executable_basename, &first_argument);
commandline = executable;
while ((wchar_t) first_argument[0] == L' ')
first_argument++;
folded = g_utf16_to_utf8_and_fold (executable, (gssize) execlen, &ex, &ex_folded);
/* This should never fail as @executable has to be valid UTF-16. */
g_assert (folded);
if (dll_function_out)
*dll_function_out = NULL;
/* See if the executable basename is "rundll32.exe". If so, then
* parse the rest of the commandline as r'"?path-to-dll"?[ ]*,*[ ]*dll_function_to_invoke'
*/
/* Using just "rundll32.exe", without an absolute path, seems
* very exploitable, but MS does that sometimes, so we have
* to accept that.
*/
if ((g_strcmp0 (ex_folded, "rundll32.exe") == 0 ||
g_str_has_suffix (ex_folded, "\\rundll32.exe") ||
g_str_has_suffix (ex_folded, "/rundll32.exe")) &&
first_argument[0] != 0 &&
dll_function_out != NULL)
{
/* Corner cases:
* > rundll32.exe c:\some,file,with,commas.dll,some_function
* is treated by rundll32 as:
* dll=c:\some
* function=file,with,commas.dll,some_function
* unless the dll name is surrounded by double quotation marks:
* > rundll32.exe "c:\some,file,with,commas.dll",some_function
* in which case everything works normally.
* Also, quoting only works if it surrounds the file name, i.e:
* > rundll32.exe "c:\some,file"",with,commas.dll",some_function
* will not work.
* Also, comma is optional when filename is quoted or when function
* name is separated from the filename by space(s):
* > rundll32.exe "c:\some,file,with,commas.dll"some_function
* will work,
* > rundll32.exe c:\some_dll_without_commas_or_spaces.dll some_function
* will work too.
* Also, any number of commas is accepted:
* > rundll32.exe c:\some_dll_without_commas_or_spaces.dll , , ,,, , some_function
* works just fine.
* And the ultimate example is:
* > "rundll32.exe""c:\some,file,with,commas.dll"some_function
* and it also works.
* Good job, Microsoft!
*/
const gunichar2 *filename_end = NULL;
gssize filename_len = 0;
gssize function_len = 0;
const gunichar2 *dllpart;
quoted = FALSE;
if ((wchar_t) first_argument[0] == L'"')
quoted = TRUE;
_g_win32_parse_filename (first_argument, TRUE, &dllpart, &filename_len, NULL, &filename_end);
if (filename_end[0] != 0 && filename_len > 0)
{
const gunichar2 *function_begin = filename_end;
while ((wchar_t) function_begin[0] == L',' || (wchar_t) function_begin[0] == L' ')
function_begin += 1;
if (function_begin[0] != 0)
{
gchar *dllpart_utf8;
gchar *dllpart_utf8_folded;
gchar *function_utf8;
const gunichar2 *space = g_utf16_wchr (function_begin, L' ');
if (space)
function_len = space - function_begin;
else
function_len = g_utf16_len (function_begin);
if (quoted)
first_argument += 1;
folded = g_utf16_to_utf8_and_fold (first_argument, filename_len, &dllpart_utf8, &dllpart_utf8_folded);
g_assert (folded);
function_utf8 = g_utf16_to_utf8 (function_begin, function_len, NULL, NULL, NULL);
/* We only take this branch when dll_function_out is not NULL */
*dll_function_out = g_steal_pointer (&function_utf8);
g_free (function_utf8);
/*
* Free our previous output candidate (rundll32) and replace it with the DLL path,
* then proceed forward as if nothing has changed.
*/
g_free (ex);
g_free (ex_folded);
ex = dllpart_utf8;
ex_folded = dllpart_utf8_folded;
}
}
}
if (ex_out)
{
if (ex_basename_out)
*ex_basename_out = (gchar *) g_utf8_find_basename (ex, -1);
*ex_out = g_steal_pointer (&ex);
}
g_free (ex);
if (ex_folded_out)
{
if (ex_folded_basename_out)
*ex_folded_basename_out = (gchar *) g_utf8_find_basename (ex_folded, -1);
*ex_folded_out = g_steal_pointer (&ex_folded);
}
g_free (ex_folded);
}
/**
* rundll32 accepts many different commandlines. Among them is this:
* > rundll32.exe "c:/program files/foo/bar.dll",,, , ,,,, , function_name %1
* rundll32 just reads the first argument as a potentially quoted
* filename until the quotation ends (if quoted) or until a comma,
* or until a space. Then ignores all subsequent spaces (if any) and commas (if any;
* at least one comma is mandatory only if the filename is not quoted),
* and then interprets the rest of the commandline (until a space or a NUL-byte)
* as a name of a function.
* When GLib tries to run a program, it attempts to correctly re-quote the arguments,
* turning the first argument into "c:/program files/foo/bar.dll,,,".
* This breaks rundll32 parsing logic.
* Try to work around this by ensuring that the syntax is like this:
* > rundll32.exe "c:/program files/foo/bar.dll" function_name
* This syntax is valid for rundll32 *and* GLib spawn routines won't break it.
*
* @commandline must have at least 2 arguments, and the second argument
* must contain a (possibly quoted) filename, followed by a space or
* a comma. This can be checked for with an extract_executable() call -
* it should return a non-null dll_function.
*/
static void
_g_win32_fixup_broken_microsoft_rundll_commandline (gunichar2 *commandline)
{
const gunichar2 *first_argument;
gunichar2 *after_first_argument;
_g_win32_parse_filename (commandline, FALSE, NULL, NULL, NULL, &first_argument);
while ((wchar_t) first_argument[0] == L' ')
first_argument++;
_g_win32_parse_filename (first_argument, TRUE, NULL, NULL, NULL, (const gunichar2 **) &after_first_argument);
if ((wchar_t) after_first_argument[0] == L',')
after_first_argument[0] = 0x0020;
/* Else everything is ok (first char after filename is ' ' or the first char
* of the function name - either way this will work).
*/
}
|
/**
* This method loads the image for a Contact into the ImageView. If the user does not have image url set, it will create an alphabeticText image.
* This will automatically check if the image is set and handle the views visibility by itself.
*
* @param imageView CircularImageView which loads the image for the user.
* @param textView TextView which will display the alphabeticText image.
* @param contact The Contact object whose image is to be displayed.
*/
public void loadContactImage(CircleImageView imageView, TextView textView, Contact contact) {
try {
textView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
String contactNumber = "";
char firstLetter = 0;
contactNumber = contact.getDisplayName().toUpperCase();
firstLetter = contact.getDisplayName().toUpperCase().charAt(0);
if (firstLetter != '+') {
textView.setText(String.valueOf(firstLetter));
} else if (contactNumber.length() >= 2) {
textView.setText(String.valueOf(contactNumber.charAt(1)));
}
Character colorKey = AlphaNumberColorUtil.alphabetBackgroundColorMap.containsKey(firstLetter) ? firstLetter : null;
GradientDrawable bgShape = (GradientDrawable) textView.getBackground();
bgShape.setColor(context.getResources().getColor(AlphaNumberColorUtil.alphabetBackgroundColorMap.get(colorKey)));
if (contact.isDrawableResources()) {
textView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
int drawableResourceId = context.getResources().getIdentifier(contact.getrDrawableName(), "drawable", context.getPackageName());
imageView.setImageResource(drawableResourceId);
} else if (contact.getImageURL() != null) {
loadImage(imageView, textView, contact.getImageURL(), 0);
} else {
textView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
}
} catch (Exception e) {
}
} |
// ISBN10 ISBN13 Title SubTitle Author Translator Publisher Pubdate Price Series Pages
func prettyBook(b *bookstore.BookInfo) {
fmt.Printf("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s\n", b.ISBN10, b.ISBN13, b.Title, b.SubTitle,
b.OriginTitle, sa(b.Author), sa(b.Translator), b.Publisher, b.Pubdate, y(b.Price),
b.Series.Title, b.Pages, b.Image)
} |
// NewClient instantiates a new core.Broker client
func NewClient(netAddr string) (core.AuthBrokerClient, error) {
brokerConn, err := grpc.Dial(
netAddr,
grpc.WithInsecure(),
grpc.WithTimeout(time.Second*15),
)
if err != nil {
return nil, err
}
broker := core.NewBrokerClient(brokerConn)
brokerManager := core.NewBrokerManagerClient(brokerConn)
return &brokerClient{
BrokerClient: broker,
BrokerManagerClient: brokerManager,
}, nil
} |
In all of JavaScript, I’m not sure there is a more maligned piece than eval() . This simple function designed to execute a string as JavaScript code has been the more source of more scrutiny and misunderstanding during the course of my career than nearly anything else. The phrase “eval() is evil” is most often attributed to Douglas Crockford, who has stated1:
The eval function (and its relatives, Function , setTimeout , and setInterval ) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.
Since Douglas hasn’t put dates on most of his writings, it’s unclear whether he actually coined the term as an article in 20032 also used this phrase without mentioning him. Regardless, it has become the go-to phrase for anyone who sees eval() in code, whether or not they really understand its use.
Despite popular theory (and Crockford’s insistence), the mere presence of eval() does not indicate a problem. Using eval() does not automatically open you up to a Cross-Site Scripting (XSS) attack nor does it mean there is some lingering security vulnerability that you’re not aware of. Just like any tool, you need to know how to wield it correctly, but even if you use it incorrectly, the potential for damage is still fairly low and contained.
Misuse
At the time when “eval() is evil” originated, it was a source of frequent misuse by those who didn’t understand JavaScript as a language. What may surprise you is that the misuse had nothing to do with performance or security, but rather with not understanding how to construct and use references in JavaScript. Suppose that you had several form inputs whose names contained a number, such as “option1″ and “option2″, it was common to see this:
function isChecked(optionNumber) { return eval("forms[0].option" + optionNumber + ".checked"); } var result = isChecked(1);
In this case, the developer is trying to write forms[0].option1.checked but is unaware of how to do that without using eval() . You see this sort of pattern a lot in code that is around ten years old or older as developers of that time just didn’t understand how to use the language properly. The use of eval() is inappropriate here because it’s unnecessary not because it’s bad. You can easily rewrite this function as:
function isChecked(optionNumber) { return forms[0]["option" + optionNumber].checked; } var result = isChecked(1);
In most cases of this nature, you can replace the call to eval() by using bracket notation to construct the property name (that is, after all, one reason it exists). Those early bloggers who talked about misuse, Crockford included, were mostly talking about this pattern.
Debugability
A good reason to avoid eval() is for debugging purposes. Until recently, it was impossible to step into eval() ed code if something went wrong. That meant you were running code into a black box and then out of it. Chrome Developer Tools can now debug eval() ed code, but it’s still painful. You have to wait until the code executes once before it shows up in the Source panel.
Avoiding eval() ed code makes debugging easier, allowing you to view and step through the code easily. That doesn’t make eval() evil, necessarily, just a bit problematic in a normal development workflow.
Performance
Another big hit against eval() is its performance impact. In older browsers, you encountered a double interpretation penalty, which is to say that your code is interpreted and the code inside of eval() is interpreted. The result could be ten times slower (or worse) in browsers without compiling JavaScript engines.
With today’s modern compiling JavaScript engines, eval() still poses a problem. Most engines can run code in one of two ways: fast path or slow path. Fast path code is code that is stable and predictable, and can therefore be compiled for faster execution. Slow path code is unpredictable, making it hard to compile and may still be run with an interpreter3. The mere presence of eval() in your code means that it is unpredictable and therefore will run in the interpreter – making it run at “old browser” speed instead of “new browser” speed (once again, a 10x difference).
Also of note, eval() makes it impossible for YUI Compressor to munge variable names that are in scope of the call to eval() . Since eval() can access any of those variables directly, renaming them would introduce errors (other tools like Closure Compiler and UglifyJS may still munge those variables – ultimately causing errors).
So performance is still a big concern when using eval() . Once again, that hardly makes it evil, but is a caveat to keep in mind.
Security
The trump card that many pull out when discussing eval() is security. Most frequently the conversation heads into the realm of XSS attacks and how eval() opens up your code to them. On the surface, this confusion is understandable, since by its definition eval() executes arbitrary code in the context of the page. This can be dangerous if you’re taking user input and running it through eval() . However, if your input isn’t from the user, is there any real danger?
I’ve received more than one complaint from someone over a piece of code in my CSS parser that uses eval() 4. The code in question uses eval() to convert a string token from CSS into a JavaScript string value. Short of creating my own string parser, this is the easiest way to get the true string value of the token. To date, no one has been able or willing to produce an attack scenario under which this code causes trouble because:
The value being eval() ed comes from the tokenizer. The tokenizer has already verified that it’s a valid string. The code is most frequently run on the command line. Even when run in the browser, this code is enclosed in a closure and can’t be called directly.
Of course, since this code has a primary destination of the command line, the story is a bit different.
Code designed to be used in browsers face different issues, however, the security of eval() typically isn’t one of them. Once again, if you are taking user input and passing it through eval() in some way, then you are asking for trouble. Never ever do that. However, if your use of eval() has input that only you control and cannot be modified by the user, then there are no security risks.
The most common attack vector cited these days is in eval() ing code that is returned from the server. This pattern famously began with the introduction of JSON, which rose in popularity specifically because it could quickly be converted into a JavaScript by using eval() . Indeed, Douglas Crockford himself used eval() in his original JSON utility due to the speed with which it could be converted. He did add checks to make sure there was no truly executable code but the implementation was fundamentally eval() .
These days, most use the built-in JSON parsing capabilities of browsers for this purpose, though some still fetch arbitrary JavaScript to execute via eval() as part of a lazy-loading strategy. This, some argue, is the real security vulnerability. If a man-in-the-middle attack is in progress, then you will be executing arbitrary attacker code on the page.
The man-in-the-middle attack is wielded as the ever-present danger of eval() , opening the security can of worms. However, this is one scenario that doesn’t concern me in the least, because anytime you can’t trust the server you’re contacting means any number of bad things are possible. Man-in-the-middle attacks can inject code onto the page in any number of ways:
By returning attacker-controlled code for JavaScript loaded via <script src=""> . By returning attacker-controlled code for JSON-P requests. By returning attacker-controlled code from an Ajax request that is then eval() ed.
Additionally, such an attack can easily steal cookies and user data without altering anything, let alone the possibility for phishing by returning attacker-controlled HTML and CSS.
In short, eval() doesn’t open you up to man-in-the-middle attacks any more than loading external JavaScript does. If you can’t trust the code from your server then you have much bigger problems than an eval() call here or there.
Conclusion
I’m not saying you should go run out and start using eval() everywhere. In fact, there are very few good use cases for running eval() at all. There are definitely concerns with code clarity, debugability, and certainly performance that should not be overlooked. But you shouldn’t be afraid to use it when you have a case where eval() makes sense. Try not using it first, but don’t let anyone scare you into thinking your code is more fragile or less secure when eval() is used appropriately.
References |
Abstract A179: Targeting UCP2 pathway in melanoma cells reprograms the tumor microenvironment and initiates antitumor immune cycle
Immune checkpoint blockade treatment displays promising therapeutic efficiency in different cancer types. However, a significant proportion of patients are refractory to this treatment due to lack of T-cell infiltration in tumors, a phenotype known as “cold tumors.” To improve the therapeutic benefits of checkpoint blockade, it is crucial to address how to escalate T-cell infiltration into tumors. Here, we characterized melanoma patients in The Cancer Genome Atlas (TCGA) into either high or low T-cell antitumor responses. We then identified the mRNA expression level of mitochondrial uncoupling protein 2 (UCP2) positively correlates with T-cell antitumor immune responses and prolonged patients survival. By using murine melanoma model, we revealed that overexpressing UCP2 in melanoma cells elevates CD8+ T-cell infiltration into the tumor microenvironment (TME) in a conventional type 1 dendritic cell (cDC1)-dependent manner and normalize tumor neovasculature. Mechanistically, UCP2 induction in tumor cells alters the cytokine milieu in tumors and stimulates the recruitment of cDC1 through a IRF5-CXCL10 chemokine axis. Hence, enhancing the expression of UCP2 in melanoma cells provides immunostimulatory shift by engaging the cDC1-CD8+ T-cell dependent antitumor immune cycle in the TME. Interestingly, we demonstrated that inducing UCP2 expression in melanoma cells by genetic approach or administration of rosiglitazone, an approved antidiabetic PPAR agonist, can sensitize PD-1 blockade-resistant melanomas to anti-PD-1 antibody treatment. Accordingly, our data indicate that targeting UCP2 in melanoma cells can be a potent strategy to increase antitumor response to checkpoint blockades in non-T-cell-inflamed tumors. Citation Format: Wan-Chen Cheng. Targeting UCP2 pathway in melanoma cells reprograms the tumor microenvironment and initiates antitumor immune cycle . In: Proceedings of the Fourth CRI-CIMT-EATI-AACR International Cancer Immunotherapy Conference: Translating Science into Survival; Sept 30-Oct 3, 2018; New York, NY. Philadelphia (PA): AACR; Cancer Immunol Res 2019;7(2 Suppl):Abstract nr A179. |
///////////////////////////////////////////////////////////////////////////////
// This file is generated automatically using Prop (version 2.4.0),
// last updated on Jul 1, 2011.
// The original source file is "env.ph".
///////////////////////////////////////////////////////////////////////////////
#line 1 "env.ph"
///////////////////////////////////////////////////////////////////////////////
//
// This file describes the environment class
//
///////////////////////////////////////////////////////////////////////////////
#ifndef environment_h
#define environment_h
#include "basics.h"
#include "ir.h"
#include "hashtab.h"
class Env
{
void operator = (const Env&);
HashTable env;
public:
Env();
Env(const Env&);
~Env();
Ty operator () (Id) const;
void bind (Id, Ty);
};
#endif
#line 28 "env.ph"
/*
------------------------------- Statistics -------------------------------
Merge matching rules = yes
Number of DFA nodes merged = 0
Number of ifs generated = 0
Number of switches generated = 0
Number of labels = 0
Number of gotos = 0
Adaptive matching = enabled
Fast string matching = disabled
Inline downcasts = enabled
--------------------------------------------------------------------------
*/
|
Phenotypic diversity and sensitivity to injury of the pulmonary endothelium during a period of rapid postnatal growth
Endothelial cells (EC) sit at the forefront of dramatic physiologic changes occurring in the pulmonary circulation during late embryonic and early postnatal life. First, as the lung moves from the hypoxic fetal environment to oxygen-rich postnatal environment, marked changes in pulmonary EC structure and function facilitate a marked increase in blood flow from the placenta to the lungs. Subsequently, pulmonary angiogenesis expands the microvasculature to drive exponential distal lung growth during early postnatal life. Yet, how these marked physiologic changes alter distinct EC subtypes to facilitate the transition of the pulmonary circulation and regulate vascular growth and remodeling remains incompletely understood.In this report, we employed single cell RNA-transcriptomics and in situ RNA imaging to profile pulmonary EC in the developing mouse lung from just before birth through this period of rapid postnatal growth.Multiple, transcriptionally distinct macro- and microvascular EC were identified in the late embryonic and early postnatal lung, with gene expression profiles distinct from their adult EC counterparts. A novel arterial subtype, unique to the developing lung localized to the distal parenchyma and expressed genes that regulate vascular growth and patterning. Birth particularly heightened microvascular diversity, inducing dramatic shifts in the transcriptome of distinct microvascular subtypes in pathways related to proliferation, migration and antigen presentation. Two distinct waves of EC proliferation were identified, including one just prior to birth, and a second during early alveolarization, a time of exponential pulmonary angiogenesis. Chronic hyperoxia, an injury that impairs parenchymal and vascular growth, induced a common gene signature among all pulmonary EC, unique alterations to distinct microvascular EC subtypes, and disrupted EC-EC and EC-immune cell cross talk.Taken together, these data reveal tremendous diversity of pulmonary EC during a critical window of postnatal vascular growth, and provide a detailed molecular map that can be used to inform both normal vascular development and alterations in EC diversity upon injury. These data have important implications for lung diseases marked by dysregulated angiogenesis and pathologic pulmonary vascular remodeling. |
A soldier prepares to fire an M-203 grenade launcher mounted to an M-16 assault rifle. U.S. forces typically use rifle-attached grenade launchers like this one. Photo courtesy U.S. Department of Defense
Impact grenades work like a bomb launched from an airplane -- they explode as soon as they hit their target. Typically, soldiers don't throw impact grenades as they would a time-delay grenade. Instead, they use a grenade launcher to hurl the grenade at high speed.
U.S. ground forces typically use grenade launchers that attach to assault rifles. In one conventional gun-mounted launcher design, grenades are propelled by the gas pressure generated by firing a blank cartridge. Some launcher grenades have their own built-in primer and propellant.
Afghan fighters and many other forces around the world use rocket-propelled grenade launchers, once mass produced by the Soviet Union. Like missiles, these grenades have a built-in rocket propulsion system.
Impact grenades must be unarmed until they are actually fired because any accidental contact might set them off. Since they are usually shot from a launcher, they must have an automatic arming system. In some designs, the arming system is triggered by the propellant explosion that drives the grenade out of the launcher. In other designs, the grenade's acceleration or rotation during its flight arms the detonator.
The diagram below shows the elements in a simple impact grenade with a rotation arming mechanism.
" "
The grenade has an aerodynamic design, with a nose, a tail and two flight fins. The impact trigger, at the nose of the grenade, consists of a movable, spring-mounted panel with an attached firing pin facing inward. As in the time-delay grenade, the fuze mechanism has a percussion cap and a detonator explosive that ignites the main explosive. But it does not include a chemical delay element.
" " A Kurdish refugee with a Soviet RPG-7 grenade launcher, a common weapon in smaller armies and resistance forces Photo courtesy Department of Defense
When the grenade is unarmed, the fuze mechanism is positioned toward the tail end, even though it has a spring pushing it toward the nose. It is held in this position by several spring-mounted, weighted pins. The firing pin is not long enough to reach the percussion cap when the fuze is in this position. If the trigger plate is pressed in accidentally, the pin will slide back and forth in the air, and nothing will happen.
When the grenade is fired it begins to spin (like a well-thrown football). This motion is caused by the shape and position of the fins, as well as spiraled grooves inside the barrel of the grenade launcher.
The spinning motion of the grenade generates a strong centrifugal force that pushes the weighted pins outward. When they move far enough out, the pins release the fuze mechanism, and it springs forward toward the nose of the grenade. When the grenade hits the ground, the nose plate pushes in, driving the firing pin against the percussion cap. The cap explodes, igniting the detonator explosive, which ignites the main explosive.
There are dozens of variations on this idea, some with much more elaborate arming and ignition systems. But the basic principle in most of these weapons is the same.
This content is not compatible on this device.
In the future, grenade mechanisms will continue to evolve. Already, some modern grenades use an electronic fuze system instead of a mechanical or chemical fuze. In time-delay electronic grenades, the fuze consists of a digital clock and an electrically operated firing pin. When the firing button or lever is activated, the electronic system starts a precise timer. At the end of the count, the fuze mechanism releases the firing pin. Since it uses an actual clock instead of a combination of chemicals, this timing system is much more accurate than conventional fuzes.
" " This Mark 19 Mod 3 machine gun fires grenade rounds rather than ordinary bullets. Photo courtesy U.S. Department of Defense
Some cutting-edge launcher-style grenades also have electronic fuzes and arming systems. The U.S. military is currently developing miniature grenades with electronic position sensors. With advanced grenade launchers, soldiers can program a grenade to explode after it has travelled a certain distance. In this way, a soldier can pinpoint particular targets, even ones behind barriers, with extremely high precision.
To learn more about grenades, including their role in military history, check out the links below.
Related HowStuffWorks Articles
More Great Links! |
<gh_stars>0
package org.springframework.security.boot.unionid.authentication;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* UnionID登录认证绑定的参数对象Model
*
* @author : <a href="https://github.com/hiwepy">wandl</a>
*/
public class UnionIDLoginRequest {
/**
* 第三方平台类型
*/
private String platform;
/**
* 第三方平台 UnionID
*/
private String unionid;
/**
* 第三方平台 Token(部分平台需要进行安全验证)
*/
private String token;
@JsonCreator
public UnionIDLoginRequest(@JsonProperty("platform") String platform, @JsonProperty("unionid") String unionid,
@JsonProperty("token") String token) {
this.platform = platform;
this.unionid = unionid;
this.token = token;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
|
/**
* Converts the specified transformation request to a Scala script that can be executed by the script engine.
*
* @param request the transformation request
* @return the Scala script
*/
@Nonnull
@VisibleForTesting
String toTransformScript(@Nonnull final TransformRequest request) {
final StringBuilder script = new StringBuilder();
script.append("class Transform (sqlContext: org.apache.spark.sql.SQLContext, sparkContextService: com.thinkbiganalytics.spark.SparkContextService) extends ");
script.append(transformScriptClass.getName());
script.append("(sqlContext, sparkContextService) {\n");
script.append("override def dataFrame: org.apache.spark.sql.DataFrame = {");
script.append(request.getScript());
script.append("}\n");
if (request.getParent() != null) {
script.append("override def parentDataFrame: org.apache.spark.sql.DataFrame = {");
script.append(request.getParent().getScript());
script.append("}\n");
script.append("override def parentTable: String = {\"");
script.append(StringEscapeUtils.escapeJava(request.getParent().getTable()));
script.append("\"}\n");
}
script.append("}\n");
script.append("new Transform(sqlContext, sparkContextService).run()\n");
return script.toString();
} |
// Valid reports whether configuration is valid or not.
func (lang *Language) Valid() bool {
notEmpty := len(strings.TrimSpace(lang.Code)) != 0
isUp := lang.Code == strings.ToUpper(lang.Code)
return notEmpty && isUp
} |
Over the years, Dale Earnhardt Jr. has been about as enthusiastic for test sessions as he is for road course racing.
In other words, he wouldn’t mind if neither existed.
But this week, Earnhardt found himself “freaking pumped up” to come to a NASCAR organizational test in Phoenix, where he’s turning laps in the public eye for the first time since last July.
Obviously, there’s a simple explanation: He missed racing. From being in the car to the camaraderie with his No. 88 team, Earnhardt has been craving a return to a competitive environment — and this gets him another step closer.
“When you’re racing every single week for 20 years and you’re testing, it gets kind of boring, no lie,” he said. “But you’ve really got to understand what the objectives are. … You forget and lose sight of that over time. You start getting lazy. So I’m excited and happy we’re here.”
Video: Dale Jr.’s first laps in the Phoenix test
At 42, Earnhardt is returning to the NASCAR circuit after missing half of last season with a concussion. Clearly, the prospect of racing again puts him in a great mood. He was all smiles when walking to his car on a beautiful Arizona morning, stopping to ask reporters what social media platform they were using to document his arrival.
Aside from a small brake fire in the morning session which cost him an hour of track time, Earnhardt felt his speed was competitive with the likes of Joey Logano and Kevin Harvick (who won the Phoenix races last year and are also at the test session).
But he acknowledged there’s some anxiety about racing again thanks to such a long layoff.
“I’m just a little nervous about if there will be any kind of learning curve,” he said. “Sometimes you see guys, no matter the type of the sport, who are away for awhile and have to adjust since they’ve taken time off. And other guys come back like they haven’t missed a day.
“I hope there’s no rust to shake off. I’m really anxious to get out there and have some success, go out and run well.” |
/*[clinic input]
_io.FileIO.read
size: Py_ssize_t(accept={int, NoneType}) = -1
/
Read at most size bytes, returned as bytes.
Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
[clinic start generated code]*/
static PyObject *
_io_FileIO_read_impl(fileio *self, Py_ssize_t size)
{
char *ptr;
Py_ssize_t n;
PyObject *bytes;
if (self->fd < 0)
return err_closed();
if (!self->readable)
return err_mode("reading");
if (size < 0)
return _io_FileIO_readall_impl(self);
if (size > _PY_READ_MAX) {
size = _PY_READ_MAX;
}
ptr = (char *) PyMem_Malloc(size);
if (ptr == NULL) {
return NULL;
}
n = _Py_read(self->fd, ptr, size);
if (n == -1) {
PyMem_Free(ptr);
return NULL;
}
bytes = PyString_FromStringAndSize(ptr, n);
PyMem_Free(ptr);
return bytes;
} |
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,string> P;
typedef long long int lld;
#define INF (1<<20)
int main(){
int n;
cin >> n;
vector<P> product;
map<string,int> count;
for(int i=0;i<n;i++){
string name; int num;
cin >> name >> num;
if(count[name] == 0) product.push_back(P(name.size(),name));
count[name] += num;
}
sort(product.begin(),product.end());
for(int i=0;i<product.size();i++){
cout << product[i].second << " " << count[product[i].second] << endl;
}
} |
<filename>doccontrollers/src/test/java/ru/doccloud/controller/IAControllerGetTest.java
package ru.doccloud.controller;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.junit.Before;
import ru.doccloud.controller.util.DocumentControllerTestsHelper;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class IAControllerGetTest {
private final static String LOGIN_PATH = "jooq/login";
private final static String HTTP_SCHEMA_URL = "http";
private final static String URL = "localhost";
private final static int PORT = 8888;
private final static String BASIC_PATH = "restapi/systemdata/";
private final static String GET_TENANTS_PATH = BASIC_PATH + "tenants";
private HttpClient httpClient;
@Before
public void init(){
httpClient = HttpClientBuilder.create().build();
}
// @Test
public void getContentTest(){
try {
final String token = getJwtToken();
if(!StringUtils.isBlank(token)) {
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme(HTTP_SCHEMA_URL).setHost(URL).setPort(PORT).setPath(GET_TENANTS_PATH);
URI uri = uriBuilder.build();
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader("Authorization", token);
HttpResponse response = httpClient.execute(httpGet, DocumentControllerTestsHelper.getHttpClientContext());
int respStatus = response.getStatusLine().getStatusCode();
System.out.println("response status: " + respStatus + "os ok ? " + (respStatus == HttpStatus.SC_OK));
if (respStatus == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
entity.writeTo(os);
} catch (IOException e1) {
}
}
}
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
private String getJwtToken(){
HttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme(HTTP_SCHEMA_URL).setHost(URL).setPort(PORT).setPath(LOGIN_PATH);
uriBuilder.addParameter("username", "boot").addParameter("password", "<PASSWORD>");
URI uri = uriBuilder.build();
HttpPost httpPost = new HttpPost(uri );
httpPost.setEntity(new StringEntity(
prepareLoginInfoAsJSON(),
ContentType.create("application/json")));
response = httpClient.execute(httpPost, DocumentControllerTestsHelper.getHttpClientContext());
int statusLoginCode = response.getStatusLine().getStatusCode();
if(statusLoginCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(content);
String accessToken = jObject.getString("access_token");
System.out.println("JWT accessToken: " + accessToken);
return accessToken;
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
private String prepareLoginInfoAsJSON(){
return "{\"username\":\"boot\",\"password\":\"<PASSWORD>\"}";
}
} |
def execute_script(self, string, args=None):
result = None
try:
result = self.driver_wrapper.driver.execute_script(string, args)
return result
except WebDriverException:
if result is not None:
message = 'Returned: ' + str(result)
else:
message = "No message. Check your Javascript source: {}".format(string)
raise WebDriverJavascriptException.WebDriverJavascriptException(self.driver_wrapper, message) |
/* access modifiers changed from: package-private */
public boolean h() {
for (int i2 = 0; i2 < this.a.size(); i2++) {
if (b(this.a.get(i2))) {
return true;
}
}
return false;
} |
// GetFakeMachineFromTemplate passes the machine template spec to return the machine object
func GetFakeMachineFromTemplate(template *v1alpha1.MachineTemplateSpec, parentObject runtime.Object, controllerRef *metav1.OwnerReference) (*v1alpha1.Machine, error) {
desiredLabels := getMachinesLabelSet(template)
desiredFinalizers := getMachinesFinalizers(template)
desiredAnnotations := getMachinesAnnotationSet(template, parentObject)
accessor, err := meta.Accessor(parentObject)
if err != nil {
return nil, fmt.Errorf("parentObject does not have ObjectMeta, %v", err)
}
prefix := getMachinesPrefix(accessor.GetName())
rand.Seed(time.Now().UnixNano())
prefix = prefix + strconv.Itoa(rand.Intn(100000))
machine := &v1alpha1.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: desiredLabels,
Annotations: desiredAnnotations,
Name: prefix,
Finalizers: desiredFinalizers,
},
Spec: v1alpha1.MachineSpec{
Class: template.Spec.Class,
},
}
if controllerRef != nil {
machine.OwnerReferences = append(machine.OwnerReferences, *controllerRef)
}
machine.Spec = *template.Spec.DeepCopy()
return machine, nil
} |
def GenerateUserReport(flags):
if FILE_MANAGER.FileExists(_REPORT_USERS_ORGS_FILE_NAME) and not flags.force:
print 'Showing counts from existing file.'
return
print 'Generating new counts...'
arg_list = [
'--output_file=%s' % _REPORT_USERS_ORGS_FILE_NAME,
'--csv_fields=%s' % ','.join(_REPORT_FILTER_FIELDS),
]
for flag_value, flag_string in [
(flags.apps_domain, '--apps_domain=%s' % flags.apps_domain),
(flags.force, '--force'),
(flags.verbose, '--verbose')]:
if flag_value:
arg_list.append(flag_string)
try:
cmd_utils.RunPyCmd('report_users.py', arg_list)
except admin_api_tool_errors.AdminAPIToolCmdError as e:
log_utils.LogError('Unable to generate org data.', e)
sys.exit(1) |
/**
* Created by sunpengfei on 15/11/4.
*/
public class HotfixApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
File dexPath = new File(getDir("dex", Context.MODE_PRIVATE), "hackdex_dex.jar");
Utils.prepareDex(this.getApplicationContext(), dexPath, "hackdex_dex.jar");
HotFix.patch(this, dexPath.getAbsolutePath(), "dodola.hackdex.AntilazyLoad");
try {
this.getClassLoader().loadClass("dodola.hackdex.AntilazyLoad");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} |
/**
* <pre>
* Kill all the TG server processes.
* Note that this method blindly tries to kill all the servers of the machine
* and do not update the running status of those servers.
* - taskkill on Windows.
* - kill -9 on Unix.
* </pre>
*
* @throws Exception Kill operation fails
*/
public static void killAll() throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(output);
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(psh);
executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
CommandLine cmdLine;
if (OS.isFamilyWindows())
cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
else {
File internalScriptFile = new File(
ClassLoader.getSystemResource(TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh").getFile());
File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
}
try {
Thread.sleep(1000);
executor.execute(cmdLine);
} catch (ExecuteException ee) {
if (output.toString().contains("ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
return;
throw new ExecuteException(output.toString().trim(), 1);
}
if (OS.isFamilyWindows()) {
if (output.toString().contains("ERROR"))
throw new ExecuteException(output.toString().trim(), 1);
}
else {
if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
return;
}
System.out.println("TGServer - Server(s) successfully killed :");
if (!output.toString().equals(""))
System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
} |
<filename>src/ui/shared/Svg/Icons/Won.tsx
import React from "react";
import Svg from "../Svg";
import {SvgProps} from "../types";
const Icon: React.FC<SvgProps> = (props) => {
return (
<Svg viewBox="0 0 80 80" {...props}>
<g clipPath="url(#clip0)">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M26.0073 13.3635C24.9476 12.4048 23.2491 12.9058 22.8792 14.286C22.6061 15.3055 23.2111 16.3534 24.2305 16.6266L31.8797 18.6762L26.0073 13.3635ZM18.609 13.1418C19.8344 8.56857 25.4621 6.90878 28.9731 10.0851L41.2257 21.1698C43.051 22.8212 41.4235 25.8102 39.0459 25.1732L23.0863 20.8968C19.7085 19.9917 17.7039 16.5197 18.609 13.1418Z"
fill="#7645D9"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M42.264 10.1052C42.7399 8.62854 44.609 8.17749 45.7061 9.27458C46.5164 10.0849 46.5164 11.3987 45.7061 12.209L39.6263 18.2888L42.264 10.1052ZM49.1002 5.88046C45.4652 2.24548 39.2724 3.73996 37.6954 8.63274L32.192 25.7073C31.3722 28.251 34.5252 30.1781 36.415 28.2883L49.1002 15.6031C51.785 12.9183 51.785 8.5653 49.1002 5.88046Z"
fill="#7645D9"
/>
<path
opacity="0.6"
d="M70.9047 42.5535C71.2363 43.8171 73.0301 43.8171 73.3617 42.5535L74.3564 38.7636C74.4727 38.3202 74.819 37.9739 75.2624 37.8575L79.0523 36.8629C80.3159 36.5313 80.3159 34.7375 79.0523 34.4059L75.2624 33.4112C74.819 33.2949 74.4727 32.9486 74.3564 32.5051L73.3617 28.7153C73.0301 27.4517 71.2363 27.4517 70.9047 28.7153L69.91 32.5051C69.7937 32.9486 69.4474 33.2949 69.004 33.4112L65.2141 34.4059C63.9505 34.7375 63.9505 36.5313 65.2141 36.8629L69.004 37.8575C69.4474 37.9739 69.7937 38.3202 69.91 38.7636L70.9047 42.5535Z"
fill="#53DEE9"
/>
<path
d="M67.9738 14.5792C67.9699 15.345 68.9855 15.6172 69.365 14.952L70.5032 12.957C70.6364 12.7235 70.885 12.58 71.1538 12.5814L73.4506 12.5932C74.2164 12.5971 74.4886 11.5814 73.8234 11.202L71.8284 10.0637C71.5949 9.93057 71.4514 9.68195 71.4528 9.41322L71.4646 7.11635C71.4685 6.35056 70.4528 6.07841 70.0734 6.74357L68.9351 8.73862C68.802 8.97203 68.5533 9.11558 68.2846 9.1142L65.9877 9.10239C65.222 9.09846 64.9498 10.1141 65.615 10.4936L67.61 11.6318C67.8434 11.765 67.987 12.0136 67.9856 12.2824L67.9738 14.5792Z"
fill="#53DEE9"
/>
<path
opacity="0.8"
d="M12.6621 19.7326C13.3806 19.544 13.3806 18.5241 12.6621 18.3356L8.79571 17.3208C8.54359 17.2547 8.34669 17.0578 8.28052 16.8056L7.26579 12.9392C7.07722 12.2208 6.05731 12.2208 5.86875 12.9392L4.85402 16.8056C4.78785 17.0578 4.59095 17.2547 4.33883 17.3208L0.472442 18.3356C-0.246022 18.5241 -0.246022 19.544 0.472441 19.7326L4.33883 20.7473C4.59095 20.8135 4.78785 21.0104 4.85402 21.2625L5.86875 25.1289C6.05731 25.8474 7.07722 25.8474 7.26578 25.1289L8.28052 21.2625C8.34669 21.0104 8.54359 20.8135 8.79571 20.7473L12.6621 19.7326Z"
fill="#53DEE9"
/>
<path
d="M16.1463 37.3821C17.0611 33.9679 20.5705 31.9418 23.9847 32.8566L57.9852 41.9671C61.3994 42.8819 63.4256 46.3912 62.5107 49.8054L56.8167 71.0558C55.9019 74.47 52.3925 76.4961 48.9783 75.5813L14.9778 66.4709C11.5636 65.556 9.53745 62.0467 10.4523 58.6325L16.1463 37.3821Z"
fill="url(#paint0_linear)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M57.157 45.058L23.1564 35.9476C21.4493 35.4902 19.6947 36.5032 19.2373 38.2103L13.5432 59.4607C13.0858 61.1678 14.0989 62.9225 15.806 63.3799L49.8066 72.4903C51.5137 72.9477 53.2683 71.9347 53.7257 70.2276L59.4198 48.9772C59.8772 47.2701 58.8641 45.5154 57.157 45.058ZM23.9847 32.8566C20.5705 31.9418 17.0611 33.9679 16.1463 37.3821L10.4523 58.6325C9.53745 62.0467 11.5636 65.556 14.9778 66.4709L48.9783 75.5813C52.3925 76.4961 55.9019 74.47 56.8167 71.0558L62.5107 49.8054C63.4256 46.3912 61.3994 42.8819 57.9852 41.9671L23.9847 32.8566Z"
fill="#0098A1"
/>
<path d="M35.9629 36.0654L46.0085 38.7571L37.0016 72.3714L26.956 69.6797L35.9629 36.0654Z"
fill="#7645D9"/>
<path d="M11.8535 53.0029L14.5452 42.9573L61.111 55.4346L58.4193 65.4802L11.8535 53.0029Z"
fill="#7645D9"/>
<g style={{mixBlendMode: "multiply"}}>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M30.0918 57.9047L40.1732 60.606L39.7591 62.1515L29.6777 59.4502L30.0918 57.9047ZM42.8724 50.5325L32.791 47.8312L33.2051 46.2857L43.2865 48.987L42.8724 50.5325Z"
fill="#7645D9"
/>
</g>
<path
d="M11.4611 31.1814C10.775 28.6207 12.2946 25.9887 14.8552 25.3026L58.1287 13.7075C60.6893 13.0214 63.3213 14.541 64.0074 17.1016L65.1462 21.3517C65.8324 23.9123 64.3128 26.5443 61.7521 27.2305L18.4787 38.8256C15.918 39.5117 13.286 37.9921 12.5999 35.4314L11.4611 31.1814Z"
fill="url(#paint1_linear)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M58.9569 16.7985L15.6834 28.3936C14.8299 28.6223 14.3233 29.4996 14.552 30.3531L15.6908 34.6032C15.9196 35.4568 16.7969 35.9633 17.6504 35.7346L60.9239 24.1395C61.7775 23.9108 62.284 23.0335 62.0553 22.1799L60.9165 17.9298C60.6878 17.0763 59.8104 16.5698 58.9569 16.7985ZM14.8552 25.3026C12.2946 25.9887 10.775 28.6207 11.4611 31.1814L12.5999 35.4314C13.286 37.9921 15.918 39.5117 18.4787 38.8256L61.7521 27.2305C64.3128 26.5443 65.8324 23.9123 65.1462 21.3517L64.0074 17.1016C63.3213 14.541 60.6893 13.0214 58.1287 13.7075L14.8552 25.3026Z"
fill="#0098A1"
/>
<path d="M31.4707 20.8506L41.5163 18.1589L45.1398 31.6818L35.0942 34.3735L31.4707 20.8506Z"
fill="#7645D9"/>
<g style={{mixBlendMode: "multiply"}}>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M31.9671 22.5998L41.9672 19.7998L41.5673 17.9998L31.3975 20.8215L31.9671 22.5998Z"
fill="#7645D9"
/>
</g>
</g>
<defs>
<linearGradient
id="paint0_linear"
x1="40.9849"
y1="37.4118"
x2="31.978"
y2="71.0261"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#53DEE9"/>
<stop offset="1" stopColor="#1FC7D4"/>
</linearGradient>
<linearGradient
id="paint1_linear"
x1="36.4919"
y1="19.505"
x2="40.1154"
y2="33.028"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#53DEE9"/>
<stop offset="1" stopColor="#1FC7D4"/>
</linearGradient>
<clipPath id="clip0">
<rect width="80" height="80" fill="white" transform="matrix(-1 0 0 1 80 0)"/>
</clipPath>
</defs>
</Svg>
);
};
export default Icon;
|
ANDERSON J R (1993) Rules of the Mind. Hillsdale, NJ: Lawrence Erlbaum Associates.
ANDERSON J R and Lebiere C (1998) The Atomic Components of Thought. Mahwah, NJ: Lawrence Erlbaum Associates.
AXTELL R, Axelrod J and Cohen M (1996) Aligning Simulation Models: A Case Study and Results. Computational and Mathematical Organization Theory, 1(2), pp. 123-141.
BERRY D and Broadbent D (1988) Interactive Tasks and the Implicit-Explicit Distinction. British Journal of Psychology, 79, pp. 251-272.
BEST B J and Lebiere C (2003) Teamwork, Communication, and Planning in ACT-R: Agents Engaging in Urban Combat in Virtual Environments. Proceedings of the IJCAI 2003 Workshop on Cognitive Modeling of Agents and Multi-Agent Interactions (Ron Sun, ed.). Acapulco, Mexico.
BOYER P and Ramble C (2001) Cognitive Templates for Religious Concepts: Cross-Cultural Evidence for Recall of Counter-Intuitive Representations. Cognitive Science, 25, pp. 535-564.
CARLEY K M (1992) Organizational Learning and Personnel Turnover. Organizational Science, 3(1). pp. 20-46.
CARLEY K M and Lin Z (1995) Organizational Designs Suited to High Performance Under Stress. IEEE - Systems Man and Cybernetics, 25(1). pp. 221-230.
CARLEY K M and Prietula M J (1992) Toward a Cognitively Motivated Theory of Organizations. Proceedings of the 1992 Coordination Theory and Collaboration Technology Workshop. Washington D.C.
CARLEY K M, Prietula M J, and Lin Z (1998) Design Versus Cognition: The interaction of agent cognition and organizational design on organizational performance. Journal of Artificial Societies and Social Simulation, 1(3), http://jasss.soc.surrey.ac.uk/1/3/4.html
CARLEY K M and Svoboda D M (1996) Modeling Organizational Adaptation as a Simulated Annealing Process. Sociological Methods and Research, 25(1), pp. 138-168.
CASTELFRANCHI C (2001) The Theory of Social Functions: Challenges for Computational Social Science and Multi-Agent Learning. Cognitive Systems Research, special issue on the multi-disciplinary studies of multi-agent learning (ed. Ron Sun), 2(1), pp. 5-38.
CECCONI F and Parisi D (1998) Individual Versus Social Survival Strategies. Journal of Artificial Societies and Social Simulation, 1(2), http://jasss.soc.surrey.ac.uk/1/2/1.html
COWARD L A and Sun R (in press) Criteria for an Effective Theory of Consciousness and Examples of Preliminary Attempts at Such a Theory. Consciousness and Cognition.
EDMONDS B and Moss S (2001) "The Importance of Representing Cognitive Processes in Multi-Agent Models." In Dorffner G, Bischof H, and Hornik K (Eds.). Artificial Neural Networks--ICANN'2001. Springer-Verlag: Lecture Notes in Computer Science, 2130, pp. 759-766.
GILBERT N and Doran J (1994) Simulating Societies: The Computer Simulation of Social Phenomena. London, UK: UCL Press, London.
GOLDSPINK C (2000) Modeling Social Systems as Complex: Towards a Social Simulation Meta-Model. Journal of Artificial Societies and Social Simulation, 3(2), http://jasss.soc.surrey.ac.uk/3/2/1.html
HUTCHINS E (1995) How a Cockpit Remembers Its Speeds. Cognitive Science, 19, pp. 265-288.
JENSEN F V (1996). An Introduction to Bayesian Networks. NY: Springer-Verlag.
KAHAN J and Rapoport A (1984) Theories of Coalition Formation. Mahwah, NJ: Erlbaum.
KLAHR D, Langley P, and Neches R (eds.) (1987) Production System Models of Learning and Development. Cambridge, MA: MIT Press.
LEVY S (1992) Artificial Life. London: Jonathan Cape.
LOUIE M A, Carley K M, Haghshenass L, Kunz J C, and Levitt R E (2003) Model Comparisons: Docking ORGAHEAD and SimVision. NAACSOS conference proceedings. PA: Pittsburgh.
MAHER M L, Smith G J and Gero J S (2003) Design Agents in 3D Virtual Worlds. Proceedings of the IJCAI 2003 Workshop on Cognitive Modeling of Agents and Multi-Agent Interactions (Ron Sun, ed.). Acapulco, Mexico.
MANDLER J (1992) How to Build a Baby. Psychology Review, 99(4), pp. 587-604.
MOSS S (1999) Relevance, Realism and Rigour: A Third Way for Social and Economic Research. CPM Report No. 99-56. Manchester, UK: Center for Policy Analysis, Manchester Metropolitan University.
PALMERI T J (1997) Exemplar Similarity and the Development of Automaticity. Journal of Experimental Psychology: Learning, Memory, and Cognition, 23, pp. 324-354.
PHELAN S and Zhiang Lin (2001) Promotion Systems and Organizational Performance: A Contingency Model. Computational and Mathematical Organization Theory, 7(3), pp. 207-232.
PROCTOR R and Dutta A (1995) Skill Acquisition and Human Performance. Thousand Oaks, CA: Sage Publications.
RABINER L (1989) A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proceedings of the IEEE, 77(2), pp. 257-286.
REBER A (1989) Implicit Learning and Tacit Knowledge. Journal of Experimental Psychology: General, 118(3), pp. 219-235.
ROSENBLOOM P, Laird J, Newell A, and McCarl R (1991) A preliminary analysis of the SOAR architecture as a basis for general intelligence. Artificial Intelligence, 47(1-3), pp. 289-325.
RUMELHART D and McClelland J (Eds.) (1986) Parallel Distributed Processing I. Cambridge, MA: MIT Press.
SCHACTER D (1990) Toward a Cognitive Neuropsychology of Awareness: Implicit Knowledge and Anosagnosia. Journal of Clinical and Experimental Neuropsychology, 12(1), pp. 155-178.
SEGER C (1994) Implicit Learning. Psychological Bulletin, 115(2). pp. 163-196.
SMITH J D and Minda J P (1998) Prototypes in the Mist: The Early Epochs of Category Learning. Journal of Experimental Psychology: Learning, Memory, and Cognition, 24, pp. 1411-1436.
SMOLENSKY P (1988) On the Proper Treatment of Connectionism. Behavioral and Brain Sciences, 11(1), pp. 1-74.
STADLER M and Frensch P (1998) Handbook of Implicit Learning. Thousand Oaks, CA: Sage Publications.
STANLEY W, Mathews R, Buss R, and Kotler-Cope S (1989) Insight Without Awareness: On the Interaction of Verbalization, Instruction and Practice in a Simulated Process Control Task. Quarterly Journal of Experimental Psychology, 41A(3), pp. 553-577.
SUN R (1995) Robust Reasoning: Integrating Rule-Based and Similarity-Based Reasoning. Artificial Intelligence, 75(2), pp. 241-296.
SUN R (1997) Learning, Action, and Consciousness: A Hybrid Approach Towards Modeling Consciousness. Neural Networks, special issue on consciousness, 10(7), pp. 1317-1331.
SUN R (2001) Cognitive Science Meets Multi-Agent Systems: A Prolegomenon. Philosophical Psychology, 14(1), pp. 5-28.
SUN R (2002) Duality of the Mind. Mahwah, NJ: Lawrence Erlbaum Associates.
SUN R, Merrill E, and Peterson T (1998) A Bottom-Up Model of Skill Learning. Proceedings of 20th Cognitive Science Society Conference, pp. 1037-1042. Mahwah, NJ: Lawrence Erlbaum Associates.
SUN R, Merrill E, and Peterson T (2001) From Implicit Skills to Explicit Knowledge: A Bottom-Up Model of Skill Learning. Cognitive Science, 25(2), pp. 203-244.
SUN R and Peterson T (1998) Autonomous Learning of Sequential Tasks: Experiments and Analyses. IEEE Transactions on Neural Networks, 9(6), pp. 1217-1234.
TAKADAMA K, Suematsu Y L, Sugimoto N, Nawa N E, and Shimohara K (2003) Cross-Element Validation in Multiagent-Based Simulation: Switching Learning Mechanisms in Agents. Journal of Artificial Societies and Social Simulation, 6(4), http://jasss.soc.surrey.ac.uk/6/4/6.html
WATKINS C (1989) Learning with Delayed Rewards. PhD Thesis, Cambridge University, Cambridge, UK.
WEST R L, Lebiere C, and Bothell D J (2003) Cognitive Architectures, Game Playing, and Interactive Agents. Proceedings of the IJCAI 2003 Workshop on Cognitive Modeling of Agents and Multi-Agent Interactions (Ron Sun, ed.). Acapulco, Mexico.
WILLINGHAM D, Nissen M and Bullemer P (1989) On the Development of Procedural Knowledge. Journal of Experimental Psychology: Learning, Memory and Cognition, 15, pp. 1047-1060.
YE M and Carley K M (1995) Radar-Soar: Towards An Artificial Organization Composed of Intelligent Agents. Journal of Mathematical Sociology, 20(2-3), pp. 219-246. |
<filename>pzy-redis-starter/src/main/java/org/pzy/opensource/redis/support/util/RedisIncrAndDecrUtil.java<gh_stars>0
/*
* Copyright (c) [2019] [潘志勇]
* [pzy-opensource] is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
* http://license.coscl.org.cn/MulanPSL
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
* PURPOSE.
* See the Mulan PSL v1 for more details.
*/
package org.pzy.opensource.redis.support.util;
import org.apache.commons.lang3.StringUtils;
import org.pzy.opensource.redis.domain.bo.IncrIdBO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
/**
* 使用redis进行自增/自减操作
*
* @author 潘志勇
* @date 2019-03-21
*/
public class RedisIncrAndDecrUtil {
private static RedisTemplate<String, Object> REDIS_TEMPLATE_VALUE_JSON_STRING;
private RedisIncrAndDecrUtil() {
}
public static RedisIncrAndDecrUtil INSTANCE;
public static RedisIncrAndDecrUtil newInstance(RedisTemplate<String, Object> redisTemplate) {
if (null == REDIS_TEMPLATE_VALUE_JSON_STRING) {
synchronized (RedisIncrAndDecrUtil.class) {
if (null == REDIS_TEMPLATE_VALUE_JSON_STRING) {
REDIS_TEMPLATE_VALUE_JSON_STRING = redisTemplate;
INSTANCE = new RedisIncrAndDecrUtil();
}
}
}
return INSTANCE;
}
/**
* 自增操作
*
* @param key 存储的key
* @return 自增后的结果
*/
public static Long incr(String key) {
return REDIS_TEMPLATE_VALUE_JSON_STRING.opsForValue().increment(key);
}
/**
* 自增操作
*
* @param key 存储的key
* @param step 自增步长
* @return 自增后的结果
*/
public static Long incr(String key, Integer step) {
return REDIS_TEMPLATE_VALUE_JSON_STRING.opsForValue().increment(key, step);
}
/**
* 自减操作
*
* @param key
* @return
*/
public static Long decr(String key) {
return REDIS_TEMPLATE_VALUE_JSON_STRING.opsForValue().decrement(key);
}
/**
* 自减操作
*
* @param key
* @param step 自减步长
* @return
*/
public static Long decr(String key, Integer step) {
return REDIS_TEMPLATE_VALUE_JSON_STRING.opsForValue().decrement(key, step);
}
/**
* 根据key获取自增id,prefix和datePattern不能同时为空
*
* @param prefix 前缀
* @param datePattern 日期格式字符串[可以为空]
* @param expireTime 过期时间,小于等于0表示永不过期[单位:秒]
* @return
*/
public static IncrIdBO getId(String prefix, String datePattern, long expireTime) {
if (StringUtils.isBlank(prefix) && StringUtils.isBlank(datePattern)) {
throw new RuntimeException("prefix和datePattern不能同时为空!");
}
String dateStr = null;
if (StringUtils.isNotBlank(datePattern)) {
dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern(datePattern));
} else {
dateStr = StringUtils.EMPTY;
}
String key;
if (StringUtils.isBlank(prefix)) {
key = dateStr;
} else if (StringUtils.isBlank(dateStr)) {
key = prefix.trim();
} else {
key = prefix.trim() + ":" + dateStr;
}
IncrIdBO incrIdBO = new IncrIdBO();
incrIdBO.setKey(key);
incrIdBO.setId(getIncr(key, expireTime));
return incrIdBO;
}
/**
* 根据key和expireTime获取自增值<br/><br/>
* 如何防止,redis重启之后,自增值由重新开始计算?<br/>
* 解决方案: <a href='https://blog.csdn.net/u010648555/article/details/73442336'>开启AOF备份</a>
*
* @param key
* @param expireTime 小于等于0表示永久有效. 单位:秒
* @return
*/
private static Long getIncr(String key, long expireTime) {
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, REDIS_TEMPLATE_VALUE_JSON_STRING.getConnectionFactory());
Long increment = entityIdCounter.getAndIncrement();
if (expireTime > 0) {
//初始设置过期时间
entityIdCounter.expire(expireTime, TimeUnit.SECONDS);
}
return increment;
}
}
|
t = int(input())
for i in range(t):
b,p,f = [int(i) for i in input().split()]
h,c = [int(i) for i in input().split()]
buns = b//2
tr = (p+f)*2
k = (p+f)
if b < 2:
print(0)
elif tr < b:
if h == c:
print(k*h)
elif h > c:
a = h*p
m = (k-p)*c
print(a+m)
else:
a = c*f
m = (k-f)*h
print(a+m)
else:
if h==c:
print(buns*h)
elif c>h:
bu = buns - f
if bu <0:
a = c * buns
print(a)
else:
a = c * f
m = bu * h
print(a+m)
else:
bu = buns - p
if bu < 0:
a = h * buns
print(a)
else:
a = h * p
m = bu * c
print(a+m)
|
use clap::Parser;
#[derive(Parser)]
#[clap(version = "1.0")]
#[derive(Debug)]
struct Opts {
year: u32,
day: usize,
part: usize,
}
fn main() {
let opts: Opts = Opts::parse();
match (opts.year, opts.day, opts.part) {
(2015, day, part) => aoc::aoc_2015::SOLUTIONS[day - 1][part - 1](),
(2021, day, part) => aoc::aoc_2021::SOLUTIONS[day - 1][part - 1](),
_ => eprintln!("Error: Unknown options {:?}", opts),
}
}
|
<filename>tests/test-checkpoint2.py
a = 5
#chk>{{{
#chk>gANDIEfymvjN9EowcCGj+XNtin7uihFyNxXkbW2Myny7GZzJcQAugAN9cQAoWAwAAABfX2J1aWx0aW5z
#chk>X19xAWNidWlsdGlucwpfX2RpY3RfXwpYAQAAAGFxAksFdS4=
#chk>}}}
print(a)
#o> 5
|
MEXICO CITY (Reuters) - Hector Beltran Leyva, one of the most notorious Mexican drug lords still at large, was captured on Wednesday by soldiers at a seafood restaurant in a picturesque town in central Mexico popular with American retirees.
Pictures of the head of the Beltran Leyva drug cartel Hector Beltran Leyva are seen displayed on a television screen during a news conference at the Attorney General's Office building in Mexico City October 1, 2014, in this handout courtesy of the office. REUTERS/Attorney General's Office/Handout via Reuters
The government’s announcement it had snared the boss of the Beltran Leyva cartel is a serious blow to a gang named after a group of brothers who became infamous for the bloody turf war they waged with their former ally, Joaquin “Shorty” Guzman.
Beltran Leyva was caught in the picture postcard town of San Miguel de Allende, a three-hour drive northwest of Mexico City, and had been living in the nearby city of Queretaro posing as a businessman dealing in art and real estate, the government said.
The 49-year-old Beltran Leyva and an associate were carrying military-issue handguns, but like his adversary Guzman, he was arrested without a shot being fired. Guzman, who was the world’s most wanted drug boss, was captured in Mexico in February.
Beltran Leyva shunned luxury cars, passing himself off as a well-off businessman, said Tomas Zeron, director of criminal investigations at the Attorney General’s office.
“(Beltran Leyva) kept his operations away from his home so as not to alter his discreet, low-key lifestyle, avoiding attracting the attention of neighbors or friends or the authorities,” Zeron said.
Beltran Leyva now faces charges of trafficking cocaine from Mexico and South America to the United States and Europe and a host of other crimes. In November, the U.S. Treasury Department said the Beltran Leyva gang was responsible for “countless murders” of Mexican anti-drugs and military personnel.
Hector’s capture is a major victory for President Enrique Pena Nieto, who has sought to shift focus away from the violence that fighting the drug gangs has spawned in recent years and onto the economic reforms he has pushed through Congress.
Pena Nieto on his Twitter account touted the capture of Beltran Leyva, who had bounties on his head of $5 million in the United States and 30 million pesos ($2.2 million) in Mexico.
Hector, who Zeron said had likely branched out into selling synthetic drugs, was the only one of the gang’s brothers known to be involved in drug trafficking not dead or behind bars.
BLOODY WAR
When Mexican special forces arrested Alfredo Beltran Leyva in early 2008, the brothers reportedly believed Guzman had sold out their sibling, sparking a war with the boss of the Sinaloa Cartel based in the northwestern state of the same name.
Over the next three years, the rupture ushered in a new brutality to the violence that overshadowed the 2006-2012 administration of then-President Felipe Calderon.
By 2010, the Beltran Leyvas had lost several leaders and Hector, alias “The Engineer,” was in control.
The Beltran Leyva gang has had a reputation as one of the most vengeful and ruthless in the business.
When Hector’s older brother Arturo was killed by Mexican marines in December 2009, the government honored one of the young marines slain in the raid and images of the family funeral were broadcast around the country.
The next day, gunmen swept into the family home and killed the marine’s mother, sister, brother and an aunt.
For years, the Beltran Leyva brothers had worked with other Sinaloan gangsters, notably Guzman, helping to manage his network of hitmen. The brothers and Guzman hailed from the same region of Sinaloa, and marriages also linked the two clans.
Guzman reportedly tasked the Beltran Leyva organization with infiltrating Mexico’s security and political apparatus.
Security experts went as far as to credit Hector Beltran Leyva with having an informant inside the office of then-President Vicente Fox a decade ago. The official, Nahum Acosta, was arrested in 2005 but later released for lack of evidence.
At its peak, the Beltran Leyva cartel dominated drug-trafficking in western Mexico. After the break with Guzman, the brothers forged alliances of convenience with former rivals in the Gulf Cartel as well as the ruthless Zetas.
After Arturo’s death, the Beltran Leyva organization was weakened by infighting as a split emerged between Hector and a faction led by U.S.-born Edgar Valdez Villarreal, alias “La Barbie,” whom Mexican authorities arrested in August 2010.
Lately, however, U.S. officials said that the Beltran Leyva cartel had begun to expand after rebuilding itself. |
////////////////////////////////////////////////////////////////////
// Function: EggVertexPool::begin()
// Access: Public
// Description: Returns an iterator that can be used to traverse
// through all the vertices in the pool.
////////////////////////////////////////////////////////////////////
EggVertexPool::iterator EggVertexPool::
begin() const {
nassertr(_index_vertices.size() == _unique_vertices.size(),
iterator(_index_vertices.begin()));
return iterator(_index_vertices.begin());
} |
<reponame>trebol-ecommerce/ngx-trebol-frontend
/*
* Copyright (c) 2022 The Trebol eCommerce Project
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
/**
* Keeps track of the sidenav open state
*/
@Injectable()
export class ManagementSidenavService {
private isSidenavOpenSource = new BehaviorSubject(true);
isSidenavOpen$ = this.isSidenavOpenSource.asObservable();
constructor() { }
toggleSidenav(): void {
this.isSidenavOpenSource.next(!this.isSidenavOpenSource.value);
}
}
|
#pragma once
#include <Engine/LogicCore/Components/SComponent.h>
namespace ScrapEngine
{
namespace Physics
{
class CollisionBody;
}
}
namespace ScrapEngine
{
namespace Core
{
class RigidBodyComponent;
class TriggerComponent : public SComponent
{
private:
Physics::CollisionBody* collisionbody_ = nullptr;
public:
TriggerComponent(Physics::CollisionBody* collisionbody);
virtual ~TriggerComponent() = 0;
void set_component_location(const SVector3& location) override;
void set_component_rotation(const SVector3& rotation) override;
bool test_collision(TriggerComponent* other) const;
bool test_collision(RigidBodyComponent* other) const;
};
}
}
|
/** Gitiles access for testing. */
public class TestGitilesAccess implements GitilesAccess.Factory {
private final DfsRepository repo;
public TestGitilesAccess(DfsRepository repo) {
this.repo = checkNotNull(repo);
}
@Override
public GitilesAccess forRequest(final HttpServletRequest req) {
return new GitilesAccess() {
@Override
public Map<String, RepositoryDescription> listRepositories(Set<String> branches) {
// TODO(dborowitz): Implement this, using the DfsRepositoryDescriptions to
// get the repository names.
throw new UnsupportedOperationException();
}
@Override
public Object getUserKey() {
return "a user";
}
@Override
public String getRepositoryName() {
return repo.getDescription().getRepositoryName();
}
@Override
public RepositoryDescription getRepositoryDescription() {
RepositoryDescription d = new RepositoryDescription();
d.name = getRepositoryName();
d.description = "a test data set";
d.cloneUrl = TestGitilesUrls.URLS.getBaseGitUrl(req) + "/" + d.name;
return d;
}
};
}
} |
def parse(self, content, path, delimiter=None):
if delimiter is None:
delimiter = self.delimiters[0]
if not isinstance(delimiter, str):
raise TypeError('delimiter must be a str')
if not self.pre_open:
self.parser(content, path, delimiter)
return
out_file = open(path, 'w', newline='')
self.parser(content, out_file, delimiter)
out_file.close() |
<gh_stars>1-10
package de.kxmpetentes.engine.command;
import de.kxmpetentes.engine.command.impl.ICommand;
import lombok.Getter;
/**
* @author kxmpetentes
* @see de.kxmpetentes.engine.command.impl.ICommand;
*/
public abstract class Command implements ICommand {
@Getter
public final String commandName;
@Getter
public final String[] aliases;
@Getter
public final boolean guildCommand;
/**
* Creates a command
*
* @param commandName string for the command syntax
* @param guildCommand make the command executable at privatechat
* @param aliases aliases for the commandsyntax
*/
public Command(String commandName, boolean guildCommand, String... aliases) {
this.commandName = commandName;
this.guildCommand = guildCommand;
this.aliases = aliases;
}
} |
export declare function any(): (_?: any) => boolean;
export declare function eq(value: any): (_?: any) => boolean;
declare class Mocked {
private calls;
private expectations;
onCall(method: string, args: any): any;
times(method: string, ...args: any): number;
reset(): void;
resetTimes(): void;
on(method: string, ...args: any): {
returns: (_: any) => void;
};
}
export declare class MockCanvasRenderingContext2D extends Mocked implements CanvasRenderingContext2D {
canvas: HTMLCanvasElement;
globalAlpha: number;
globalCompositeOperation: string;
drawImage(image: any, sx: any, sy: any, sw?: any, sh?: any, dx?: any, dy?: any, dw?: any, dh?: any): any;
beginPath(): void;
clip(path?: any, fillRule?: any): any;
fill(path?: any, fillRule?: any): any;
isPointInPath(path: any, x: any, y?: any, fillRule?: any): any;
isPointInStroke(path: any, x: any, y?: any): any;
stroke(path?: any): any;
fillStyle: string | CanvasGradient | CanvasPattern;
strokeStyle: string | CanvasGradient | CanvasPattern;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createPattern(image: CanvasImageSource, repetition: string): CanvasPattern;
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
filter: string;
createImageData(sw: any, sh?: any): any;
getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;
putImageData(imagedata: any, dx: any, dy: any, dirtyX?: any, dirtyY?: any, dirtyWidth?: any, dirtyHeight?: any): any;
imageSmoothingEnabled: boolean;
imageSmoothingQuality: ImageSmoothingQuality;
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;
closePath(): void;
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
lineTo(x: number, y: number): void;
moveTo(x: number, y: number): void;
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;
rect(x: number, y: number, w: number, h: number): void;
lineCap: CanvasLineCap;
lineDashOffset: number;
lineJoin: CanvasLineJoin;
lineWidth: number;
miterLimit: number;
getLineDash(): number[];
setLineDash(segments: any): any;
clearRect(x: number, y: number, w: number, h: number): void;
fillRect(x: number, y: number, w: number, h: number): void;
strokeRect(x: number, y: number, w: number, h: number): void;
shadowBlur: number;
shadowColor: string;
shadowOffsetX: number;
shadowOffsetY: number;
restore(): void;
save(): void;
fillText(text: string, x: number, y: number, maxWidth?: number): void;
measureText(text: string): TextMetrics;
strokeText(text: string, x: number, y: number, maxWidth?: number): void;
direction: CanvasDirection;
font: string;
textAlign: CanvasTextAlign;
textBaseline: CanvasTextBaseline;
getTransform(): DOMMatrix;
resetTransform(): void;
rotate(angle: number): void;
scale(x: number, y: number): void;
setTransform(a?: any, b?: any, c?: any, d?: any, e?: any, f?: any): any;
transform(a: number, b: number, c: number, d: number, e: number, f: number): void;
translate(x: number, y: number): void;
drawFocusIfNeeded(path: any, element?: any): any;
scrollPathIntoView(path?: any): any;
}
export declare class MockCanvas extends Mocked {
width: number;
height: number;
getContext(type: string): any;
addEventListener(type: string, callback: any): any;
asCanvas(): HTMLCanvasElement;
}
export {};
//# sourceMappingURL=MockCanvas.d.ts.map |
<filename>src/models/index.ts
export * from './IPersonalQuickLinksWebPartProps';
export * from './IPersonalQuickLinksProps';
export * from './IQuickLinks';
export * from './IQuickLink';
|
from complete_db.models import Author, Book
import flask_api_framework as af
from .schemas import (
AuthorsBooksListKwargsSchema,
AuthorSchema,
BookCreateSchema,
BookDetailBodySchema,
BookDetailKwargsSchema,
BookListSchema,
)
class AuthorsIndex(af.List, af.Create):
"""
List all authors.
Same body schema for List and Create.
"""
body_schema = AuthorSchema()
def get_instances(self):
return Author.query.all()
class AuthorsBooksList(af.List):
"""
List all books for a specific author defined by a view arg.
"""
kwargs_schema = AuthorsBooksListKwargsSchema()
body_schema = BookListSchema()
def get_instances(self):
q = Book.query
q = q.filter_by(author=self.loaded_kwargs)
return q.all()
class BooksIndex(af.List, af.Create):
"""
List all books, and Create new book.
When listing, allow filtering via query params.
Different body schemas for List and Create.
"""
list_body_schema = BookListSchema()
create_body_schema = BookCreateSchema()
def get_instances(self):
return Book.query.all()
class BookDetail(af.Read, af.Update, af.Delete):
"""
Read, Update, or Delete one specific book.
Same body schema for Read, Update, Delete.
"""
kwargs_schema = BookDetailKwargsSchema()
body_schema = BookDetailBodySchema()
|
export * from './failover-strategy';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.