text
stringlengths
27
775k
#!/usr/bin/env perl #----------------------------------------------------------------------------------------------------------- # input: # clusters_file - a cluster file in the format GENE_NAME\tGENE_CLUSTER\n # regulated_file - the output file for genes # sql_file - the output file for the genes sql file # gene_table - the name of the gene table to create # dir - the directory that the sql file will point to /fiery/u2/erans/D/Biology/RECOMB02/Promoters/D/ # output: # sets the database in mysql with the additional column and then calls bio_update_column.pl to load data #----------------------------------------------------------------------------------------------------------- #---------------------------------------------------------------- # load the settings #---------------------------------------------------------------- if (length($ARGV[0]) == 0) { $settings_file = "settings"; } else { $settings_file = $ARGV[0]; } open(SETTINGS, "<$settings_file") or die "could not open SETTINGS"; while (<SETTINGS>) { chop; ($id, $value) = split(/=/, $_, 2); $settings{$id} = $value; } #---------------------------------------------------------------- # parameters #---------------------------------------------------------------- $clusters_file = $settings{"clusters_file"}; $regulated_file = $settings{"regulated_file"}; $sql_file = $settings{"sql_file"}; $gene_table = $settings{"gene_table"}; $dir = $settings{"dir"}; open(CLUSTER_FILE, "<$clusters_file"); open(REGULATED_FILE, ">$regulated_file"); open(SQL_FILE, ">$sql_file"); $max_cluster = 0; $gene_id = 0; while (<CLUSTER_FILE>) { chop; ($gene_name, $gene_cluster) = split(/\t/); $gene_name_to_cluster{$gene_name} = $gene_cluster; $gene_names[$gene_id] = $gene_name; if ($gene_cluster > $max_cluster) { $max_cluster = $gene_cluster; } $gene_id++; } for ($j = 0; $j < $gene_id; $j++) { $gene_name = $gene_names[$j]; print REGULATED_FILE "$j\t$gene_name"; for ($i = 1; $i <= $max_cluster; $i++) { if ($gene_name_to_cluster{$gene_name} eq $i) { print REGULATED_FILE "\t1"; } else { print REGULATED_FILE "\t0"; } } print REGULATED_FILE "\n"; } print SQL_FILE "drop table if exists $gene_table;\n"; print SQL_FILE "create table $gene_table(\n"; print SQL_FILE " gene_id int primary key,\n"; print SQL_FILE " gene_name char(20)"; for ($i = 1; $i <= $max_cluster; $i++) { print SQL_FILE ",\n"; print SQL_FILE " regulated_by_tf$i int"; } print SQL_FILE "\n);\n"; print SQL_FILE "load data local infile \"$dir/$regulated_file\" into table $gene_table;\n";
from abc import ABC, abstractmethod class BlobStorageClient(ABC): @abstractmethod def delete_all_objects(self, bucket: str, prefix: str) -> None: ... @abstractmethod def put_object(self, data: bytes, bucket: str, key: str) -> str: ... @abstractmethod def get_object(self, bucket: str, key: str) -> bytes: ...
/* Copyright 2006 by Sean Luke Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec.select; import ec.EvolutionState; import ec.Individual; import ec.SelectionMethod; import ec.steadystate.SteadyStateBSourceForm; import ec.steadystate.SteadyStateEvolutionState; import ec.util.IntBag; import ec.util.Parameter; import java.util.ArrayList; import java.util.HashMap; /* * FirstSelection.java * * Created: Mon Aug 30 19:27:15 1999 * By: Sean Luke */ /** * Always picks the first individual in the subpopulation. This is mostly * for testing purposes. * * * <p><b>Default Base</b><br> * select.first * * @author Sean Luke * @version 1.0 */ public class FirstSelection extends SelectionMethod implements SteadyStateBSourceForm { /** * default base */ public static final String P_FIRST = "first"; public Parameter defaultBase() { return SelectDefaults.base().push(P_FIRST); } // I hard-code both produce(...) methods for efficiency's sake public int produce(final int subpopulation, final EvolutionState state, final int thread) { return 0; } // I hard-code both produce(...) methods for efficiency's sake public int produce(final int min, final int max, final int start, final int subpopulation, final Individual[] inds, final EvolutionState state, final int thread, HashMap<String, Object> misc) { int n = 1; if (n > max) n = max; if (n < min) n = min; for (int q = 0; q < n; q++) { // pick size random individuals, then pick the best. ArrayList<Individual> oldinds = state.population.subpops.get(subpopulation).individuals; inds[start + q] = oldinds.get(0); // note it's a pointer transfer, not a copy! if (misc != null && misc.get(KEY_PARENTS) != null) { IntBag parent = new IntBag(1); parent.add(0); ((IntBag[]) misc.get(KEY_PARENTS))[start + q] = parent; } } return n; } public void individualReplaced(final SteadyStateEvolutionState state, final int subpopulation, final int thread, final int individual) { return; } public void sourcesAreProperForm(final SteadyStateEvolutionState state) { return; } }
package uz.javokhirdev.extensions typealias EmptyBlock = () -> Unit typealias SingleBlock <T> = T.() -> Unit typealias DoubleBlock <T, E> = (T, E) -> Unit typealias TrialBlock <T, E, F> = (T, E, F) -> Unit
package uk.gov.justice.digital.hmpps.pecs.jpc.config import nz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import uk.gov.justice.digital.hmpps.pecs.jpc.config.aws.ReportingProvider import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.Price import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.PriceRepository import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.Supplier import uk.gov.justice.digital.hmpps.pecs.jpc.service.MonitoringService import uk.gov.justice.digital.hmpps.pecs.jpc.service.reports.ReportImporter import uk.gov.justice.digital.hmpps.pecs.jpc.service.reports.ReportReaderParser import java.time.Clock import java.time.LocalDate import java.time.LocalDateTime import java.util.stream.Stream @Configuration class ReportImporterConfiguration { @Autowired private lateinit var priceRepository: PriceRepository @Autowired private lateinit var reportingProvider: ReportingProvider @Autowired private lateinit var reportReaderParser: ReportReaderParser @Autowired private lateinit var monitoringString: MonitoringService @Bean fun timeSource() = TimeSource { LocalDateTime.now(Clock.systemDefaultZone()) } @Bean fun supplierPrices() = SupplierPrices { supplier, year -> priceRepository.findBySupplierAndEffectiveYear(supplier, year) } @Bean fun reportImporter() = ReportImporter(reportingProvider, monitoringString, reportReaderParser) // This is now needed for Spring Boot as part of moving from 2.5.3 to 3.0.0 Thymeleaf Layout Dialect @Bean fun thymeleafLayoutDialect() = LayoutDialect() } fun interface SupplierPrices { fun get(supplier: Supplier, effectiveYear: Int): Stream<Price> } /** * To be used for providing date and or time in the applications. Enables control of time in the code (and unit tests). */ fun interface TimeSource { fun dateTime(): LocalDateTime fun date(): LocalDate = dateTime().toLocalDate() fun yesterday(): LocalDate = date().minusDays(1) }
<?php /** * @var $menus array * @var $widget \cms\widgets\menu\controllers\IndexController */ $widget->renderMenu($menus);
#include "vm.h" #include "conf.h" #include "lib.h" #include "mem.h" #include "string.h" #include <inttypes.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static inline void err(const char *msg) { fprintf(stderr, "riff: [vm] %s\n", msg); exit(1); } static rf_htab globals; static rf_tab argv; static rf_tab fldv; static rf_iter *iter; static rf_stack stack[VM_STACK_SIZE]; // Integer arithmetic (Bitwise ops) #define int_arith(l,r,op) set_int(l, (intval(l) op intval(r))) // Floating-point arithmetic (div) #define flt_arith(l,r,op) set_flt(l, (fltval(l) op fltval(r))) // "Polymorphic" arithmetic (add, sub, mul) #define num_arith(l,r,op) \ if (is_int(l) && is_int(r)) { \ l->i = (l->i op r->i); \ } else { \ flt_arith(l,r,op); \ } // Return boolean result of value (0/1) static inline int test(rf_val *v) { switch (v->type) { case TYPE_INT: return !!(v->i); case TYPE_FLT: return !!(v->f); // If entire string is a numeric value, return logical result of // the number. Otherwise, return whether the string is longer than // 0. case TYPE_STR: { char *end; rf_flt f = u_str2d(v->s->str, &end, 0); if (!*end) { // Check for literal '0' character in string if (f == 0.0 && s_haszero(v->s)) return 0; else return !!f; } return !!s_len(v->s); } case TYPE_TAB: return !!t_logical_size(v->t); case TYPE_RE: case TYPE_RNG: case TYPE_RFN: case TYPE_CFN: return 1; default: return 0; } } #define Z_UOP(op) static inline void z_##op(rf_val *v) #define Z_BINOP(op) static inline void z_##op(rf_val *l, rf_val *r) Z_BINOP(add) { num_arith(l,r,+); } Z_BINOP(sub) { num_arith(l,r,-); } Z_BINOP(mul) { num_arith(l,r,*); } // Language comparison for division by zero: // 0/0 = nan; 1/0 = inf : lua, mawk // error: pretty much all others Z_BINOP(div) { flt_arith(l,r,/); } // Language comparison for modulus by zero: // `nan`: mawk // error: pretty much all others Z_BINOP(mod) { rf_flt res = fmod(numval(l), numval(r)); set_flt(l, res < 0 ? res + numval(r) : res); } Z_BINOP(pow) { set_flt(l, pow(fltval(l), fltval(r))); } Z_BINOP(and) { int_arith(l,r,&); } Z_BINOP(or) { int_arith(l,r,|); } Z_BINOP(xor) { int_arith(l,r,^); } Z_BINOP(shl) { int_arith(l,r,<<); } Z_BINOP(shr) { int_arith(l,r,>>); } Z_UOP(num) { switch (v->type) { case TYPE_INT: case TYPE_FLT: break; case TYPE_STR: set_flt(v, str2flt(v->s)); break; default: set_int(v, 0); break; } } Z_UOP(neg) { switch (v->type) { case TYPE_INT: v->i = -v->i; break; case TYPE_FLT: v->f = -v->f; break; case TYPE_STR: set_flt(v, -str2flt(v->s)); break; default: set_int(v, 0); break; } } Z_UOP(not) { set_int(v, ~intval(v)); } // == and != operators #define cmp_eq(l,r,op) \ if (is_int(l) && is_int(r)) { \ l->i = (l->i op r->i); \ } else if (is_null(l) ^ is_null(r)) { \ set_int(l, !(0 op 0)); \ } else if (is_str(l) && is_str(r)) { \ set_int(l, ((l->s) op (r->s))); \ } else if (is_str(l) && !is_str(r)) { \ if (!s_len(l->s)) { \ set_int(l, !(0 op 0)); \ return; \ } \ char *end; \ rf_flt f = u_str2d(l->s->str, &end, 0); \ if (*end) { \ set_int(l, 0); \ } else { \ set_int(l, (f op numval(r))); \ } \ } else if (!is_str(l) && is_str(r)) { \ if (!s_len(r->s)) { \ set_int(l, !(0 op 0)); \ return; \ } \ char *end; \ rf_flt f = u_str2d(r->s->str, &end, 0); \ if (*end) { \ set_int(l, 0); \ } else { \ set_int(l, (numval(l) op f)); \ } \ } else { \ num_arith(l,r,op); \ } // >, <, >= and <= operators #define cmp_rel(l,r,op) \ if (is_int(l) && is_int(r)) { \ l->i = (l->i op r->i); \ } else { \ set_int(l, (numval(l) op numval(r))); \ } Z_BINOP(eq) { cmp_eq(l,r,==); } Z_BINOP(ne) { cmp_eq(l,r,!=); } Z_BINOP(gt) { cmp_rel(l,r,>); } Z_BINOP(ge) { cmp_rel(l,r,>=); } Z_BINOP(lt) { cmp_rel(l,r,<); } Z_BINOP(le) { cmp_rel(l,r,<=); } Z_UOP(lnot) { set_int(v, !test(v)); } Z_UOP(len) { rf_int l = 0; switch (v->type) { // For integers: // #x = ⌊log10(x)⌋ + 1 for x > 0 // ⌊log10(-x)⌋ + 2 for x < 0 case TYPE_INT: if (v->i == INT64_MIN) { l = 20; } else { l = v->i > 0 ? (rf_int) log10(v->i) + 1 : v->i < 0 ? (rf_int) log10(-v->i) + 2 : 1; } v->i = l; return; case TYPE_FLT: l = (rf_int) snprintf(NULL, 0, "%g", v->f); break; case TYPE_STR: l = s_len(v->s); break; case TYPE_TAB: l = t_logical_size(v->t); break; case TYPE_RE: // TODO - extract something from PCRE pattern? case TYPE_RNG: // TODO case TYPE_RFN: case TYPE_CFN: l = 1; break; default: break; } set_int(v, l); } Z_BINOP(cat) { char *lhs, *rhs; char temp_lhs[32]; char temp_rhs[32]; if (!is_str(l)) { switch (l->type) { case TYPE_INT: u_int2str(l->i, temp_lhs); break; case TYPE_FLT: u_flt2str(l->f, temp_lhs); break; default: temp_lhs[0] = '\0'; break; } lhs = temp_lhs; } else { lhs = l->s->str; } if (!is_str(r)) { switch (r->type) { case TYPE_INT: u_int2str(r->i, temp_rhs); break; case TYPE_FLT: u_flt2str(r->f, temp_rhs); break; default: temp_rhs[0] = '\0'; break; } rhs = temp_rhs; } else { rhs = r->s->str; } set_str(l, s_new_concat(lhs, rhs)); } static inline rf_int match(rf_val *l, rf_val *r) { // Common case: LHS string, RHS regex if (is_str(l) && is_re(r)) return re_match(l->s->str, s_len(l->s), r->r, 1); char *lhs; size_t len = 0; char temp_lhs[32]; char temp_rhs[32]; if (!is_str(l)) { switch (l->type) { case TYPE_INT: len = u_int2str(l->i, temp_lhs); break; case TYPE_FLT: len = u_flt2str(l->f, temp_lhs); break; default: temp_lhs[0] = '\0'; break; } lhs = temp_lhs; } else { lhs = l->s->str; len = s_len(l->s); } if (!is_re(r)) { rf_re *temp_re; rf_int res; int errcode; int capture = 0; switch (r->type) { case TYPE_INT: u_int2str(r->i, temp_rhs); break; case TYPE_FLT: u_flt2str(r->f, temp_rhs); break; case TYPE_STR: capture = 1; temp_re = re_compile(r->s->str, s_len(r->s), 0, &errcode); goto do_match; default: temp_rhs[0] = '\0'; break; } temp_re = re_compile(temp_rhs, PCRE2_ZERO_TERMINATED, 0, &errcode); do_match: // Check for invalid regex in RHS // TODO treat as literal string in this case? (PCRE2_LITERAL) if (errcode != 100) { PCRE2_UCHAR errstr[0x200]; pcre2_get_error_message(errcode, errstr, 0x200); err((const char *) errstr); } res = re_match(lhs, len, temp_re, capture); re_free(temp_re); return res; } else { return re_match(lhs, len, r->r, 1); } } Z_BINOP(match) { set_int(l, match(l, r)); } Z_BINOP(nmatch) { set_int(l, !match(l, r)); } Z_BINOP(idx) { char temp[32]; switch (l->type) { case TYPE_INT: { u_int2str(l->i, temp); if (is_rng(r)) { set_str(l, s_substr(temp, r->q->from, r->q->to, r->q->itvl)); } else { rf_int r1 = intval(r); rf_int len = (rf_int) strlen(temp); if (r1 < 0) r1 += len; if (r1 > len - 1 || r1 < 0) set_null(l); else set_str(l, s_new(temp + r1, 1)); } break; } case TYPE_FLT: { u_flt2str(l->f, temp); if (is_rng(r)) { set_str(l, s_substr(temp, r->q->from, r->q->to, r->q->itvl)); } else { rf_int r1 = intval(r); rf_int len = (rf_int) strlen(temp); if (r1 < 0) r1 += len; if (r1 > len - 1 || r1 < 0) set_null(l); else set_str(l, s_new(temp + r1, 1)); } break; } case TYPE_STR: { if (is_rng(r)) { l->s = s_substr(l->s->str, r->q->from, r->q->to, r->q->itvl); } else { rf_int r1 = intval(r); rf_int len = (rf_int) s_len(l->s); if (r1 < 0) r1 += len; if (r1 > len - 1 || r1 < 0) set_null(l); else l->s = s_new(&l->s->str[r1], 1); } break; } case TYPE_TAB: *l = *t_lookup(l->t, r, 0); break; default: set_null(l); break; } } static inline void new_iter(rf_val *set) { rf_iter *new = malloc(sizeof(rf_iter)); new->p = iter; iter = new; switch (set->type) { case TYPE_NULL: iter->t = LOOP_NULL; iter->keys = NULL; iter->n = 1; break; case TYPE_FLT: set->i = (rf_int) set->f; // Fall-through case TYPE_INT: iter->keys = NULL; iter->t = LOOP_RNG; iter->st = 0; if (set->i >= 0) { iter->n = set->i + 1; // Inclusive iter->set.itvl = 1; } else { iter->n = -(set->i) + 1; // Inclusive iter->set.itvl = -1; } break; case TYPE_STR: iter->t = LOOP_STR; iter->n = s_len(set->s); iter->keys = NULL; iter->set.str = set->s->str; break; case TYPE_RE: err("cannot iterate over regular expression"); case TYPE_RNG: iter->keys = NULL; iter->t = LOOP_RNG; iter->set.itvl = set->q->itvl; if (iter->set.itvl > 0) iter->on = (set->q->to - set->q->from) + 1; else iter->on = (set->q->from - set->q->to) + 1; if (iter->on <= 0) iter->n = UINT64_MAX; // TODO "Infinite" loop else iter->n = (rf_uint) ceil(fabs(iter->on / (double) iter->set.itvl)); iter->st = set->q->from; break; case TYPE_TAB: iter->t = LOOP_TAB; iter->on = iter->n = t_logical_size(set->t); iter->keys = t_collect_keys(set->t); iter->set.tab = set->t; break; case TYPE_RFN: case TYPE_CFN: err("cannot iterate over function"); default: break; } } static inline void destroy_iter(void) { rf_iter *old = iter; iter = iter->p; if (old->t == LOOP_TAB) { if (!(old->n + 1)) // Loop completed? free(old->keys - old->on); else free(old->keys - (old->on - old->n)); } free(old); } static inline void init_argv(rf_tab *t, rf_int arg0, int rf_argc, char **rf_argv) { t_init(t); for (rf_int i = 0; i < rf_argc; ++i) { rf_val v = (rf_val) { TYPE_STR, .s = s_new(rf_argv[i], strlen(rf_argv[i])) }; rf_int idx = i - arg0; if (idx < 0) ht_insert_val(t->h, &(rf_val){TYPE_INT, .i = idx}, &v); else t_insert_int(t, idx, &v); } } static inline int exec(uint8_t *, rf_val *, rf_stack *, rf_stack *); #define add_user_funcs() \ for (int i = 0; i < e->nf; ++i) { \ if (e->fn[i]->name->hash) { \ ht_insert_str(&globals, e->fn[i]->name, &(rf_val){TYPE_RFN, .fn = e->fn[i]}); \ } \ } // VM entry point/initialization int z_exec(rf_env *e) { ht_init(&globals); iter = NULL; t_init(&fldv); re_register_fldv(&fldv); init_argv(&argv, e->arg0, e->argc, e->argv); ht_insert_cstr(&globals, "arg", &(rf_val){TYPE_TAB, .t = &argv}); l_register_builtins(&globals); // Add user-defined functions to the global hash table add_user_funcs(); return exec(e->main.code->code, e->main.code->k, stack, stack); } // Reentry point for eval() int z_exec_reenter(rf_env *e, rf_stack *fp) { // Add user-defined functions to the global hash table add_user_funcs(); return exec(e->main.code->code, e->main.code->k, fp, fp); } #ifndef COMPUTED_GOTO #ifdef __GNUC__ #define COMPUTED_GOTO #endif #endif // VM interpreter loop static inline int exec(uint8_t *ep, rf_val *k, rf_stack *sp, rf_stack *fp) { if (sp - stack >= VM_STACK_SIZE) err("stack overflow"); rf_stack *retp = sp; // Save original SP rf_val *tp; // Temp pointer register uint8_t *ip = ep; #ifndef COMPUTED_GOTO // Use standard while loop with switch/case if computed goto is // disabled or unavailable #define L(l) case OP_##l: #define BREAK break while (1) { switch (*ip) { #else #define L(l) L_##l: #define BREAK DISPATCH() #define DISPATCH() goto *dispatch_labels[*ip] static void *dispatch_labels[] = { #define OPCODE(x,y,z) &&L_##x #include "opcodes.h" }; DISPATCH(); #endif // Unconditional jumps #define j8() (ip += (int8_t) ip[1]) #define j16() (ip += (int16_t) ((ip[1] << 8) + ip[2])) L(JMP8) j8(); BREAK; L(JMP16) j16(); BREAK; // Conditional jumps (pop stack unconditionally) #define jc8(x) (x ? j8() : (ip += 2)); --sp #define jc16(x) (x ? j16() : (ip += 3)); --sp L(JNZ8) jc8(test(&sp[-1].v)); BREAK; L(JNZ16) jc16(test(&sp[-1].v)); BREAK; L(JZ8) jc8(!test(&sp[-1].v)); BREAK; L(JZ16) jc16(!test(&sp[-1].v)); BREAK; // Conditional jumps (pop stack if jump not taken) #define xjc8(x) if (x) j8(); else {--sp; ip += 2;} #define xjc16(x) if (x) j16(); else {--sp; ip += 3;} L(XJNZ8) xjc8(test(&sp[-1].v)); BREAK; L(XJNZ16) xjc16(test(&sp[-1].v)); BREAK; L(XJZ8) xjc8(!test(&sp[-1].v)); BREAK; L(XJZ16) xjc16(!test(&sp[-1].v)); BREAK; // Initialize/cycle current iterator L(LOOP8) L(LOOP16) { int jmp16 = *ip == OP_LOOP16; if (!iter->n--) { if (jmp16) ip += 3; else ip += 2; BREAK; } switch (iter->t) { case LOOP_RNG: if (is_null(iter->v)) *iter->v = (rf_val) {TYPE_INT, .i = iter->st}; else iter->v->i += iter->set.itvl; break; case LOOP_STR: if (iter->k != NULL) { if (is_null(iter->k)) { set_int(iter->k, 0); } else { iter->k->i += 1; } } if (!is_null(iter->v)) { iter->v->s = s_new(iter->set.str++, 1); } else { *iter->v = (rf_val) {TYPE_STR, .s = s_new(iter->set.str++, 1)}; } break; case LOOP_TAB: if (iter->k != NULL) { *iter->k = *iter->keys; } *iter->v = *t_lookup(iter->set.tab, iter->keys, 0); iter->keys++; break; case LOOP_NULL: set_null(iter->v); if (iter->k != NULL) { set_null(iter->k); } break; default: break; } // Treat byte(s) following OP_LOOP as unsigned since jumps are always // backward if (jmp16) ip -= (ip[1] << 8) + ip[2]; else ip -= ip[1]; BREAK; } // Destroy the current iterator struct L(POPL) destroy_iter(); ++ip; BREAK; // Create iterator and jump to the corresponding OP_LOOP instruction for // initialization L(ITERV) L(ITERKV) { int k = *ip == OP_ITERKV; new_iter(&sp[-1].v); --sp; set_null(&sp++->v); // Reserve extra stack slot for k,v iterators if (k) { set_null(&sp++->v); iter->k = &sp[-2].v; } else { iter->k = NULL; } iter->v = &sp[-1].v; j16(); BREAK; } // Unary operations // sp[-1].v is assumed to be safe to overwrite #define unop(x) z_##x(&sp[-1].v); ++ip L(LEN) unop(len); BREAK; L(LNOT) unop(lnot); BREAK; L(NEG) unop(neg); BREAK; L(NOT) unop(not); BREAK; L(NUM) unop(num); BREAK; // Standard binary operations // sp[-2].v and sp[-1].v are assumed to be safe to overwrite #define binop(x) z_##x(&sp[-2].v, &sp[-1].v); --sp; ++ip L(ADD) binop(add); BREAK; L(SUB) binop(sub); BREAK; L(MUL) binop(mul); BREAK; L(DIV) binop(div); BREAK; L(MOD) binop(mod); BREAK; L(POW) binop(pow); BREAK; L(AND) binop(and); BREAK; L(OR) binop(or); BREAK; L(XOR) binop(xor); BREAK; L(SHL) binop(shl); BREAK; L(SHR) binop(shr); BREAK; L(EQ) binop(eq); BREAK; L(NE) binop(ne); BREAK; L(GT) binop(gt); BREAK; L(GE) binop(ge); BREAK; L(LT) binop(lt); BREAK; L(LE) binop(le); BREAK; L(CAT) binop(cat); BREAK; L(MATCH) binop(match); BREAK; L(NMATCH) binop(nmatch); BREAK; // Pre-increment/decrement // sp[-1].a is address of some variable's rf_val. // Increment/decrement this value directly and replace the stack element with a // copy of the value. #define pre(x) \ switch (sp[-1].a->type) { \ case TYPE_INT: sp[-1].a->i += x; break; \ case TYPE_FLT: sp[-1].a->f += x; break; \ case TYPE_STR: \ set_flt(sp[-1].a, str2flt(sp[-1].a->s) + x); \ break; \ default: \ set_int(sp[-1].a, x); \ break; \ } \ sp[-1].v = *sp[-1].a; \ ++ip L(PREINC) pre(1); BREAK; L(PREDEC) pre(-1); BREAK; // Post-increment/decrement // sp[-1].a is address of some variable's rf_val. Create a copy of the raw // value, then increment/decrement the rf_val at the given address. Replace the // stack element with the previously made copy and coerce to a numeric value if // needed. #define post(x) \ tp = sp[-1].a; \ sp[-1].v = *tp; \ switch (tp->type) { \ case TYPE_INT: tp->i += x; break; \ case TYPE_FLT: tp->f += x; break; \ case TYPE_STR: \ set_flt(tp, str2flt(tp->s) + x); \ break; \ default: \ set_int(tp, x); \ break; \ } \ unop(num) L(POSTINC) post(1); BREAK; L(POSTDEC) post(-1); BREAK; // Compound assignment operations // sp[-2].a is address of some variable's rf_val. Save the address and place a // copy of the value in sp[-2].v. Perform the binary operation x and assign the // result to the saved address. #define cbinop(x) \ tp = sp[-2].a; \ sp[-2].v = *tp; \ binop(x); \ *tp = sp[-1].v L(ADDX) cbinop(add); BREAK; L(SUBX) cbinop(sub); BREAK; L(MULX) cbinop(mul); BREAK; L(DIVX) cbinop(div); BREAK; L(MODX) cbinop(mod); BREAK; L(CATX) cbinop(cat); BREAK; L(POWX) cbinop(pow); BREAK; L(ANDX) cbinop(and); BREAK; L(ORX) cbinop(or); BREAK; L(SHLX) cbinop(shl); BREAK; L(SHRX) cbinop(shr); BREAK; L(XORX) cbinop(xor); BREAK; // Simple pop operation L(POP) --sp; ++ip; BREAK; // Pop IP+1 values from stack L(POPI) sp -= ip[1]; ip += 2; BREAK; // Push null literal on stack L(NUL) set_null(&sp++->v); ++ip; BREAK; // Push immediate // Assign integer value x to the top of the stack. #define imm(x) set_int(&sp++->v, x) L(IMM8) imm(ip[1]); ip += 2; BREAK; L(IMM16) imm((ip[1]<<8) + ip[2]); ip += 3; BREAK; L(IMM0) imm(0); ++ip; BREAK; L(IMM1) imm(1); ++ip; BREAK; L(IMM2) imm(2); ++ip; BREAK; // Push constant // Copy constant x from code object's constant table to the top of the stack. #define pushk(x) sp++->v = k[(x)] L(CONST) pushk(ip[1]); ip += 2; BREAK; L(CONST0) pushk(0); ++ip; BREAK; L(CONST1) pushk(1); ++ip; BREAK; L(CONST2) pushk(2); ++ip; BREAK; // Push global address // Assign the address of global variable x's rf_val in the globals table. // The lookup will create an entry if needed, accommodating // undeclared/uninitialized variable usage. // Parser signals for this opcode for assignment or pre/post ++/--. #define gbla(x) sp++->a = ht_lookup_str(&globals, k[(x)].s) L(GBLA) gbla(ip[1]); ip += 2; BREAK; L(GBLA0) gbla(0); ++ip; BREAK; L(GBLA1) gbla(1); ++ip; BREAK; L(GBLA2) gbla(2); ++ip; BREAK; // Push global value // Copy the value of global variable x to the top of the stack. // The lookup will create an entry if needed, accommodating // undeclared/uninitialized variable usage. // Parser signals for this opcode to be used when only needing the value, e.g. // arithmetic. #define gblv(x) sp++->v = *ht_lookup_str(&globals, k[(x)].s) L(GBLV) gblv(ip[1]); ip += 2; BREAK; L(GBLV0) gblv(0); ++ip; BREAK; L(GBLV1) gblv(1); ++ip; BREAK; L(GBLV2) gblv(2); ++ip; BREAK; // Push local address // Push the address of FP[x] to the top of the stack. #define lcla(x) sp++->a = &fp[(x)].v L(LCLA) lcla(ip[1]); ip += 2; BREAK; L(LCLA0) lcla(0); ++ip; BREAK; L(LCLA1) lcla(1); ++ip; BREAK; L(LCLA2) lcla(2); ++ip; BREAK; // Push local value // Copy the value of FP[x] to the top of the stack. #define lclv(x) sp++->v = fp[(x)].v L(LCLV) lclv(ip[1]); ip += 2; BREAK; L(LCLV0) lclv(0); ++ip; BREAK; L(LCLV1) lclv(1); ++ip; BREAK; L(LCLV2) lclv(2); ++ip; BREAK; // Tailcalls // Recycle current call frame L(TCALL) { int nargs = ip[1] + 1; if (!is_fn(&sp[-nargs].v)) err("attempt to call non-function value"); if (is_rfn(&sp[-nargs].v)) { sp -= nargs; rf_fn *fn = sp->v.fn; int ar1 = sp - fp - 1; // Current frame's "arity" int ar2 = fn->arity; // Callee's arity // Recycle call frame for (int i = 0; i <= ar2; ++i) { fp[i].v = sp[i].v; } // Increment SP without nullifying slots (preserving values) if number // of arguments exceeds the frame's current "arity" if (nargs-1 > ar1) { sp += (nargs - ar1 - 1); ar1 = nargs - 1; } // In the case of direct recursion and no call frame adjustments needed, // quickly reset IP and dispatch control if (ep == fn->code->code && ar1 == ar2) { ip = ep; BREAK; } // If callee's arity is larger than the current frame, create stack // space and nullify slots if (ar2 > ar1) { while (ar1++ < ar2) set_null(&sp++->v); } // Else, if the current frame is too large for the next call, decrement // SP else if (ar2 < ar1) { sp -= ar1 - ar2; } // Else else, if the size of the call frame is fine, but the user didn't // provide enough arguments, create stack space and nullify slots else if (nargs <= ar2) { while (nargs++ <= ar2) set_null(&sp++->v); } ip = ep = fn->code->code; k = fn->code->k; BREAK; } // Fall-through to OP_CALL for C function calls } // Calling convention // Arguments are pushed in-order following the rf_val containing a pointer to // the function to be called. Caller sets SP and FP to appropriate positions // and cleans up stack afterward. Callee returns from exec() the number of // values to be returned to the caller. L(CALL) { int nargs = ip[1]; if (!is_fn(&sp[-nargs-1].v)) err("attempt to call non-function value"); int arity, nret; // User-defined functions if (is_rfn(&sp[-nargs-1].v)) { rf_fn *fn = sp[-nargs-1].v.fn; arity = fn->arity; // If user called function with too few arguments, nullify stack slots and // increment SP. if (nargs < arity) { for (int i = nargs; i < arity; ++i) { set_null(&sp++->v); } } // If user called function with too many arguments, decrement SP so it // points to the appropriate slot for control transfer. else if (nargs > arity) { sp -= (nargs - arity); } // Pass SP-arity-1 as the FP for the succeeding call frame. Since the // function is already at this location in the stack, the compiler can // reserve the slot to accommodate any references a named function makes // to itself without any other work required from the VM here. This is // completely necessary for local named functions, but globals benefit // as well. nret = exec(fn->code->code, fn->code->k, sp, sp - arity - 1); sp -= arity; // Copy the function's return value to the stack top - this should be // where the caller pushed the original function. sp[-1].v = sp[arity].v; } // Built-in/C functions else { c_fn *fn = sp[-nargs-1].v.cfn; arity = fn->arity; // Most library functions are somewhat variadic; their arity refers to // the minimum number of arguments they require. if (arity && nargs < arity) { // If user called function with too few arguments, nullify stack // slots. for (int i = nargs; i < arity; ++i) { set_null(&sp[i].v); } } // Decrement SP to serve as the FP for the function call. Library // functions assign their own return values to SP-1. sp -= nargs; nret = fn->fn(&sp->v, nargs); } ip += 2; // Nulllify stack slot if callee returns nothing if (!nret) { set_null(&sp[-1].v); } BREAK; } L(RET) return 0; // Caller expects return value to be at its original SP + arity of the function. // "clean up" any created locals by copying the return value to the appropriate // slot. L(RET1) retp->v = sp[-1].v; return 1; // Create a sequential table of x elements from the top of the stack. Leave the // table rf_val on the stack. Tables index at 0 by default. #define new_tab(x) \ tp = v_newtab(x); \ for (int i = (x) - 1; i >= 0; --i) { \ --sp; \ t_insert_int(tp->t, i, &sp->v); \ } \ sp++->v = *tp L(TAB0) new_tab(0); ++ip; BREAK; L(TAB) new_tab(ip[1]); ip += 2; BREAK; L(TABK) new_tab(k[ip[1]].i); ip += 2; BREAK; L(IDXV) for (int i = -ip[1] - 1; i < -1; ++i) { if (sp[i].t <= TYPE_CFN) { z_idx(&sp[i].v, &sp[i+1].v); sp[i+1].v = sp[i].v; continue; } switch (sp[i].a->type) { // Create table if sp[-2].a is an uninitialized variable case TYPE_NULL: *sp[i+1].a = *v_newtab(0); // Fall-through case TYPE_TAB: sp[i+1].v = *t_lookup(sp[i].a->t, &sp[i+1].v, 0); break; // Dereference and call z_idx(). case TYPE_INT: case TYPE_FLT: case TYPE_STR: sp[i].v = *sp[-i].a; z_idx(&sp[i].v, &sp[i+1].v); sp[i+1].v = sp[i].v; break; case TYPE_RFN: case TYPE_CFN: err("attempt to subscript a function"); default: break; } } sp -= ip[1]; sp[-1].v = sp[ip[1] - 1].v; ip += 2; BREAK; L(IDXA) for (int i = -ip[1] - 1; i < -1; ++i) { if (sp[i].t <= TYPE_CFN) tp = &sp[i].v; else tp = sp[i].a; switch (tp->type) { // Create table if sp[i].a is an uninitialized variable case TYPE_NULL: *tp = *v_newtab(0); // Fall-through case TYPE_TAB: sp[i+1].a = t_lookup(tp->t, &sp[i+1].v, 1); break; // IDXA is invalid for all other types default: err("invalid assignment"); } } sp -= ip[1]; sp[-1].a = sp[ip[1] - 1].a; ip += 2; BREAK; // IDXA // Perform the lookup and leave the corresponding element's rf_val address on // the stack. L(IDXA1) // Accomodate OP_IDXA calls when SP-2 is a raw value if (sp[-2].t <= TYPE_CFN) tp = &sp[-2].v; else tp = sp[-2].a; switch (tp->type) { // Create table if sp[-2].a is an uninitialized variable case TYPE_NULL: *tp = *v_newtab(0); // Fall-through case TYPE_TAB: sp[-2].a = t_lookup(tp->t, &sp[-1].v, 1); break; // IDXA is invalid for all other types default: err("invalid assignment"); } --sp; ++ip; BREAK; // IDXV // Perform the lookup and leave a copy of the corresponding element's value on // the stack. L(IDXV1) // All expressions e.g. x[y] are compiled to push the address of the // identifier being subscripted. However OP_IDXV is emitted for all // expressions not requiring the address of the set element to be left on // the stack. In the event the instruction is OP_IDXV and SP-2 contains a // raw value (not a pointer), the high order 64 bits will be the type tag of // the rf_val instead of a memory address. When that happens, defer to // z_idx(). if (sp[-2].t <= TYPE_CFN) { binop(idx); BREAK; } switch (sp[-2].a->type) { // Create table if sp[-2].a is an uninitialized variable case TYPE_NULL: *sp[-2].a = *v_newtab(0); // Fall-through case TYPE_TAB: sp[-2].v = *t_lookup(sp[-2].a->t, &sp[-1].v, 0); --sp; ++ip; break; // Dereference and call z_idx(). case TYPE_INT: case TYPE_FLT: case TYPE_STR: sp[-2].v = *sp[-2].a; binop(idx); break; case TYPE_RFN: case TYPE_CFN: err("attempt to subscript a function"); default: break; } BREAK; // Fast paths for table lookups with string literal keys L(SIDXA) if (sp[-1].t <= TYPE_CFN) tp = &sp[-1].v; else tp = sp[-1].a; switch (tp->type) { // Create table if sp[-2].a is an uninitialized variable case TYPE_NULL: *tp = *v_newtab(0); // Fall-through case TYPE_TAB: sp[-1].a = ht_lookup_val(tp->t->h, &k[ip[1]]); break; default: err("invalid assignment"); } ip += 2; BREAK; L(SIDXV) if (sp[-1].t <= TYPE_CFN) { binop(idx); BREAK; } switch (sp[-1].a->type) { // Create table if sp[-2].a is an uninitialized variable case TYPE_NULL: *sp[-1].a = *v_newtab(0); // Fall-through case TYPE_TAB: sp[-1].v = *ht_lookup_val(sp[-1].a->t->h, &k[ip[1]]); ip += 2; break; default: err("invalid member access (non-table value)"); } BREAK; L(FLDA) sp[-1].a = t_lookup(&fldv, &sp[-1].v, 1); ++ip; BREAK; L(FLDV) sp[-1].v = *t_lookup(&fldv, &sp[-1].v, 0); ++ip; BREAK; // Create a new "range" value. // There are 8 different valid forms of a range; each has their own instruction. // rng: x..y SP[-2]..SP[-1] // rngf: x.. SP[-1]..INT_MAX // rngt: ..y 0..SP[-1] // rnge: .. 0..INT_MAX // srng: x..y:z SP[-3]..SP[-2]:SP[-1] // srngf: x..:z SP[-2]..INT_MAX:SP[-1] // srngt: ..y:z 0..SP[-2]:SP[-1] // srnge: ..:z 0..INT_MAX:SP[-1] // If `z` is not provided, the interval is set to -1 if x > y (downward ranges). // Otherwise, the interval is set to 1 (upward ranges). #define z_range(f,t,i,s) { \ rf_rng *rng = malloc(sizeof(rf_rng)); \ rf_int from = rng->from = (f); \ rf_int to = rng->to = (t); \ rf_int itvl = (i); \ rng->itvl = itvl ? itvl : from > to ? -1 : 1; \ s = (rf_val) {TYPE_RNG, .q = rng}; \ } // x..y L(RNG) z_range(intval(&sp[-2].v), intval(&sp[-1].v), 0, sp[-2].v); --sp; ++ip; BREAK; // x.. L(RNGF) z_range(intval(&sp[-1].v), INT64_MAX, 0, sp[-1].v); ++ip; BREAK; // ..y L(RNGT) z_range(0, intval(&sp[-1].v), 0, sp[-1].v); ++ip; BREAK; // .. L(RNGI) ++sp; z_range(0, INT64_MAX, 0, sp[-1].v); ++ip; BREAK; // x..y:z L(SRNG) z_range(intval(&sp[-3].v), intval(&sp[-2].v), intval(&sp[-1].v), sp[-3].v); sp -= 2; ++ip; BREAK; // x..:z L(SRNGF) z_range(intval(&sp[-2].v), INT64_MAX, intval(&sp[-1].v), sp[-2].v); --sp; ++ip; BREAK; // ..y:z L(SRNGT) z_range(0, intval(&sp[-2].v), intval(&sp[-1].v), sp[-2].v); --sp; ++ip; BREAK; // ..:z L(SRNGI) z_range(0, INT64_MAX, intval(&sp[-1].v), sp[-1].v); ++ip; BREAK; // Simple assignment // copy SP[-1] to *SP[-2] and leave value on stack. L(SET) sp[-2].v = *sp[-2].a = sp[-1].v; --sp; ++ip; BREAK; #ifndef COMPUTED_GOTO } } #endif return 0; }
#! /usr/bin/env bash git remote add gitcafe git@gitcafe.com:bbcallen/ijkplayer.git git remote add oschina git@git.oschina.net:bbcallen/ijkplayer.git git remote add csdn git@code.csdn.net:bbcallen/ijkplayer.git git fetch --all
package org.aksw.rdfunit.sources; import java.util.List; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.aksw.rdfunit.enums.TestAppliesTo; import org.aksw.rdfunit.io.reader.RdfReader; import org.aksw.rdfunit.io.reader.RdfReaderException; import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModelSpec; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Selector; import org.apache.jena.rdf.model.SimpleSelector; import org.apache.jena.rdf.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Dimitris Kontokostas * @since 9/16/13 1:51 PM */ @ToString @EqualsAndHashCode(exclude = {"model", "schemaReader"}) public class SchemaSource implements Source { /** * Constant <code>log</code> */ protected static final Logger log = LoggerFactory.getLogger(SchemaSource.class); protected final SourceConfig sourceConfig; protected final RdfReader schemaReader; @Getter private final String schema; @Getter(lazy = true) private final Model model = initModel(); SchemaSource(SourceConfig sourceConfig, RdfReader schemaReader) { this(sourceConfig, sourceConfig.getUri(), schemaReader); } SchemaSource(SourceConfig sourceConfig, String schema, RdfReader schemaReader) { this.sourceConfig = sourceConfig; this.schema = schema; this.schemaReader = schemaReader; } public SchemaSource(SchemaSource source) { this(source.sourceConfig, source.schema, source.schemaReader); } @Override public String getPrefix() { if (sourceConfig.getPrefix() != "") { return sourceConfig.getPrefix(); } else { Model m = this.getModel(); Selector selector = new SimpleSelector(m.getResource(schema), m.getProperty("http://purl.org/vocab/vann/preferredNamespacePrefix"), (RDFNode) null); List<Statement> prefixStmts = m.listStatements(selector).toList(); if (prefixStmts.size() == 1 && prefixStmts.get(0).getObject().isLiteral()) { return prefixStmts.get(0).getObject().asLiteral().getString(); } log.warn("Prefix not given (-p), neither defined in schema (vann:preferredNamespacePrefix)."); return ""; } } @Override public String getUri() { return sourceConfig.getUri(); } @Override public TestAppliesTo getSourceType() { return TestAppliesTo.Schema; } public SourceConfig getSourceConfig() { return sourceConfig; } /** * lazy loaded via lombok */ private Model initModel() { OntModel m = ModelFactory .createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); try { schemaReader.read(m); } catch (RdfReaderException e) { log.error("Cannot load ontology: {} ", getSchema(), e); } return m; } }
#include "module_adc.h" #include <Module_UID/module_uid.h> #include <QtGui> #include "Module_ADC/adc_form.h" Module_ADC::Module_ADC(QString id, Module_UID *uid) : RobotModule(id) { this->uid=uid; setDefaultValue("i2cAddress", 0x48); setDefaultValue("frequency", 1); setDefaultValue("Vagnd", 0); setDefaultValue("Vref", 5); setDefaultValue("waterFilter",5); setDefaultValue("filtersize",5); timer.moveToThread(this); } Module_ADC::~Module_ADC() { } void Module_ADC::terminate() { QTimer::singleShot(0, &timer, SLOT(stop())); RobotModule::terminate(); } void Module_ADC::init() { // timer.moveToThread(this); connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData())); reset(); } void Module_ADC::reset() { RobotModule::reset(); initFilter(); int freq = 1000/getSettingsValue("frequency").toInt(); if (freq>0) { timer.setInterval(freq); // QTimer::singleShot(0, &timer, SLOT(start())); timer.start(); } else { timer.stop(); // QTimer::singleShot(0, &timer, SLOT(stop())); } if (!getSettingsValue("enabled").toBool()) return; } void Module_ADC::refreshData() { if (!getSettingsValue("enabled").toBool()) return; float value; if (readChannel(0, &value)) addData("channel0",value); if (readChannel(1, &value)) addData("channel1",value); if (readChannel(2, &value)) addData("channel2",value); if (readChannel(3, &value)) addData("channel3",value); } QList<RobotModule*> Module_ADC::getDependencies() { QList<RobotModule*> ret; ret.append(uid); return ret; } QWidget* Module_ADC::createView(QWidget* parent) { return new ADC_Form(this, parent); } void Module_ADC::initFilter() { waterFilter.clear(); voltage1.clear(); voltage2.clear(); voltage3.clear(); for(int i = 0; i < getSettingsValue("filtersize").toInt();i++) { waterFilter.append(5.0); voltage1.append(5.0); voltage2.append(5.0); voltage3.append(5.0); } } void Module_ADC::doHealthCheck() { if(waterFilter.size() == 0) initFilter(); /*there are two adc converters installed, but only adc0 * checks for voltage and water */ if(this->getId() == "adc0") { /* check for water and voltage level */ waterFilter.pop_front(); waterFilter.append(getDataValue("channel0").toFloat()); voltage1.pop_front(); voltage2.pop_front(); voltage3.pop_front(); voltage1.append(getDataValue("channel1").toFloat()); voltage2.append(getDataValue("channel2").toFloat()); voltage3.append(getDataValue("channel3").toFloat()); float med1 = 0.0; float med2 = 0.0; float med3 = 0.0; float med = 0.0; for(int i = 0; i < waterFilter.size(); i++) { med = med + waterFilter.at(i); med1 = med1 + voltage1.at(i); med2 = med2 + voltage2.at(i); med3 = med3 + voltage3.at(i); } med = med / waterFilter.size(); med1 = med1 / waterFilter.size(); med2 = med2 / waterFilter.size(); med3 = med3 / waterFilter.size(); if(med < 2.1) { emit emergencyStop(); setHealthToSick("Water Inside!"); } if(med1 < 3.5 || med2 < 3.5 || med3 < 3.5) { emit emergencyStop(); setHealthToSick("low voltage"); } else setHealthToOk(); addData("Mchannel0m",med); addData("Mchannel1m",med1); addData("Mchannel2m",med2); addData("Mchannel3m",med3); } } bool Module_ADC::readChannel(int channel, float *value) { unsigned char address = getSettingsValue("i2cAddress").toInt(); float Vref = getSettingsValue("Vref").toFloat(); float Vagnd = getSettingsValue("Vagnd").toFloat(); char readBuffer[2]; if (!uid->I2C_ReadRegisters(address, channel, 2, readBuffer)) { setHealthToSick(uid->getLastError()); return false; } *value = Vagnd + (Vref-Vagnd)/256*((unsigned char)readBuffer[1]); return true; }
require 'sinatra/base' module Http module Whois class Base < Sinatra::Base configure do disable :method_override disable :static end before do content_type 'application/json; charset=utf-8' end not_found do JSON.pretty_generate(error: 'Resource not found.') end end end end
import { Card, Col, Row } from 'antd' import { IconCheckmark, IconRadioButtonUnchecked } from 'lib/components/icons' import React, { useState } from 'react' import './Experiment.scss' export function ExperimentWorkflow(): JSX.Element { const [workflowValidateStepCompleted, setWorkflowValidateStepCompleted] = useState(false) const [workflowLaunchStepCompleted, setWorkflowLaunchStepCompleted] = useState(false) return ( <Card className="experiment-workflow" title={<span className="card-secondary">Experiment workflow</span>}> <Row> <Col className="exp-workflow-step step-completed full-width"> <Row align="middle"> {true ? ( <IconCheckmark style={{ color: 'var(--primary)', fontSize: 24 }} /> ) : ( <IconRadioButtonUnchecked /> )} <b className="ml-05">Create experiment</b> </Row> <div className="ml-2">Set variants, select participants, and add secondary metrics</div> </Col> </Row> <Row> <Col className={`full-width exp-workflow-step ${workflowValidateStepCompleted ? 'step-completed' : ''}`} onClick={() => setWorkflowValidateStepCompleted(!workflowValidateStepCompleted)} > <Row align="middle"> {workflowValidateStepCompleted ? ( <IconCheckmark style={{ color: 'var(--primary)', fontSize: 24 }} /> ) : ( <IconRadioButtonUnchecked /> )} <b className="ml-05">Validate experiment</b> </Row> <div className="ml-2"> Once you've written your code, it's a good idea to test that each variant behaves as you'd expect. </div> </Col> </Row> <Row> <Col className={`full-width exp-workflow-step ${workflowLaunchStepCompleted ? 'step-completed' : ''}`} onClick={() => setWorkflowLaunchStepCompleted(!workflowLaunchStepCompleted)} > <Row align="middle"> {workflowLaunchStepCompleted ? ( <IconCheckmark style={{ color: 'var(--primary)', fontSize: 24 }} /> ) : ( <IconRadioButtonUnchecked /> )} <b className="ml-05">Launch experiment</b> </Row> <div className="ml-2"> Run your experiment, monitor results, and decide when to terminate your experiment. </div> </Col> </Row> </Card> ) }
<?php //usermodel类 class userModel extends Model{ public $table = 'mm_user'; public $key = 'user_id'; }
export 'slides/agenda_slide.dart'; export 'slides/everything_is_a_widget_slide.dart'; export 'slides/first_steps.dart'; export 'slides/set_up_slide.dart'; export 'slides/title_slide.dart'; export 'slides/what_is_flutter_slide.dart';
CREATE PROCEDURE [dbo].[dnn_AddSearchCommonWord] @CommonWord nvarchar(255), @Locale nvarchar(10) AS INSERT INTO dbo.dnn_SearchCommonWords ( [CommonWord], [Locale] ) VALUES ( @CommonWord, @Locale ) select SCOPE_IDENTITY()
import defaultTheme from './default'; export const themes = { default: defaultTheme, };
using Mocking Mocking.activate() using CloudWatchLogs using CloudWatchLogs: MAX_EVENT_SIZE import AWSCore import AWSCore.Services: logs, sts using AWSCore: AWSConfig, aws_config, AWSCredentials, AWSException using Dates using EzXML using HTTP using Printf using Memento using Memento.TestUtils using Test using TimeZones using UUIDs const LOGGER = getlogger(CloudWatchLogs) function assume_role(config::AWSConfig, role_arn::AbstractString; kwargs...) response = sts( config, "AssumeRole"; RoleArn=role_arn, RoleSessionName=session_name(), kwargs... ) response_creds = response["Credentials"] response_user = response["AssumedRoleUser"] AWSCredentials( response_creds["AccessKeyId"], response_creds["SecretAccessKey"], response_creds["SessionToken"], response_user["Arn"], ) end function session_name() user = get(ENV, "USER", "unknown") location = gethostname() name = "$user@$location" ts = string(round(Int64, time())) # RoleSessionName must be no more than 64 characters max_name_length = 64 - length(ts) - 1 if length(name) > max_name_length name = name[1:max_name_length-3] * "..." end return "$name-$ts" end function stack_output(config::AWSConfig, stack_name::AbstractString) outputs = Dict{String, String}() # https://github.com/JuliaCloud/AWSCore.jl/issues/41 response = AWSCore.service_query( config; service="cloudformation", version="2010-05-15", operation="DescribeStacks", args=[:StackName=>stack_name], return_raw=true, ) xml = EzXML.root(EzXML.parsexml(response)) ns = EzXML.namespace(xml) outputs_xml = findall("//ns:Stacks/ns:member[1]/ns:Outputs/ns:member", xml, ["ns"=>ns]) for output_xml in outputs_xml key = string(findfirst("//ns:OutputKey/text()", output_xml, ["ns"=>ns])) val = string(findfirst("//ns:OutputValue/text()", output_xml, ["ns"=>ns])) outputs[key] = val end return outputs end @testset "CloudWatchLogs.jl" begin include("event.jl") include("mocked_aws.jl") include("online.jl") end
# Copyright 2020 The UniqueRandomizer Authors. # # 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. # Lint as: python3 """This implementation of UniqueRandomizer is simple for educational purposes. This implementation is designed to match the pseudocode in the UniqueRandomizer paper. Compared to the better implementation in unique_randomizer.py, the bare-bones implementation in this file lacks: * Efficiency tricks, such as storing unsampled probability masses as a single numpy array * Some useful functions, such as computing the fraction of the space sampled * The Randomizer -> UniqueRandomizer/NormalRandomizer object hierarchy * UniqueRandomizer with SBS for batching """ from typing import List, Optional import numpy as np def _log_subtract(x: float, y: float) -> float: """Returns log(exp(x) - exp(y)), or negative infinity if x <= y.""" # Inspired by https://stackoverflow.com/questions/778047. return x + np.log1p(-np.exp(np.minimum(y - x, 0))) def _sample_log_distribution(log_distribution: List[float]) -> int: """Samples from an unnormalized probability distribution in log space.""" # A slower but more numerically stable solution is discussed at # https://stats.stackexchange.com/questions/64081. However, we expect that # as the randomizer runs, the probability distribution at each node should # not be skewed significantly more than the initial provided distribution, # since we will sample more frequently from high-probability choices until # the probabilities "even out". unnormalized = np.exp(log_distribution - np.max(log_distribution)) distribution = unnormalized / np.sum(unnormalized) return int(np.random.choice(np.arange(len(distribution)), p=distribution)) class _TrieNode(object): """A trie node for UniqueRandomizer. Attributes: parent: The _TrieNode parent of this node, or None if this node is the root. children: A list of _TrieNode children. The list will be None if this node has never sampled a child yet. The list will be empty if this node is a leaf. unsampled_log_mass: The current unsampled log probability mass at this node. """ def __init__(self, parent: Optional['_TrieNode'], unsampled_log_mass: float) -> None: """Initializes a _TrieNode.""" self.parent = parent self.children = None self.unsampled_log_mass = unsampled_log_mass def _node_exhausted(node: _TrieNode) -> bool: """Returns whether all of the mass at this node has been sampled.""" if node.children == []: # Distinguish [] and None. pylint: disable=g-explicit-bool-comparison return True # This node is a leaf. if node.children is None: return False # This node is not a leaf but has never been sampled from. return all(child.unsampled_log_mass == np.NINF for child in node.children) class UniqueRandomizer(object): """Samples unique sequences of discrete random choices. When using a UniqueRandomizer object to provide randomness, the client algorithm must be deterministic and behave identically when given a constant sequence of choices. When a sequence of choices is complete, the client algorithm must call `mark_sequence_complete()`. This will update the internal data so that the next sampled choices form a new sequence, which is guaranteed to be different from previous complete sequences. Choices returned by a UniqueRandomizer object respect the initial probability distributions provided by the client algorithm, conditioned on the constraint that a complete sequence of choices cannot be sampled more than once. `sample_distribution()` returns an int in the range [0, num_choices), raising a ValueError if all possible sequences of choices have already been sampled. """ def __init__(self) -> None: """Initializes a UniqueRandomizer object.""" self.root_node = _TrieNode(None, 0.0) self.current_node = self.root_node def sample_distribution(self, distribution: List[float]) -> int: """Samples from a given probability distribution.""" if _node_exhausted(self.current_node): raise ValueError('This node has been completely sampled already.') current = self.current_node if not current.children: # This is the first sample from the current node. Set up its children. # Note that the current node's unsampled_log_mass is still the initial # log probability mass, since the node has never been sampled from before. current.children = [ _TrieNode(parent=current, unsampled_log_mass=float(log_mass)) for log_mass in np.log(distribution) + current.unsampled_log_mass] child_index = _sample_log_distribution([child.unsampled_log_mass for child in current.children]) self.current_node = current.children[child_index] return child_index def mark_sequence_complete(self) -> float: """Ends a sequence of choices and returns its log probability.""" self.current_node.children = [] # This marks the current node as a leaf. # Update unsampled log masses for all ancestors. sampled_log_mass = self.current_node.unsampled_log_mass node = self.current_node while node: if _node_exhausted(node): node.unsampled_log_mass = np.NINF else: node.unsampled_log_mass = _log_subtract(node.unsampled_log_mass, sampled_log_mass) node = node.parent self.current_node = self.root_node return sampled_log_mass def exhausted(self) -> bool: """Returns whether all possible sequences of choices have been sampled.""" return _node_exhausted(self.root_node)
@extends('layouts.admin.panel') @section('breadcrumb') <div class="ui breadcrumb"> <a class="section" href="{{ route('Laralum::blogs') }}">{{ trans('laralum.blogs_title') }}</a> <i class="right angle icon divider"></i> <a class="section" href="{{ route('Laralum::blogs_posts', ['id' => $row->post->blog->id]) }}">{{ trans('laralum.blogs_posts_title') }}</a> <i class="right angle icon divider"></i> <a class="section" href="{{ route('Laralum::posts', ['id' => $row->post->blog->id]) }}">{{ $row->post->title }}</a> <i class="right angle icon divider"></i> <div class="active section">{{ trans('laralum.comments_edit_title') }}</div> </div> @endsection @section('title', trans('laralum.comments_edit_title')) @section('icon', "edit") @section('subtitle', trans('laralum.comments_edit_subtitle', ['id' => $row->id])) @section('content') <div class="ui doubling stackable grid container"> <div class="three wide column"></div> <div class="ten wide column"> <div class="ui very padded segment"> <form class="ui form" method="POST"> {{ csrf_field() }} @include('laralum/forms/master') <br> <button type="submit" class="ui {{ Laralum::settings()->button_color }} submit button">{{ trans('laralum.submit') }}</button> </form> </div> <br> </div> <div class="three wide column"></div> </div> @endsection
var colors = [ "blue", "white", "green", "navy", "pink", "purple", "orange", "yellow", "black", "brown" ]; var randomColor = colors[Math.floor(Math.random() * colors.length)];
use crate::boolean::Boolean; use crate::eq::EqGadget; use crate::fields::fp::FpVar; use crate::fields::FieldVar; use ark_ff::PrimeField; use ark_relations::r1cs::SynthesisError; use ark_std::vec::Vec; pub mod vanishing_poly; #[derive(Clone, Debug)] /// Defines an evaluation domain over a prime field. The domain is a coset of size `1<<dim`. /// /// Native code corresponds to `ark-poly::univariate::domain::radix2`, but `ark-poly` only supports /// subgroup for now. /// // TODO: support cosets in `ark-poly`. pub struct Radix2DomainVar<F: PrimeField> { /// generator of subgroup g pub gen: F, /// index of the quotient group (i.e. the `offset`) offset: FpVar<F>, /// dimension of evaluation domain, which is log2(size of coset) pub dim: u64, } impl<F: PrimeField> Radix2DomainVar<F> { /// Construct an evaluation domain with the given offset. pub fn new(gen: F, dimension: u64, offset: FpVar<F>) -> Result<Self, SynthesisError> { offset.enforce_not_equal(&FpVar::zero())?; Ok(Self { gen, offset, dim: dimension, }) } /// What is the offset of `self`? pub fn offset(&self) -> &FpVar<F> { &self.offset } } impl<F: PrimeField> EqGadget<F> for Radix2DomainVar<F> { fn is_eq(&self, other: &Self) -> Result<Boolean<F>, SynthesisError> { if self.gen != other.gen || self.dim != other.dim { Ok(Boolean::constant(false)) } else { self.offset.is_eq(&other.offset) } } } impl<F: PrimeField> Radix2DomainVar<F> { /// order of the domain pub fn order(&self) -> usize { 1 << self.dim } /// Returns offset, offset*g, offset*g^2, ..., offset*g^{coset_size} pub fn elements(&self) -> Vec<FpVar<F>> { let mut result = Vec::new(); result.push(self.offset.clone()); for _ in 1..(1 << self.dim) { let new_element = result.last().unwrap() * self.gen; result.push(new_element); } result } /// Size of the domain pub fn size(&self) -> u64 { 1 << self.dim } /// For domain `h<g>` with dimension `n`, `position` represented by `query_pos` in big endian form, /// returns all points of `h*g^{position}<g^{2^{n-coset_dim}}>`. The result is the query coset at index `query_pos` /// for the FRI protocol. /// /// # Panics /// This function panics when `query_pos.len() != coset_dim` or `query_pos.len() != self.dim`. pub fn query_position_to_coset_elements( &self, query_pos: &[Boolean<F>], coset_dim: u64, ) -> Result<Vec<FpVar<F>>, SynthesisError> { Ok(self .query_position_to_coset(query_pos, coset_dim)? .elements()) } /// For domain `h<g>` with dimension `n`, `position` represented by `query_pos` in big endian form, /// returns all points of `h*g^{position}<g^{n-query_pos.len()}>` /// /// # Panics /// This function panics when `query_pos.len() < log2_num_cosets`. pub fn query_position_to_coset( &self, query_pos: &[Boolean<F>], coset_dim: u64, ) -> Result<Self, SynthesisError> { let coset_index = truncate_to_coset_index(query_pos, self.dim, coset_dim); let offset_var = &self.offset * FpVar::Constant(self.gen).pow_le(&coset_index)?; Ok(Self { gen: self.gen.pow(&[1 << (self.dim - coset_dim)]), // distance between coset offset: offset_var, dim: coset_dim, }) } } fn truncate_to_coset_index<F: PrimeField>( query_pos: &[Boolean<F>], codeword_dim: u64, coset_dim: u64, ) -> Vec<Boolean<F>> { let log2_num_cosets = (codeword_dim - coset_dim) as usize; assert!(query_pos.len() >= log2_num_cosets); query_pos[0..log2_num_cosets].to_vec() } #[cfg(test)] mod tests { use crate::prelude::*; use ark_ff::PrimeField; use ark_relations::r1cs::ConstraintSystem; use ark_std::{rand::Rng, test_rng}; use crate::{alloc::AllocVar, fields::fp::FpVar, poly::domain::Radix2DomainVar, R1CSVar}; fn test_query_coset_template<F: PrimeField>() { const COSET_DIM: u64 = 7; const COSET_SIZE: u64 = 1 << COSET_DIM; const LOCALIZATION: u64 = 3; let cs = ConstraintSystem::new_ref(); let mut rng = test_rng(); let gen = F::get_root_of_unity(COSET_SIZE).unwrap(); let offset = F::rand(&mut rng); let offset_var = FpVar::new_witness(cs.clone(), || Ok(offset)).unwrap(); let domain = Radix2DomainVar::new(gen, COSET_DIM, offset_var).unwrap(); let num_cosets = 1 << (COSET_DIM - LOCALIZATION); let coset_index = rng.gen_range(0..num_cosets); let coset_index_var = UInt32::new_witness(cs.clone(), || Ok(coset_index)) .unwrap() .to_bits_le() .into_iter() .take(COSET_DIM as usize) .collect::<Vec<_>>(); let elements_actual = domain .query_position_to_coset(&coset_index_var, LOCALIZATION) .unwrap() .elements(); let elements_expected = domain .elements() .into_iter() .skip(coset_index as usize) .step_by(1 << (COSET_DIM - LOCALIZATION)) .collect::<Vec<_>>(); assert_eq!(elements_expected.len(), elements_actual.len()); elements_expected .into_iter() .zip(elements_actual.into_iter()) .for_each(|(left, right)| { assert_eq!(left.value().unwrap(), right.value().unwrap()); }); } #[test] fn test_on_bls12_381() { test_query_coset_template::<ark_bls12_381::Fr>(); } #[test] fn test_on_bls12_377() { test_query_coset_template::<ark_bls12_377::Fr>(); } }
<div class="a2a_kit"> <a class="a2a_button_facebook"> <img src="{{asset('image/social/facebook.png')}}" border="0" alt="Facebook" width="24" height="24"/> </a> <a class="a2a_button_twitter"> <img src="{{asset('image/social/twitter.png')}}" border="0" alt="Twitter" width="24" height="24"/> </a> <a class="a2a_button_google_plus"> <img src="{{asset('image/social/gplus.png')}}" border="0" alt="Google Plus" width="24" height="24"/> </a> <a class="a2a_button_youtube"> <img src="{{asset('image/social/youtube.png')}}" border="0" alt="Youtube" width="24" height="24"/> </a> <a class="a2a_button_email"> <img src="{{asset('image/social/mail2.png')}}" border="0" alt="Mail" width="24" height="24"/> </a> <a class="a2a_dd" href="https://www.addtoany.com/share"> <img src="{{asset('image/social/addthis.png')}}" border="0" alt="Addtoany" width="24" height="24"/> </a> </div>
# Runs a `gcardvault sync`. # # In "copy" mode, downloads and saves all the user's # contacts from Google Contacts. # # In "sync" mode, downloads/saves all contacts, and removes # any contacts on disk that are not longer available # in Google. function cmd_google_contacts { google_username=${1:?google_username arg required} app_slug=google_contacts user_slug=${google_username//[^[:alnum:]]/_} user_confd=${BACKUPCONFD}/gcardvault/${user_slug} user_backupd=${BACKUPDATAD}/${app_slug}/${user_slug} flags="" [ ! -z "$GOOGLE_OAUTH_CLIENT_ID" ] && flags+=" --client-id ${GOOGLE_OAUTH_CLIENT_ID}" [ ! -z "$GOOGLE_OAUTH_CLIENT_SECRET" ] && flags+=" --client-secret ${GOOGLE_OAUTH_CLIENT_SECRET}" [ "${mode}" == "sync" ] && flags+=" --clean" echo "Using config at ${user_confd}" echo "Backing up to ${user_backupd}" _run_gcardvault sync "${google_username}" ${flags} }
#![deny(rust_2018_idioms, warnings)] #![deny(clippy::all, clippy::pedantic)] pub mod race { pub struct LazyBox<T, F = fn() -> T> { cell: once_cell::race::OnceBox<T>, init: F, } impl<T, F> LazyBox<T, F> { pub const fn new(init: F) -> Self { LazyBox { cell: once_cell::race::OnceBox::<T>::new(), init, } } } impl<T, F> std::ops::Deref for LazyBox<T, F> where F: Fn() -> T { type Target = T; fn deref(&self) -> &Self::Target { self.cell.get_or_init(|| Box::new((self.init)())) } } }
var app = angular.module("springDemo",[]); app.controller("AppCtrl", function($scope, $http){ $scope.statistics = []; $http({ method: 'GET', url: 'http://localhost:9200/pop_nouns/_search?size=40&sort=_id&pretty=true&q=*:*' }).then(function (success){ $scope.statistics = success.data; }); });
#include "truckitem.h" TruckItem::TruckItem(QObject *parent) : QObject(parent) { truckImg.load("/image/truck.png"); setQuantity(0); } TruckItem::TruckItem(QString _taskName, int _quantity, QObject *parent):QObject(parent){ taskName=_taskName; setQuantity(_quantity); truckImg.load(":/image/truck.png"); } QRectF TruckItem::boundingRect()const{ return QRectF(0,0,110,60); } void TruckItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){ painter->setBrush(QBrush(QColor(139,21,39))); painter->drawPixmap(0,14,110,46,truckImg); painter->drawText(36,15,taskName+QString(":")+QString::number(m_quantity>0?m_quantity:0)); //we set 10px per quantity if(m_quantity>0) painter->drawRect(32,18,m_quantity*10,27); } void TruckItem::setQuantity(float _quantity){ m_quantity=_quantity; update(); } float TruckItem::quantity()const{ return m_quantity; }
import 'dart:ui'; import 'package:get/get.dart'; import 'DateFormatter.dart'; import 'en_US.dart'; import 'fa_IR.dart'; //AppTranslation.dart class AppTranslation extends Translations { AppTranslation(){ _setupDateParser(); } // static final locale = Locale('en', 'US'); static final locale = Locale('fa', 'IR'); static final fallbackLocale = Locale('en', 'US'); @override Map<String, Map<String, String>> get keys => { 'en_US':en_US, 'fa_IR':fa_IR, }; _setupDateParser(){ DateFormatter.setup(keys.keys.toList()); } }
# frozen_string_literal: true class StuckAppealsChecker < DataIntegrityChecker def call return unless stuck_appeals.count > 0 add_to_report "Stuck Appeals: #{stuck_appeals.count} reported by AppealsWithNoTasksOrAllTasksOnHoldQuery" end private def stuck_appeals @stuck_appeals ||= AppealsWithNoTasksOrAllTasksOnHoldQuery.new.call end end
from django.core.validators import MinValueValidator from django.db import models from operator_api.models import CleanModel, MutexModel from decimal import Decimal class EthereumTransactionAttempt(CleanModel, MutexModel): transaction = models.ForeignKey( to='EthereumTransaction', on_delete=models.PROTECT) block = models.BigIntegerField() gas_price = models.DecimalField( max_digits=80, decimal_places=0, validators=[MinValueValidator(Decimal('0'))]) signed_attempt = models.TextField() hash = models.CharField( max_length=64, unique=True) mined = models.BigIntegerField( blank=True, null=True) confirmed = models.BooleanField( default=False)
module QuadOsc export quadosc include("SeriesAccelerations.jl") using .SeriesAccelerations using QuadGK @doc raw""" quadosc(fn, a, Inf, fnzeros; ...) Integrate the function `fn(x)` from `a` to `Inf`. The function `fnzeros(n)` takes an integer `n` and is such that `fn(fnzeros(n)) == 0`. The algorithm works by integrating between successive zeros, and accelerating the alternating series. The argument `pren` is the number of intervals to integrate before applying the series acceleration. `atol` and `rtol` specify the absolute and relative tolerances for determining convergence. `order` is passed on to `quadgk()` of the [QuadGK](https://github.com/JuliaMath/QuadGK.jl) package. `nconvergences` is the number of iterations before convergence is declared. See `?QuadOsc.accel_cohen_villegas_zagier` for details on the series acceleration. """ function quadosc(f::Function, a::Number, b::Number, zerosf::Function; pren=2, atol=zero(Float64), rtol=sqrt(eps(Float64)), order=7, #nconvergences=ceil(Int,-1.31*log10(rtol)), #accelerator=accel_cohen_villegas_zagier) nconvergences=5, accelerator=accel_wynn_eps) @assert b == Inf T = Float64 i1 = findfirst(n -> zerosf(n) - a >= 0, 1:typemax(Int)) z1 = zerosf(i1) Ipre, Epre = quadgk(f, a, z1; atol=atol, rtol=rtol, order=order) z0 = z1 for i=1:pren i1 += 1 z1 = zerosf(i1) I, E = quadgk(f, z0, z1; atol=atol, rtol=rtol, order=order) Ipre += I Epre += E z0 = z1 end I = T(0) oldI = T(0) ak = T[] ek = T[] while nconvergences > 0 i1 += 1 z1 = zerosf(i1) I, E = quadgk(f, z0, z1; atol=atol, rtol=rtol) push!(ak, I) push!(ek, E) z0 = z1 I = accelerator(ak) adiff = abs(I - oldI) rdiff = adiff * 2 / abs(I + oldI) if adiff <= atol || rdiff <= rtol nconvergences -= 1 end oldI = I end I = Ipre + I E = Epre + abs(accelerator(ek)) return I, E end end # module # vim: set sw=4 et sts=4 :
INCLUDE 'vibAnalysisMod.f03' Program unitTest ! ! This program is a unit test program for various sub-programs being written ! for the vibrational analysis program I'm testing. ! ! -H. P. Hratchian, 2019. ! ! ! USE Connections ! use VibAnalysisMod use mqc_general use mqc_gaussian use mqc_algebra2 use iso_fortran_env ! ! Variable Declarations ! implicit none integer(kind=int64)::nDim real(kind=real64),dimension(:),allocatable::eVals real(kind=real64),dimension(:,:),allocatable::mat,eVecs ! ! Format Statements ! 1000 Format(1x,'Enter z.') 1010 Format(3x,'Matrix File: ',A,/) 1100 Format(1x,'nAtoms=',I4) ! ! write(IOut,1000) nDim = 3 Allocate(mat(nDim,nDim),eVals(nDim),eVecs(nDim,nDim)) mat(1,1) = 1 mat(2,1) = -3 mat(3,1) = 3 mat(2,2) = 1 mat(3,2) = 2 mat(3,3) = -4 mat(1,2) = mat(2,1) mat(1,3) = mat(3,1) mat(2,3) = mat(3,2) call mqc_print(iOut,mat,header='mat') call mySVD(iOut,nDim,mat,eVals,eVecs) call mqc_print(iOut,mat,header='AFTER mySVD, mat') call mqc_print(iOut,eVals,header='EigenValues') call mqc_print(iOut,eVecs,header='EigenVectors') ! 999 Continue write(iOut,*)' END OF unitTest' end program unitTest
<?php Load::lib('phpmailer/class.phpmailer'); Load::lib('phpmailer/class.smtp'); class Correos { protected $_mail = NULL; public function __construct() { $this->_mail = new PHPMailer(); $this->_mail->IsSMTP(); $this->_mail->SMTPAuth = TRUE; $this->_mail->SMTPSecure = 'ssl'; $this->_mail->Host = "smtp.gmail.com"; $this->_mail->Port = 465; $this->_mail->Username = "";//escribir el correo $this->_mail->Password = "";//escribir la clave $this->_mail->FROM = ""; //escribir el remitente $this->_mail->FromName = "Manuel Aguirre"; } /** * Envia un correo de registro exitoso al usuario. * * @param Usuarios $usuario * @return boolean */ public function enviarRegistro(Usuarios $usuario) { /*$mensaje = "Felicidades tu cuenta en " . Config::get('config.application.name'); $mensaje .= " ha sido creada Exitosamente...!!! "; $mensaje .= "<ul><li>Usuario: " . h($data['login']) . "</li>"; $mensaje .= "<li>Contraseña: " . h($data['clave']) . "</li></ul>"; $mensaje .= "<p>Para activar tu cuenta visita el siguiente link: "; $mensaje .= Html::link("registro/activar/{$data['id']}/{$data['hash']}", $data['hash']); $this->_mail->Subject = "Tu cuenta ha sido creada con exito - " . Config::get('config.application.name'); $this->_mail->AltBody = strip_tags($mensaje); $this->_mail->MsgHTML($mensaje); $this->_mail->IsHTML(TRUE); $this->_mail->AddAddress($data['email'], $data['nombres']); return $this->_enviar();*/ } protected function _enviar(){ ob_start(); $res = $this->_mail->Send(); ob_clean(); return $res; } }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class ChatModel extends CI_Model{ function __construct() { parent::__construct(); $this->load->library("Utilerias"); } private function getPersonasDeProyecto($id_proyecto) { $r = $this->db->select("p.id_persona,p.paterno,p.materno,p.nombre,p.email,p.avatar")-> from("personas as p")-> join("proyectos_personas as pp","p.id_persona=pp.id_persona")-> where("pp.id_proyecto",$id_proyecto)-> where("p.id_persona <> ".$this->session->id_persona)-> get(); if($r) { $d = $r->result_array(); $data = $d;//$this->utilerias->utf8Encode($d); return $data; }else{ return array(); } } function listarChats($id_proyecto) { $personas = $this->getPersonasDeProyecto($id_proyecto); return $personas; } }
<?php namespace GqAus\CourseBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * UpsellQual */ class UpsellQual { /** * @var boolean */ private $prio; /** * @var integer */ private $id; /** * @var \GqAus\CourseBundle\Entity\Courses */ private $qual; /** * @var \GqAus\CourseBundle\Entity\Course */ private $related; /** * Set prio * * @param boolean $prio * @return UpsellQual */ public function setPrio($prio) { $this->prio = $prio; return $this; } /** * Get prio * * @return boolean */ public function getPrio() { return $this->prio; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set qual * * @param \GqAus\CourseBundle\Entity\Courses $qual * @return UpsellQual */ public function setQual(\GqAus\CourseBundle\Entity\Courses $qual = null) { $this->qual = $qual; return $this; } /** * Get qual * * @return \GqAus\CourseBundle\Entity\Courses */ public function getQual() { return $this->qual; } /** * Set related * * @param \GqAus\CourseBundle\Entity\Course $related * @return UpsellQual */ public function setRelated(\GqAus\CourseBundle\Entity\Course $related = null) { $this->related = $related; return $this; } /** * Get related * * @return \GqAus\CourseBundle\Entity\Course */ public function getRelated() { return $this->related; } }
<?php declare(strict_types=1); namespace DelayedJobs\Test\TestCase\Shell; use Cake\ORM\Entity; use Cake\TestSuite\TestCase; use DelayedJobs\Model\Table\DelayedJobsTable; use Fabricate\Fabricate; /** * Class WorkerShellTest * * @coversDefaultClass DelayedJobs\Shell\WorkerShell */ class WorkerShellTest extends TestCase { /** * fixtures * * @var array */ public $fixtures = ['plugin.DelayedJobs.DelayedJobs']; /** * @var \DelayedJobs\Shell\WorkerShell */ public $Shell; /** * @var \Cake\Console\ConsoleIo */ public $io; /** * setup test * * @return void */ public function setUp() { parent::setUp(); $this->io = $this->getMock('Cake\Console\ConsoleIo', [], [], '', false); $this->Shell = $this->getMock( 'DelayedJobs\Shell\WorkerShell', ['in', 'out', 'hr', 'err', 'createFile', '_stop'], [$this->io] ); $lock_mock = $this->getMock('\\DelayedJobs\\Lock'); $this->Shell->startup($lock_mock); } /** * tearDown method * * @return void */ public function tearDown() { parent::tearDown(); unset($this->Shell); } /** * @return void * @covers ::main * @expectedException \Cake\Core\Exception\Exception */ public function testNoJobId() { $this->Shell->args = []; $this->Shell->main(); } /** * @return void * @covers ::main */ public function testStopsIfLocked() { $this->Shell->Lock ->expects($this->once()) ->method('lock') ->with('DelayedJobs.WorkerShell.main.1') ->willReturn(false); $this->Shell ->expects($this->once()) ->method('_stop') ->with(1); $this->Shell->args = [1]; $this->Shell->main(); } /** * @return void * @covers ::main */ public function testStopsIfJobDoesNotExist() { $this->Shell->Lock ->expects($this->once()) ->method('lock') ->with('DelayedJobs.WorkerShell.main.1') ->willReturn(true); $this->Shell ->expects($this->once()) ->method('_stop') ->with(1); $this->Shell->args = [1]; $this->Shell->main(); } public function errorDataProvider() { return [ [DelayedJobsTable::STATUS_SUCCESS, 'Job previously completed'], [DelayedJobsTable::STATUS_BURRIED, 'Job Failed too many times'], ]; } /** * @param int $job_status Job status to use. * @param string $expected_message Expected message to test for. * @return void * @covers ::main * @dataProvider errorDataProvider */ public function testErrorForStatus($job_status, $expected_message) { $job = Fabricate::create('DelayedJobs.DelayedJobs', 1, function () use ($job_status) { return ['status' => $job_status]; })[0]; $this->Shell->DelayedJobs = $this->getMockForModel('DelayedJobs.DelayedJobs', ['failed'], [ 'table' => 'delayed_jobs', ]); $this->Shell->Lock ->expects($this->once()) ->method('lock') ->with('DelayedJobs.WorkerShell.main.1') ->willReturn(true); $this->Shell->DelayedJobs ->expects($this->once()) ->method('failed') ->with( $this->callback(function ($subject) use ($job) { return $subject instanceof Entity && $subject->id === $job->id; }), $this->stringContains($expected_message) ); $this->Shell->args = [$job->id]; $this->Shell->main(); } protected function _buildJobMock() { $job_data = Fabricate::attributes_for('DelayedJobs.DelayedJobs', 1, function () { return ['status' => DelayedJobsTable::STATUS_BUSY]; })[0]; $job = $this->getMock('\\DelayedJobs\\Model\\Entity\\DelayedJob', ['execute'], [$job_data]); $this->Shell->DelayedJobs = $this->getMockForModel('DelayedJobs.DelayedJobs', ['failed', 'completed', 'get'], [ 'table' => 'delayed_jobs', ]); $this->Shell->Lock ->expects($this->once()) ->method('lock') ->with('DelayedJobs.WorkerShell.main.1') ->willReturn(true); $this->Shell->DelayedJobs ->expects($this->once()) ->method('get') ->with($job->id) ->willReturn($job); return $job; } /** * @return void * @covers ::main */ public function testExecuteSuccessJob() { $job = $this->_buildJobMock(); $job ->expects($this->once()) ->method('execute') ->willReturn(true); $this->Shell->DelayedJobs ->expects($this->once()) ->method('completed') ->with( $this->callback(function ($subject) use ($job) { return $subject instanceof Entity && $subject->id === $job->id; }) ); $this->Shell->args = [$job->id]; $this->Shell->main(); } /** * @return void * @covers ::main */ public function testExecuteFailedJob() { $job = $this->_buildJobMock(); $job ->expects($this->once()) ->method('execute') ->willReturn(false); $this->Shell->DelayedJobs ->expects($this->once()) ->method('failed') ->with( $this->callback(function ($subject) use ($job) { return $subject instanceof Entity && $subject->id === $job->id; }), $this->stringContains('Invalid response received') ); $this->Shell->args = [$job->id]; $this->Shell->main(); } }
# mobilesafe ## 这是一个eclipse项目,黑马视频中的手机安全卫士,自己做了点更新,稍微美化了一下。 下面是一些操作演示,由于电脑的genymotion不能使用,这里用ASM连真机录的,所以有些卡。录的时候有些问题,出现了绿屏和黑屏。 ![](https://github.com/IAn2018cs/mobilesafe/blob/master/gifRepository/demo.gif)
<?php Route::get('index',"AdminController@index"); //route brand Route::get('brandIndex',"AdminController@brandIndex"); Route::get('brand/create',"AdminController@brandCreate"); Route::post('brand/store',"AdminController@brandStore"); Route::get('brand/edit/{id}',"AdminController@brandEdit"); Route::post('brand/update/{id}',"AdminController@brandUpdate"); Route::get('brand/delete/{id}',"AdminController@brandDestroy"); Route::get('brand/detail/{id}',"AdminController@brandDetail"); //route category Route::get('categoriesIndex',"AdminController@categoriesIndex"); Route::get('category/create',"AdminController@categoriesCreate"); Route::post('category/store',"AdminController@categoriesStore"); Route::get('category/edit/{id}',"AdminController@categoryEdit"); Route::post('category/update/{id}',"AdminController@categoryUpdate"); Route::get('category/delete/{id}',"AdminController@categoryDestroy"); Route::get('category/detail/{id}',"AdminController@categoryDetail"); //route product Route::get('productIndex',"AdminController@productIndex"); Route::get('product/create',"AdminController@productCreate"); Route::post('product/store',"AdminController@productStore"); Route::get('product/edit/{id}',"AdminController@productEdit"); Route::post('product/update/{id}',"AdminController@productUpdate"); Route::get('product/delete/{id}',"AdminController@productDestroy"); Route::get('product/detail/{id}',"AdminController@productDetail"); //route user Route::get('userIndex',"AdminController@userIndex"); Route::get('user/create',"AdminController@userCreate"); Route::post('user/store',"AdminController@userStore"); Route::get('user/edit/{id}',"AdminController@userEdit"); Route::post('user/update/{id}',"AdminController@userUpdate"); Route::get('user/delete/{id}',"AdminController@userDestroy"); //route user Route::get('orderIndex',"AdminController@orderIndex");
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once(SHAREDPATH . 'core/APP_Batch_controller.php'); /** * Class Base_controller * * @extend APP_Batch_controller */ class Base_controller extends APP_Batch_controller { }
<?php namespace Solital\Core\Resource; class Cookie { /** * @param string $index * @param mixed $value * @return bool */ public static function new(string $index, string $value, $time = null, string $path = null): bool { setcookie($index, $value, $time, $path); return true; } /** * @param string $index * @return bool */ public static function delete($index, $path = null): bool { setcookie($index, NULL, -1, $path); return true; } /** * @param string $index * @return bool */ public static function show(string $index) { if (\filter_input(INPUT_COOKIE, $index, FILTER_SANITIZE_STRING)) { return \filter_input(INPUT_COOKIE, $index); } } /** * @param string $index * @return bool */ public static function has($index): bool { if (\filter_input(INPUT_COOKIE, $index)) { return true; } else { return false; } } }
<?php namespace App\Http\Services\Admin; use App\Http\Services\MyService; use App\Models\Product; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; class ProductService extends MyService { public function getPaginationForList() { return DB::table('product') ->select('product.*', 'folder.name as folder_name') ->join('folder', 'folder.id', '=', 'product.folder_id') ->whereNull('product.deleted_at') ->paginate(25); } public function getAllByFolderId($id) { return DB::table('product') ->where('folder_id', '=', $id) ->where('active', '=', 1) ->whereNull('deleted_at') ->get(); } public function register($input) { $product = new Product($input); $product->save(); return $product; } public function registerValidate($request) { return $validator = Validator::make($request, [ 'name' => "required|max:50|unique:product,name,NULL,id,deleted_at,NULL", 'folder_id' => 'required|exists:folder,id', 'price' => 'nullable|numeric|digits_between:1,10', 'summary' => 'required|max:190', 'introduce' => 'max:10000', 'code' => 'max:50', 'text_domain' => 'required|max:50', 'note' => 'max:500', 'qty' => 'nullable|numeric|digits_between:1,10', 'image' => 'required|max:10', 'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:5000', ]); } public function updateValidate($request, $id) { return $validator = Validator::make($request, [ 'name' => "required|max:50|unique:product,name,$id,id,deleted_at,NULL", 'folder_id' => 'required|exists:folder,id', 'price' => 'nullable|numeric|digits_between:1,10', 'summary' => 'required|max:190', 'introduce' => 'max:10000', 'code' => 'max:50', 'text_domain' => 'required|max:50', 'note' => 'max:500', 'qty' => 'nullable|numeric|digits_between:1,10', 'image' => 'max:10', 'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:5000', ]); } }
# card `bw-card` is an easy customizable card with css custom properties, styling for bulma is included ## Usage #### installation ```bash npm i -S @bulma-web/card # or yarn add -S @bulma-web/card ``` ```javascript import '@bulma-web/card' ``` #### Example ```html <bw-card> <div slot="content"> <h2> “There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.” </h2> <p>Jeff Atwood</p> </div> </bw-card> ``` ### API #### Slots |slot name |Description | |-------------------|---------------------------| |content |Content to display in card | |header-title |title ot be placed for card header| |header-icon |icon to be displayed in the outer right of the card header| |image |image to be added in the card| |footer-item |items to be placed in the footer of the card| #### custom css variables for customization |Variable |Description |Type | |-------------------|-------------------------------|-------------------| |`--card-color` |text color for the card |color code | |`--card-background-color`|background color of the card|color code | |`--card-shadow` |card shadow |box shadow | |`--card-header-background-color`|background color for the card header|color code| |`--card-header-color`|text color for the card header|color code | |`--card-header-padding`|padding size for the card header|unit size| |`--card-header-shadow`|shadow for card header|nox shadow notation| |`--card-header-weight`|font weight for card header|units| |`--card-content-background-color`|background color for card|color code| |`--card-content-padding`|padding for card content|unit size| |`--card-footer-background-color`|background color for the card footer|color code| |`--card-footer-border-top`|border top of card footer|cdd border shorthand notation| |`--card-footer-padding`|padding for card footer|unit size| |`--card-media-margin`|margin for card media|unit size|
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. IMG_DIR=$1 OUT_DIR=$2 ANO_DIR=$3 set -e if [ -z $CUDA_VISIBLE_DEVICES ]; then CUDA_VISIBLE_DEVICES='all' fi echo "extracting image features..." if [ ! -d $OUT_DIR ]; then mkdir -p $OUT_DIR fi docker run --gpus '"'device=$CUDA_VISIBLE_DEVICES'"' --ipc=host --rm -it \ --mount src=$IMG_DIR,dst=/img,type=bind,readonly \ --mount src=$OUT_DIR,dst=/output,type=bind \ --mount src=$ANO_DIR,dst=/ano,type=bind \ -e NVIDIA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES \ -w /src chenrocks/butd-caffe:nlvr2 \ # bash -c "python tools/generate_npz.py --gpu 0" #echo "done"
#include <Debug.h> #include <TCPPacket.h> using namespace Network; Network::TCPPacket::TCPPacket() : APacket(TCP), _protobufPacket() { _protobufPacket.set_type(CubZPacket::PacketTCP::UNKNOWN); } Network::TCPPacket::~TCPPacket() { } ByteBuffer Network::TCPPacket::getData() const { ByteBuffer _finalBuffer{}; _finalBuffer.resize(_protobufPacket.ByteSizeLong()); _protobufPacket.SerializeToArray(_finalBuffer.data(), _protobufPacket.ByteSize()); TCPMSG("Get data on TCPPPacket. Packet size: " << (_finalBuffer.size()) << std::endl); TRACE(_protobufPacket.DebugString() << std::endl); return (_finalBuffer); } std::size_t Network::TCPPacket::setData(ByteBuffer const &buff) { TRACE("Set data on TCPPacket(size: " << buff.size() << ")" << std::endl); bool success{_protobufPacket.ParseFromArray(buff.data(), buff.size())}; if (!success) TRACE("Couldn't parse protobuf packet !" << std::endl); TRACE("DEBUG PROTOBUF PRINT " <<_protobufPacket.DebugString() << std::endl); return (buff.size()); } void Network::TCPPacket::setType(Type t) { _protobufPacket.set_type(t); } Network::TCPPacket::Type Network::TCPPacket::getPacketType() const { return (_protobufPacket.type()); } CubZPacket::PacketTCP &Network::TCPPacket::getTCPPacket() { return (_protobufPacket); } CubZPacket::PacketTCP const &Network::TCPPacket::getTCPPacket() const { return (_protobufPacket); } std::ostream &operator<<(std::ostream &os, Network::TCPPacket const &packet) { os << packet.getTCPPacket().DebugString(); return (os); }
package com.goldenpiedevs.schedule.app.ui.view import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.appcompat.app.AppCompatActivity fun AppCompatActivity.hideSoftKeyboard() { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager val v = currentFocus if (v != null) { inputMethodManager.hideSoftInputFromWindow(v.windowToken, 0) } } catch (e: Exception) { } } fun androidx.fragment.app.Fragment.hideSoftKeyboard() { try { val imm = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view!!.windowToken, 0) } catch (e: Exception) { } } fun AppCompatActivity.showSoftKeyboard() { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.showSoftInput(currentFocus, 0) } catch (e: Exception) { } } fun Context.showSoftKeyboard(editText: EditText) { try { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED) } catch (e: Exception) { } } fun Context.hideSoftKeyboard(editText: EditText?) { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager if (editText != null) { inputMethodManager.hideSoftInputFromWindow(editText.windowToken, 0) } } catch (e: Exception) { } } fun Context.hideSoftKeyboard(vararg views: View) { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager for (view in views) { inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) } } catch (e: Exception) { } } fun AppCompatActivity.hideSoftKeyboard(vararg views: View) { hideSoftKeyboard() for (view in views) { view.clearFocus() } }
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:sofia/application/states/retrieve_tracks_state.dart'; import 'package:sofia/model/track.dart'; import 'package:sofia/utils/database.dart'; class RetrieveTracksNotifier extends StateNotifier<RetrieveTracksState> { final Database _database; RetrieveTracksNotifier(this._database) : super(RetrieveTracksState()); Future<void> retrieveTracks() async { try { state = RetrieveTracksState.retrieving(); List<Track> tracks = await _database.retrieveTracks(); state = RetrieveTracksState.retrieved(tracks); } catch (error) { state = RetrieveTracksState.error(message: 'Error retrieveing tracks'); } } }
/* */ package networthcalculator.labels; import javafx.collections.ObservableList; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import networthcalculator.utilities.MyUtility; import networthcalculator.TotalAmount; import networthcalculator.labels.labelsubclasses.AccCategory; import networthcalculator.utilities.NumberReformatter; /** * * @author MP */ public class SubTotalAmountLabel extends javafx.scene.layout.AnchorPane { private Label leftPlaceholder = new Label(); private Label subTotal = new Label(); private Label subAmountNumLabel = new Label(); private HBox hbox = new HBox(); private String text; final private int PREF_HEIGHT = 25; private TotalAmount totalAmount; public SubTotalAmountLabel(String text, TotalAmount totalAmount) { this.totalAmount = totalAmount; this.text = text; this.setId("SubTotalAmountLabel"); setHBox(); setLabelProperties(); this.getChildren().add(hbox); } private void setHBox() { hbox.setId("SubTotalAmountLabelHBox"); ObservableList list = hbox.getChildren(); list.addAll(leftPlaceholder, subTotal, subAmountNumLabel); AnchorPane.setLeftAnchor(hbox, 0.0); AnchorPane.setRightAnchor(hbox, 0.0); } private void setLabelProperties() { leftPlaceholder.setPrefHeight(PREF_HEIGHT); leftPlaceholder.setAlignment(Pos.CENTER_LEFT); leftPlaceholder.prefWidthProperty().bind(hbox.widthProperty()); subTotal.setId("SubTotalLabel"); subTotal.setText(text); subTotal.setPrefHeight(PREF_HEIGHT); subTotal.prefWidthProperty().bind(hbox.widthProperty()); subAmountNumLabel.setPrefHeight(PREF_HEIGHT); subAmountNumLabel.setAlignment(Pos.CENTER_RIGHT); subAmountNumLabel.prefWidthProperty().bind(hbox.widthProperty()); } public void setSubTotal(double subTotal, AccCategory category) { String sign = ""; if(category.getCategory().equals(AccCategory.LIABILITIES)) { sign = "-"; } subAmountNumLabel.setText(sign + NumberReformatter.reformat(subTotal)); } public void setSubTotalDifference(AccCategory category, double subTotalDifference) { totalAmount.setSubTotalDifference(category, subTotalDifference); } }
/* * The MIT License (MIT) * * Copyright (c) 2020 TileDB, Inc. * * 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. */ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package io.tiledb.java.api; import io.tiledb.libtiledb.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class NativeArray implements AutoCloseable { private Class javaType; private Datatype nativeType; private int nativeTypeSize; private floatArray floatArray; private doubleArray doubleArray; private int8_tArray int8_tArray; private int16_tArray int16_tArray; private int32_tArray int32_tArray; private int64_tArray int64_tArray; private uint8_tArray uint8_tArray; private uint16_tArray uint16_tArray; private uint32_tArray uint32_tArray; private int64_tArray uint64_tArray; private int size; // private charArray charArray; /** * Creates an empty native array using a native datatype and a provided size * * @param ctx A TileDB context * @param size Number of array elements * @param nativeType A TileDB datatype * @exception TileDBError A TileDB exception */ public NativeArray(Context ctx, int size, Datatype nativeType) throws TileDBError { this.size = size; this.javaType = Types.getJavaType(nativeType); this.nativeType = nativeType; this.nativeTypeSize = tiledb.tiledb_datatype_size(nativeType.toSwigEnum()).intValue(); allocateEmptyArray(); } /** * Creates an empty native array using a java datatype and a provided size * * @param ctx A TileDB context * @param size Number of array elements * @param javaType A Java scalar type class * @exception TileDBError A TileDB exception */ public NativeArray(Context ctx, int size, Class javaType) throws TileDBError { this.size = size; this.javaType = javaType; this.nativeType = Types.getNativeType(javaType); this.nativeTypeSize = tiledb.tiledb_datatype_size(this.nativeType.toSwigEnum()).intValue(); allocateEmptyArray(); } /** * Creates a native array using a java datatype. It takes as input a Java buffer (i.e long[], * int[]) and copies its values to the C native array. * * @param ctx A TileDB context * @param buffer A Java array * @param javaType A Java scalar type class * @exception TileDBError A TileDB exception */ public NativeArray(Context ctx, Object buffer, Class javaType) throws TileDBError { this.javaType = javaType; this.nativeType = Types.getNativeType(javaType); this.nativeTypeSize = tiledb.tiledb_datatype_size(this.nativeType.toSwigEnum()).intValue(); this.size = getSize(buffer); createNativeArrayFromBuffer(buffer); } /** * Creates a native array using a native datatype. It takes as input a Java buffer (i.e long[], * int[]) and copies its values to the C native array. * * @param ctx A TileDB context * @param buffer A Java array * @param nativeType A TileDB datatype * @param size The array size * @exception TileDBError A TileDB exception */ public NativeArray(Context ctx, Object buffer, Datatype nativeType, int size) throws TileDBError { this.javaType = Types.getJavaType(nativeType); this.nativeType = nativeType; this.nativeTypeSize = tiledb.tiledb_datatype_size(this.nativeType.toSwigEnum()).intValue(); this.size = size; createNativeArrayFromBuffer(buffer); } /** * Creates a native array using a native datatype. It takes as input a Java buffer (i.e long[], * int[]) and copies its values to the C native array. * * @param ctx A TileDB context * @param buffer A Java array * @param nativeType A TileDB datatype * @exception TileDBError A TileDB exception */ public NativeArray(Context ctx, Object buffer, Datatype nativeType) throws TileDBError { this.javaType = Types.getJavaType(nativeType); this.nativeType = nativeType; this.nativeTypeSize = tiledb.tiledb_datatype_size(this.nativeType.toSwigEnum()).intValue(); this.size = getSize(buffer); createNativeArrayFromBuffer(buffer); } protected NativeArray(Context ctx, Datatype nativeType, SWIGTYPE_p_p_void pointer, int nelements) throws TileDBError { this.javaType = Types.getJavaType(nativeType); this.nativeType = nativeType; this.nativeTypeSize = tiledb.tiledb_datatype_size(this.nativeType.toSwigEnum()).intValue(); this.size = nelements; createNativeArrayFromVoidPointer(pointer); } protected NativeArray(Context ctx, Datatype nativeType, SWIGTYPE_p_void pointer, int nelements) throws TileDBError { this.javaType = Types.getJavaType(nativeType); this.nativeType = nativeType; this.nativeTypeSize = tiledb.tiledb_datatype_size(this.nativeType.toSwigEnum()).intValue(); this.size = nelements; createNativeArrayFromVoidPointer(pointer); } private int getSize(Object buffer) throws TileDBError { switch (this.nativeType) { case TILEDB_FLOAT32: { return ((float[]) buffer).length; } case TILEDB_FLOAT64: { return ((double[]) buffer).length; } case TILEDB_INT8: { return ((byte[]) buffer).length; } case TILEDB_INT16: { return ((short[]) buffer).length; } case TILEDB_INT32: { return ((int[]) buffer).length; } case TILEDB_INT64: { return ((long[]) buffer).length; } case TILEDB_UINT8: { return ((short[]) buffer).length; } case TILEDB_UINT16: { return ((int[]) buffer).length; } case TILEDB_UINT32: { return ((long[]) buffer).length; } case TILEDB_UINT64: { return ((long[]) buffer).length; } case TILEDB_CHAR: case TILEDB_STRING_ASCII: { Charset charset = StandardCharsets.ISO_8859_1; return stringToBytes((String) buffer, charset).length; } case TILEDB_STRING_UTF8: { Charset charset = StandardCharsets.UTF_8; return stringToBytes((String) buffer, charset).length; } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: case TILEDB_DATETIME_AS: { return ((long[]) buffer).length; } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } private void createNativeArrayFromBuffer(Object buffer) throws TileDBError { switch (nativeType) { case TILEDB_FLOAT32: { floatArray = Utils.newFloatArray((float[]) buffer); break; } case TILEDB_FLOAT64: { doubleArray = Utils.newDoubleArray((double[]) buffer); break; } case TILEDB_INT8: { int8_tArray = Utils.newInt8_tArray((byte[]) buffer); break; } case TILEDB_INT16: { int16_tArray = Utils.newInt16_tArray((short[]) buffer); break; } case TILEDB_INT32: { int32_tArray = Utils.newInt32_tArray((int[]) buffer); break; } case TILEDB_INT64: { int64_tArray = Utils.newInt64_tArray((long[]) buffer); break; } case TILEDB_UINT8: { uint8_tArray = Utils.newUint8_tArray((short[]) buffer); break; } case TILEDB_UINT16: { uint16_tArray = Utils.newUint16_tArray((int[]) buffer); break; } case TILEDB_UINT32: { uint32_tArray = Utils.newUint32_tArray((long[]) buffer); break; } case TILEDB_UINT64: { uint64_tArray = Utils.newInt64_tArray((long[]) buffer); break; } case TILEDB_CHAR: case TILEDB_STRING_ASCII: { Charset charset = StandardCharsets.ISO_8859_1; int8_tArray = Utils.newInt8_tArray(stringToBytes((String) buffer, charset)); break; } case TILEDB_STRING_UTF8: { Charset charset = StandardCharsets.UTF_8; int8_tArray = Utils.newInt8_tArray(stringToBytes((String) buffer, charset)); break; } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: case TILEDB_DATETIME_AS: { int64_tArray = Utils.newInt64_tArray((long[]) buffer); break; } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } private void allocateEmptyArray() throws TileDBError { switch (nativeType) { case TILEDB_FLOAT32: { floatArray = new floatArray(size); break; } case TILEDB_FLOAT64: { doubleArray = new doubleArray(size); break; } case TILEDB_INT8: { int8_tArray = new int8_tArray(size); break; } case TILEDB_INT16: { int16_tArray = new int16_tArray(size); break; } case TILEDB_INT32: { int32_tArray = new int32_tArray(size); break; } case TILEDB_INT64: { int64_tArray = new int64_tArray(size); break; } case TILEDB_UINT8: { uint8_tArray = new uint8_tArray(size); break; } case TILEDB_UINT16: { uint16_tArray = new uint16_tArray(size); break; } case TILEDB_UINT32: { uint32_tArray = new uint32_tArray(size); break; } case TILEDB_UINT64: { uint64_tArray = new int64_tArray(size); break; } case TILEDB_STRING_ASCII: case TILEDB_CHAR: { int8_tArray = new int8_tArray(size); break; } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: case TILEDB_DATETIME_AS: { int64_tArray = new int64_tArray(size); break; } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } /** * Returns the item on index position of the native array. * * @param index Index of array scalar to return * @return item A Java scalar * @exception TileDBError A TileDB exception */ public Object getItem(int index) throws ArrayIndexOutOfBoundsException, TileDBError { if (index >= size || index < 0) { throw new ArrayIndexOutOfBoundsException(index); } switch (nativeType) { case TILEDB_FLOAT32: { return floatArray.getitem(index); } case TILEDB_FLOAT64: { return doubleArray.getitem(index); } case TILEDB_INT8: { return int8_tArray.getitem(index); } case TILEDB_INT16: { return int16_tArray.getitem(index); } case TILEDB_INT32: { return int32_tArray.getitem(index); } case TILEDB_INT64: { return int64_tArray.getitem(index); } case TILEDB_UINT8: { return uint8_tArray.getitem(index); } case TILEDB_UINT16: { return uint16_tArray.getitem(index); } case TILEDB_UINT32: { return uint32_tArray.getitem(index); } case TILEDB_UINT64: { return uint64_tArray.getitem(index); } case TILEDB_STRING_ASCII: case TILEDB_CHAR: { return int8_tArray.getitem(index); } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: case TILEDB_DATETIME_AS: { return int64_tArray.getitem(index); } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } /** * Sets the item on index position of the native array. * * @param index array index * @param value array value to set at index * @exception TileDBError A TileDB exception */ public void setItem(int index, Object value) throws ArrayIndexOutOfBoundsException, TileDBError { if (index >= size || index < 0) { throw new ArrayIndexOutOfBoundsException(index); } switch (nativeType) { case TILEDB_FLOAT32: { floatArray.setitem(index, (float) value); break; } case TILEDB_FLOAT64: { doubleArray.setitem(index, (double) value); break; } case TILEDB_INT8: { int8_tArray.setitem(index, (byte) value); break; } case TILEDB_INT16: { int16_tArray.setitem(index, (short) value); break; } case TILEDB_INT32: { int32_tArray.setitem(index, (int) value); break; } case TILEDB_INT64: { int64_tArray.setitem(index, (long) value); break; } case TILEDB_UINT8: { uint8_tArray.setitem(index, (short) value); break; } case TILEDB_UINT16: { uint16_tArray.setitem(index, (int) value); break; } case TILEDB_UINT32: { uint32_tArray.setitem(index, (long) value); break; } case TILEDB_UINT64: { uint64_tArray.setitem(index, (long) value); break; } case TILEDB_CHAR: case TILEDB_STRING_ASCII: { Charset charset = StandardCharsets.ISO_8859_1; for (byte b : stringToBytes((String) value, charset)) { int8_tArray.setitem(index, b); index++; } break; } case TILEDB_STRING_UTF8: { Charset charset = StandardCharsets.UTF_8; for (byte b : stringToBytes((String) value, charset)) { int8_tArray.setitem(index, b); index++; } break; } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: case TILEDB_DATETIME_AS: { int64_tArray.setitem(index, (long) value); break; } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } public SWIGTYPE_p_void toVoidPointer() throws TileDBError { switch (nativeType) { case TILEDB_FLOAT32: { return PointerUtils.toVoid(floatArray); } case TILEDB_FLOAT64: { return PointerUtils.toVoid(doubleArray); } case TILEDB_INT8: { return PointerUtils.toVoid(int8_tArray); } case TILEDB_INT16: { return PointerUtils.toVoid(int16_tArray); } case TILEDB_INT32: { return PointerUtils.toVoid(int32_tArray); } case TILEDB_INT64: { return PointerUtils.toVoid(int64_tArray); } case TILEDB_UINT8: { return PointerUtils.toVoid(uint8_tArray); } case TILEDB_UINT16: { return PointerUtils.toVoid(uint16_tArray); } case TILEDB_UINT32: { return PointerUtils.toVoid(uint32_tArray); } case TILEDB_UINT64: { return PointerUtils.toVoid(uint64_tArray); } case TILEDB_STRING_ASCII: case TILEDB_STRING_UTF8: case TILEDB_CHAR: { return PointerUtils.toVoid(int8_tArray); } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: { return PointerUtils.toVoid(int64_tArray); } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } public long toCPointer() throws TileDBError { switch (nativeType) { case TILEDB_FLOAT32: { return PointerUtils.toCPtr(floatArray); } case TILEDB_FLOAT64: { return PointerUtils.toCPtr(doubleArray); } case TILEDB_INT8: { return PointerUtils.toCPtr(int8_tArray); } case TILEDB_INT16: { return PointerUtils.toCPtr(int16_tArray); } case TILEDB_INT32: { return PointerUtils.toCPtr(int32_tArray); } case TILEDB_INT64: { return PointerUtils.toCPtr(int64_tArray); } case TILEDB_UINT8: { return PointerUtils.toCPtr(uint8_tArray); } case TILEDB_UINT16: { return PointerUtils.toCPtr(uint16_tArray); } case TILEDB_UINT32: { return PointerUtils.toCPtr(uint32_tArray); } case TILEDB_UINT64: { return PointerUtils.toCPtr(uint64_tArray); } case TILEDB_CHAR: { return PointerUtils.toCPtr(int8_tArray); } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: { return PointerUtils.toCPtr(int64_tArray); } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } /** * Return a Java array (i.e. int[], long[]) that is a copy of the entire native array * * @return A java array * @throws TileDBError A TileDB exception */ public Object toJavaArray() throws TileDBError { return toJavaArray(0, size); } /** * Return a Java array (i.e. int[], long[]) that is a copy of the native array values with the * given size, starting at position 0 * * @param elements number of elements to return * @return A java array * @exception TileDBError A TileDB exception */ public Object toJavaArray(int elements) throws TileDBError { return toJavaArray(0, elements); } /** * Return a Java array (i.e. int[], long[]) that is a copy of the native array values with the * given size, starting at given position * * @param position position to start copying from * @param elements number of elements to return * @return A java array * @exception TileDBError A TileDB exception */ public Object toJavaArray(int position, int elements) throws TileDBError { if (position + elements > size || position < 0 || elements < 0) { throw new ArrayIndexOutOfBoundsException(position + elements); } switch (nativeType) { case TILEDB_FLOAT32: { return Utils.floatArrayGet(floatArray, position, elements); } case TILEDB_FLOAT64: { return Utils.doubleArrayGet(doubleArray, position, elements); } case TILEDB_INT8: { return Utils.int8ArrayGet(int8_tArray, position, elements); } case TILEDB_INT16: { return Utils.int16ArrayGet(int16_tArray, position, elements); } case TILEDB_INT32: { return Utils.int32ArrayGet(int32_tArray, position, elements); } case TILEDB_INT64: { return Utils.int64ArrayGet(int64_tArray, position, elements); } case TILEDB_UINT8: { return Utils.uint8ArrayGet(uint8_tArray, position, elements); } case TILEDB_UINT16: { return Utils.uint16ArrayGet(uint16_tArray, position, elements); } case TILEDB_UINT32: { return Utils.uint32ArrayGet(uint32_tArray, position, elements); } case TILEDB_UINT64: { return Utils.int64ArrayGet(uint64_tArray, position, elements); } case TILEDB_STRING_ASCII: case TILEDB_STRING_UTF8: case TILEDB_CHAR: { return Utils.int8ArrayGet(int8_tArray, position, elements); } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: { return Utils.int64ArrayGet(int64_tArray, position, elements); } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } private void createNativeArrayFromVoidPointer(SWIGTYPE_p_p_void pointer) throws TileDBError { switch (nativeType) { case TILEDB_FLOAT32: { floatArray = PointerUtils.floatArrayFromVoid(pointer); break; } case TILEDB_FLOAT64: { doubleArray = PointerUtils.doubleArrayFromVoid(pointer); break; } case TILEDB_INT8: { int8_tArray = PointerUtils.int8_tArrayFromVoid(pointer); break; } case TILEDB_INT16: { int16_tArray = PointerUtils.int16_tArrayFromVoid(pointer); break; } case TILEDB_INT32: { int32_tArray = PointerUtils.int32_tArrayFromVoid(pointer); break; } case TILEDB_INT64: { int64_tArray = PointerUtils.int64_tArrayFromVoid(pointer); break; } case TILEDB_UINT8: { uint8_tArray = PointerUtils.uint8_tArrayFromVoid(pointer); break; } case TILEDB_UINT16: { uint16_tArray = PointerUtils.uint16_tArrayFromVoid(pointer); break; } case TILEDB_UINT32: { uint32_tArray = PointerUtils.uint32_tArrayFromVoid(pointer); break; } case TILEDB_UINT64: { uint64_tArray = PointerUtils.int64_tArrayFromVoid(pointer); break; } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: { int64_tArray = PointerUtils.int64_tArrayFromVoid(pointer); break; } case TILEDB_STRING_ASCII: case TILEDB_STRING_UTF8: case TILEDB_CHAR: { int8_tArray = PointerUtils.int8_tArrayFromVoid(pointer); break; } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } private void createNativeArrayFromVoidPointer(SWIGTYPE_p_void pointer) throws TileDBError { switch (nativeType) { case TILEDB_FLOAT32: { floatArray = PointerUtils.floatArrayFromVoid(pointer); break; } case TILEDB_FLOAT64: { doubleArray = PointerUtils.doubleArrayFromVoid(pointer); break; } case TILEDB_INT8: { int8_tArray = PointerUtils.int8_tArrayFromVoid(pointer); break; } case TILEDB_INT16: { int16_tArray = PointerUtils.int16_tArrayFromVoid(pointer); break; } case TILEDB_INT32: { int32_tArray = PointerUtils.int32_tArrayFromVoid(pointer); break; } case TILEDB_INT64: { int64_tArray = PointerUtils.int64_tArrayFromVoid(pointer); break; } case TILEDB_UINT8: { uint8_tArray = PointerUtils.uint8_tArrayFromVoid(pointer); break; } case TILEDB_UINT16: { uint16_tArray = PointerUtils.uint16_tArrayFromVoid(pointer); break; } case TILEDB_UINT32: { uint32_tArray = PointerUtils.uint32_tArrayFromVoid(pointer); break; } case TILEDB_UINT64: { uint64_tArray = PointerUtils.int64_tArrayFromVoid(pointer); break; } case TILEDB_DATETIME_YEAR: case TILEDB_DATETIME_MONTH: case TILEDB_DATETIME_WEEK: case TILEDB_DATETIME_DAY: case TILEDB_DATETIME_HR: case TILEDB_DATETIME_MIN: case TILEDB_DATETIME_SEC: case TILEDB_DATETIME_MS: case TILEDB_DATETIME_US: case TILEDB_DATETIME_NS: case TILEDB_DATETIME_PS: case TILEDB_DATETIME_FS: { int64_tArray = PointerUtils.int64_tArrayFromVoid(pointer); break; } default: { throw new TileDBError("Unsupported TileDB NativeArray Datatype enum: " + this.nativeType); } } } private byte[] stringToBytes(String buffer, Charset charset) { return buffer.getBytes(charset); } protected Datatype getNativeType() { return nativeType; } public Class getJavaType() { return javaType; } public int getSize() { return size; } public int getNativeTypeSize() { return nativeTypeSize; } public long getNBytes() { return ((long) size) * nativeTypeSize; } /** Free's NativeArray off heap allocated resources */ public void close() { if (floatArray != null) { floatArray.delete(); } if (doubleArray != null) { doubleArray.delete(); } if (int8_tArray != null) { int8_tArray.delete(); } if (int16_tArray != null) { int16_tArray.delete(); } if (int32_tArray != null) { int32_tArray.delete(); } if (int64_tArray != null) { int64_tArray.delete(); } if (uint8_tArray != null) { uint8_tArray.delete(); } if (uint16_tArray != null) { uint16_tArray.delete(); } if (uint32_tArray != null) { uint32_tArray.delete(); } if (uint64_tArray != null) { uint64_tArray.delete(); } } }
# Examples ``` export BIGTABLE_EMULATOR_HOST=localhost:8086 cargo run --bin simple_read ```
# frozen_string_literal: true require 'rails_helper' describe Role do context 'with validates' do it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_uniqueness_of(:name) } it { is_expected.to validate_length_of(:name).is_at_least(4) } it { is_expected.to validate_presence_of(:description) } end context 'with associations' do it { is_expected.to have_many(:user_roles) } # бизнес-роли пользователя it { is_expected.to have_many(:users).through(:user_roles) } end it 'have search method' do expect(described_class.search('').first).to eq(described_class.first) end end
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use App\Traits\Uuid; class Jabatan extends Model { use HasFactory; use Uuid; protected $table = 'jabatan'; protected $fillable = ['nama_jabatan']; public function pengurus(){ return $this->hasMany('App\Models\Pengurus'); } public function majelispembimbing(){ return $this->hasMany('App\Models\Majelispembimbing'); } public function pemeriksakeuangan(){ return $this->hasMany('App\Models\Pemeriksakeuangan'); } public function dewankehormatan(){ return $this->hasMany('App\Models\Dewankehormatan'); } public function satuanpengawas(){ return $this->hasMany('App\Models\Satuanpengawas'); } public function satuankarya(){ return $this->hasMany('App\Models\Satuankarya'); } public function pusatpelatihan(){ return $this->hasMany('App\Models\Pusatpelatihan'); } public function satgaspramuka(){ return $this->hasMany('App\Models\Satgaspramuka'); } public function penguruskwaran(){ return $this->hasMany('App\Models\Penguruskwaran'); } public function mabiran(){ return $this->hasMany('App\Models\Mabiran'); } public function lpk(){ return $this->hasMany('App\Models\Lpk'); } public function dewankerjakwaran(){ return $this->hasMany('App\Models\Dewankerjakwaran'); } public function pengurusgudep(){ return $this->hasMany('App\Models\Pengurusgudep'); } }
from abc import abstractmethod from utils.loggings import logger import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter class Model(): def __init__(self, save_path, log_path): self.save_path = save_path self.log_path = log_path self.model = None self.classifier = None self.parameters = None self.optimizer = None self.train_logger = None self.eval_logger = None self.summary_writer = None @abstractmethod def loss(self, **kwargs): pass @abstractmethod def train(self, **kwargs): pass @abstractmethod def evaluate(self, **kwargs): pass @abstractmethod def checkpoint(self, **kwargs): pass def data_parallel(self): # If GPU available, move the graph to GPU(s) self.CUDA_AVAILABLE = self.check_cuda() if self.CUDA_AVAILABLE: device_ids = list(range(torch.cuda.device_count())) self.model = nn.DataParallel(self.model, device_ids) self.classifier = nn.DataParallel(self.classifier, device_ids) self.model.to('cuda') self.classifier.to('cuda') assert (next(self.model.parameters()).is_cuda) assert (next(self.classifier.parameters()).is_cuda) pass else: print('CUDA not found or not enabled, use CPU instead') def set_optimizer(self, Optimizer, lr, **kwargs): self.optimizer = Optimizer(self.parameters, lr=lr, **kwargs) def set_logger(self, mode='a'): self.train_logger = logger('train',self.log_path + '-train', mode=mode) self.eval_logger = logger('eval', self.log_path + '-eval', mode=mode) def set_summary_writer(self): self.summary_writer = SummaryWriter(self.log_path + 'tensorboard') def check_cuda(self): if torch.cuda.is_available(): print("INFO: CUDA device exists") return torch.cuda.is_available() def resume_checkpoint(self, checkpoint_path): checkpoint = torch.load(checkpoint_path) if self.model != None: model_state_dict = checkpoint['model_state_dict'] self.model.load_state_dict(model_state_dict) self.model.train() classifier_state_dict = checkpoint['classifier_state_dict'] self.classifier.load_state_dict(classifier_state_dict) self.classifier.train() def save_model(self, checkpoint, save_path): torch.save(checkpoint, save_path) def load_model(self, checkpoint_path): checkpoint = torch.load(checkpoint_path) if self.model != None: model_state_dict = checkpoint['model_state_dict'] self.model.load_state_dict(model_state_dict) self.model.eval() classifier_state_dict = checkpoint['classifier_state_dict'] self.classifier.load_state_dict(classifier_state_dict) self.classifier.eval() def count_parameters(self): try: assert self.model != None model_params = sum(p.numel() for p in self.model.parameters() if p.requires_grad) print('Number of Model Parameters: %d'%model_params) for name, param in self.model.named_parameters(): if param.requires_grad: print(name, param.numel()) except: print('No Model specified') try: assert self.classifier != None classifier = sum(p.numel() for p in self.classifier.parameters() if p.requires_grad) print('Number of Model Classifier: %d' % classifier) for name, param in self.classifier.named_parameters(): if param.requires_grad: print(name, param.numel()) except: print('No Classifier specified')
package main import ( "fmt" "github.com/inwecrypto/ethgo/rpc" "github.com/inwecrypto/ethgo/erc20" ) var client *rpc.Client func init() { client = rpc.NewClient("http://47.52.158.99:8545") } func main() { accoutState, err := client.GetBalance("0xf4cc4154a4987f8784064468c3c6b21f0d0cdd64") if err != nil { fmt.Println("err:", err) return } fmt.Println(accoutState) state := &rpc.CallSite{ From: "0xf4cc4154a4987f8784064468c3c6b21f0d0cdd64", // from To: "0x9b7929b142dddc08b889c146340c872cf8d6de71", // smart comtract address Value: "0x0", GasPrice: "0x0", Gas: "0x0", Data: erc20.BalanceOf("0xf4cc4154a4987f8784064468c3c6b21f0d0cdd64"), // comtract function } fmt.Println(state) val, err := client.Call(state) if err != nil { fmt.Println("err:", err) return } fmt.Println(val) intval, err := rpc.ReadBigint(val) if err != nil { fmt.Println("err:", err) return } fmt.Println(intval) }
#[derive(Debug)] pub struct Register { // registers pub zero: u64, pub ra: u64, pub sp: u64, pub gp: u64, pub tp: u64, pub t0: u64, pub t1: u64, pub t2: u64, pub fp: u64, // s0 pub s1: u64, pub a0: u64, pub a1: u64, pub a2: u64, pub a3: u64, pub a4: u64, pub a5: u64, pub a6: u64, pub a7: u64, pub s2: u64, pub s3: u64, pub s4: u64, pub s5: u64, pub s6: u64, pub s7: u64, pub s8: u64, pub s9: u64, pub s10: u64, pub s11: u64, pub t3: u64, pub t4: u64, pub t5: u64, pub t6: u64, pub pc: u64, // supervisor-level csr pub sstatus: u64, // 0x100 pub sie: u64, // 0x104 pub stvec: u64, // 0x105 pub scounteren: u64, // 0x106 pub senvcfg: u64, // 0x10A pub sscratch: u64, // 0x140 pub sepc: u64, // 0x141 pub scause: u64, // 0x142 pub stval: u64, // 0x143 pub sip: u64, // 0x144 pub satp: u64, // 0x180 pub scontext: u64, // 0x5A8 // machine-level csr pub mvendorid: u64, // 0xF11 pub marchid: u64, // 0xF12 pub mimpid: u64, // 0xF13 pub mhartid: u64, // 0xF14 pub mconfigptr: u64, // 0xF15 pub mstatus: u64, // 0x300 pub misa: u64, // 0x301 pub medeleg: u64, // 0x302 pub mideleg: u64, // 0x303 pub mie: u64, // 0x304 pub mtvec: u64, // 0x305 pub mcounteren: u64, // 0x306 pub mstatush: u64, // 0x310 pub mscratch: u64, // 0x340 pub mepc: u64, // 0x341 pub mcause: u64, // 0x342 pub mtval: u64, // 0x343 pub mip: u64, // 0x344 pub mtinst: u64, // 0x34A pub mtval2: u64, // 0x34B pub menvcfg: u64, // 0x30A pub menvcfgh: u64, // 0x31A pub mseccfg: u64, // 0x747 pub mseccfgh: u64, // 0x757 pub pmpcfg0: u64, // 0x3A0 pub pmpcfg1: u64, // 0x3A1 pub pmpcfg2: u64, // 0x3A2 pub pmpcfg3: u64, // 0x3A3 pub pmpcfg4: u64, // 0x3A4 pub pmpcfg5: u64, // 0x3A5 pub pmpcfg6: u64, // 0x3A6 pub pmpcfg7: u64, // 0x3A7 pub pmpcfg8: u64, // 0x3A8 pub pmpcfg9: u64, // 0x3A9 pub pmpcfg10: u64, // 0x3AA pub pmpcfg11: u64, // 0x3AB pub pmpcfg12: u64, // 0x3AC pub pmpcfg13: u64, // 0x3AD pub pmpcfg14: u64, // 0x3AE pub pmpcfg15: u64, // 0x3AF pub pmpaddr0: u64, // 0x3B0 pub pmpaddr1: u64, // 0x3B1 pub pmpaddr2: u64, // 0x3B2 pub pmpaddr3: u64, // 0x3B3 pub pmpaddr4: u64, // 0x3B4 pub pmpaddr5: u64, // 0x3B5 pub pmpaddr6: u64, // 0x3B6 pub pmpaddr7: u64, // 0x3B7 pub pmpaddr8: u64, // 0x3B8 pub pmpaddr9: u64, // 0x3B9 pub pmpaddr10: u64, // 0x3BA pub pmpaddr11: u64, // 0x3BB pub pmpaddr12: u64, // 0x3BC pub pmpaddr13: u64, // 0x3BD pub pmpaddr14: u64, // 0x3BE pub pmpaddr15: u64, // 0x3BF pub pmpaddr16: u64, // 0x3C0 pub pmpaddr17: u64, // 0x3C1 pub pmpaddr18: u64, // 0x3C2 pub pmpaddr19: u64, // 0x3C3 pub pmpaddr20: u64, // 0x3C4 pub pmpaddr21: u64, // 0x3C5 pub pmpaddr22: u64, // 0x3C6 pub pmpaddr23: u64, // 0x3C7 pub pmpaddr24: u64, // 0x3C8 pub pmpaddr25: u64, // 0x3C9 pub pmpaddr26: u64, // 0x3CA pub pmpaddr27: u64, // 0x3CB pub pmpaddr28: u64, // 0x3CC pub pmpaddr29: u64, // 0x3CD pub pmpaddr30: u64, // 0x3CE pub pmpaddr31: u64, // 0x3CF pub pmpaddr32: u64, // 0x3D0 pub pmpaddr33: u64, // 0x3D1 pub pmpaddr34: u64, // 0x3D2 pub pmpaddr35: u64, // 0x3D3 pub pmpaddr36: u64, // 0x3D4 pub pmpaddr37: u64, // 0x3D5 pub pmpaddr38: u64, // 0x3D6 pub pmpaddr39: u64, // 0x3D7 pub pmpaddr40: u64, // 0x3D8 pub pmpaddr41: u64, // 0x3D9 pub pmpaddr42: u64, // 0x3DA pub pmpaddr43: u64, // 0x3DB pub pmpaddr44: u64, // 0x3DC pub pmpaddr45: u64, // 0x3DD pub pmpaddr46: u64, // 0x3DE pub pmpaddr47: u64, // 0x3DF pub pmpaddr48: u64, // 0x3E0 pub pmpaddr49: u64, // 0x3E1 pub pmpaddr50: u64, // 0x3E2 pub pmpaddr51: u64, // 0x3E3 pub pmpaddr52: u64, // 0x3E4 pub pmpaddr53: u64, // 0x3E5 pub pmpaddr54: u64, // 0x3E6 pub pmpaddr55: u64, // 0x3E7 pub pmpaddr56: u64, // 0x3E8 pub pmpaddr57: u64, // 0x3E9 pub pmpaddr58: u64, // 0x3EA pub pmpaddr59: u64, // 0x3EB pub pmpaddr60: u64, // 0x3EC pub pmpaddr61: u64, // 0x3ED pub pmpaddr62: u64, // 0x3EE pub pmpaddr63: u64, // 0x3EF } impl Register { pub fn new() -> Register { Register { zero: 0, ra: 0, sp: 0, gp: 0, tp: 0, t0: 0, t1: 0, t2: 0, fp: 0, s1: 0, a0: 0, a1: 0, a2: 0, a3: 0, a4: 0, a5: 0, a6: 0, a7: 0, s2: 0, s3: 0, s4: 0, s5: 0, s6: 0, s7: 0, s8: 0, s9: 0, s10: 0, s11: 0, t3: 0, t4: 0, t5: 0, t6: 0, pc: 0, // supervisor-level csr sstatus: 0, // 0x100 sie: 0, // 0x104 stvec: 0, // 0x105 scounteren: 0, // 0x106 senvcfg: 0, // 0x10A sscratch: 0, // 0x140 sepc: 0, // 0x141 scause: 0, // 0x142 stval: 0, // 0x143 sip: 0, // 0x144 satp: 0, // 0x180 scontext: 0, // 0x5A8 // machine-level csr mvendorid: 0, // 0xF11 marchid: 0, // 0xF12 mimpid: 0, // 0xF13 mhartid: 0, // 0xF14 mconfigptr: 0, // 0xF15 mstatus: 0, // 0x300 misa: 0, // 0x301 medeleg: 0, // 0x302 mideleg: 0, // 0x303 mie: 0, // 0x304 mtvec: 0, // 0x305 mcounteren: 0, // 0x306 mstatush: 0, // 0x310 mscratch: 0, // 0x340 mepc: 0, // 0x341 mcause: 0, // 0x342 mtval: 0, // 0x343 mip: 0, // 0x344 mtinst: 0, // 0x34A mtval2: 0, // 0x34B menvcfg: 0, // 0x30A menvcfgh: 0, // 0x31A mseccfg: 0, // 0x747 mseccfgh: 0, // 0x757 pmpcfg0: 0, // 0x3A0 pmpcfg1: 0, // 0x3A1 pmpcfg2: 0, // 0x3A2 pmpcfg3: 0, // 0x3A3 pmpcfg4: 0, // 0x3A4 pmpcfg5: 0, // 0x3A5 pmpcfg6: 0, // 0x3A6 pmpcfg7: 0, // 0x3A7 pmpcfg8: 0, // 0x3A8 pmpcfg9: 0, // 0x3A9 pmpcfg10: 0, // 0x3AA pmpcfg11: 0, // 0x3AB pmpcfg12: 0, // 0x3AC pmpcfg13: 0, // 0x3AD pmpcfg14: 0, // 0x3AE pmpcfg15: 0, // 0x3AF pmpaddr0: 0, // 0x3B0 pmpaddr1: 0, // 0x3B1 pmpaddr2: 0, // 0x3B2 pmpaddr3: 0, // 0x3B3 pmpaddr4: 0, // 0x3B4 pmpaddr5: 0, // 0x3B5 pmpaddr6: 0, // 0x3B6 pmpaddr7: 0, // 0x3B7 pmpaddr8: 0, // 0x3B8 pmpaddr9: 0, // 0x3B9 pmpaddr10: 0, // 0x3BA pmpaddr11: 0, // 0x3BB pmpaddr12: 0, // 0x3BC pmpaddr13: 0, // 0x3BD pmpaddr14: 0, // 0x3BE pmpaddr15: 0, // 0x3BF pmpaddr16: 0, // 0x3C0 pmpaddr17: 0, // 0x3C1 pmpaddr18: 0, // 0x3C2 pmpaddr19: 0, // 0x3C3 pmpaddr20: 0, // 0x3C4 pmpaddr21: 0, // 0x3C5 pmpaddr22: 0, // 0x3C6 pmpaddr23: 0, // 0x3C7 pmpaddr24: 0, // 0x3C8 pmpaddr25: 0, // 0x3C9 pmpaddr26: 0, // 0x3CA pmpaddr27: 0, // 0x3CB pmpaddr28: 0, // 0x3CC pmpaddr29: 0, // 0x3CD pmpaddr30: 0, // 0x3CE pmpaddr31: 0, // 0x3CF pmpaddr32: 0, // 0x3D0 pmpaddr33: 0, // 0x3D1 pmpaddr34: 0, // 0x3D2 pmpaddr35: 0, // 0x3D3 pmpaddr36: 0, // 0x3D4 pmpaddr37: 0, // 0x3D5 pmpaddr38: 0, // 0x3D6 pmpaddr39: 0, // 0x3D7 pmpaddr40: 0, // 0x3D8 pmpaddr41: 0, // 0x3D9 pmpaddr42: 0, // 0x3DA pmpaddr43: 0, // 0x3DB pmpaddr44: 0, // 0x3DC pmpaddr45: 0, // 0x3DD pmpaddr46: 0, // 0x3DE pmpaddr47: 0, // 0x3DF pmpaddr48: 0, // 0x3E0 pmpaddr49: 0, // 0x3E1 pmpaddr50: 0, // 0x3E2 pmpaddr51: 0, // 0x3E3 pmpaddr52: 0, // 0x3E4 pmpaddr53: 0, // 0x3E5 pmpaddr54: 0, // 0x3E6 pmpaddr55: 0, // 0x3E7 pmpaddr56: 0, // 0x3E8 pmpaddr57: 0, // 0x3E9 pmpaddr58: 0, // 0x3EA pmpaddr59: 0, // 0x3EB pmpaddr60: 0, // 0x3EC pmpaddr61: 0, // 0x3ED pmpaddr62: 0, // 0x3EE pmpaddr63: 0, // 0x3EF } } pub fn print(&self) { let mut zero_ls: Vec<String> = vec![]; non_zero_print("zero", "0x000", self.zero, &mut zero_ls); non_zero_print("ra", "0x001", self.ra, &mut zero_ls); non_zero_print("sp", "0x002", self.sp, &mut zero_ls); non_zero_print("gp", "0x003", self.gp, &mut zero_ls); non_zero_print("tp", "0x004", self.tp, &mut zero_ls); non_zero_print("t0", "0x005", self.t0, &mut zero_ls); non_zero_print("t1", "0x006", self.t1, &mut zero_ls); non_zero_print("t2", "0x007", self.t2, &mut zero_ls); non_zero_print("fp", "0x008", self.fp, &mut zero_ls); non_zero_print("s1", "0x009", self.s1, &mut zero_ls); non_zero_print("a0", "0x00A", self.a0, &mut zero_ls); non_zero_print("a1", "0x00B", self.a1, &mut zero_ls); non_zero_print("a2", "0x00C", self.a2, &mut zero_ls); non_zero_print("a3", "0x00D", self.a3, &mut zero_ls); non_zero_print("a4", "0x00E", self.a4, &mut zero_ls); non_zero_print("a5", "0x00F", self.a5, &mut zero_ls); non_zero_print("a6", "0x010", self.a6, &mut zero_ls); non_zero_print("a7", "0x011", self.a7, &mut zero_ls); non_zero_print("s2", "0x012", self.s2, &mut zero_ls); non_zero_print("s3", "0x013", self.s3, &mut zero_ls); non_zero_print("s4", "0x014", self.s4, &mut zero_ls); non_zero_print("s5", "0x015", self.s5, &mut zero_ls); non_zero_print("s6", "0x016", self.s6, &mut zero_ls); non_zero_print("s7", "0x017", self.s7, &mut zero_ls); non_zero_print("s8", "0x018", self.s8, &mut zero_ls); non_zero_print("s9", "0x019", self.s9, &mut zero_ls); non_zero_print("s10", "0x01A", self.s10, &mut zero_ls); non_zero_print("s11", "0x01B", self.s11, &mut zero_ls); non_zero_print("t3", "0x01C", self.t3, &mut zero_ls); non_zero_print("t4", "0x01D", self.t4, &mut zero_ls); non_zero_print("t5", "0x01E", self.t5, &mut zero_ls); non_zero_print("t6", "0x01F", self.t6, &mut zero_ls); non_zero_print("pc", "0x020", self.pc, &mut zero_ls); non_zero_print("mstatus", "0x300", self.mstatus, &mut zero_ls); non_zero_print("medeleg", "0x302", self.medeleg, &mut zero_ls); non_zero_print("mideleg", "0x303", self.mideleg, &mut zero_ls); non_zero_print("mie", "0x304", self.mie, &mut zero_ls); non_zero_print("mscratch", "0x340", self.mscratch, &mut zero_ls); non_zero_print("mepc", "0x341", self.mepc, &mut zero_ls); non_zero_print("mip", "0x344", self.mip, &mut zero_ls); non_zero_print("mtvec", "0x3B0", self.mtvec, &mut zero_ls); non_zero_print("sstatus", "0x100", self.sstatus, &mut zero_ls); non_zero_print("sie", "0x104", self.sie, &mut zero_ls); non_zero_print("stvec", "0x105", self.stvec, &mut zero_ls); non_zero_print("sscratch", "0x140", self.sscratch, &mut zero_ls); non_zero_print("sepc", "0x141", self.sepc, &mut zero_ls); non_zero_print("scause", "0x142", self.scause, &mut zero_ls); non_zero_print("sip", "0x144", self.sip, &mut zero_ls); non_zero_print("satp", "0x180", self.satp, &mut zero_ls); non_zero_print("pmpaddr0", "0x3B0", self.pmpaddr0, &mut zero_ls); non_zero_print("pmpcfg0", "0x3A0", self.pmpcfg0, &mut zero_ls); println!("zero: {:?}", zero_ls); } pub fn get_reg(&self, reg: u8) -> u64 { match reg { 0b0_0000 => self.zero, 0b0_0001 => self.ra, 0b0_0010 => self.sp, 0b0_0011 => self.gp, 0b0_0100 => self.tp, 0b0_0101 => self.t0, 0b0_0110 => self.t1, 0b0_0111 => self.t2, 0b0_1000 => self.fp, 0b0_1001 => self.s1, 0b0_1010 => self.a0, 0b0_1011 => self.a1, 0b0_1100 => self.a2, 0b0_1101 => self.a3, 0b0_1110 => self.a4, 0b0_1111 => self.a5, 0b1_0000 => self.a6, 0b1_0001 => self.a7, 0b1_0010 => self.s2, 0b1_0011 => self.s3, 0b1_0100 => self.s4, 0b1_0101 => self.s5, 0b1_0110 => self.s6, 0b1_0111 => self.s7, 0b1_1000 => self.s8, 0b1_1001 => self.s9, 0b1_1010 => self.s10, 0b1_1011 => self.s11, 0b1_1100 => self.t3, 0b1_1101 => self.t4, 0b1_1110 => self.t5, 0b1_1111 => self.t6, _ => panic!("invalid register"), } } pub fn get_csr(&self, reg: u16) -> u64 { match reg { // supervisor-level csr 0x100 => self.sstatus, 0x104 => self.sie, 0x105 => self.stvec, 0x106 => self.scounteren, 0x10A => self.senvcfg, 0x140 => self.sscratch, 0x141 => self.sepc, 0x142 => self.scause, 0x143 => self.stval, 0x144 => self.sip, 0x180 => self.satp, 0x5A8 => self.scontext, // machine-level csr 0xF11 => self.mvendorid, 0xF12 => self.marchid, 0xF13 => self.mimpid, 0xF14 => self.mhartid, 0xF15 => self.mconfigptr, 0x300 => self.mstatus, 0x301 => self.misa, 0x302 => self.medeleg, 0x303 => self.mideleg, 0x304 => self.mie, 0x305 => self.mtvec, 0x306 => self.mcounteren, 0x310 => self.mstatush, 0x340 => self.mscratch, 0x341 => self.mepc, 0x342 => self.mcause, 0x343 => self.mtval, 0x344 => self.mip, 0x34A => self.mtinst, 0x34B => self.mtval2, 0x30A => self.menvcfg, 0x31A => self.menvcfgh, 0x747 => self.mseccfg, 0x757 => self.mseccfgh, 0x3A0 => self.pmpcfg0, 0x3A1 => self.pmpcfg1, 0x3A2 => self.pmpcfg2, 0x3A3 => self.pmpcfg3, 0x3A4 => self.pmpcfg4, 0x3A5 => self.pmpcfg5, 0x3A6 => self.pmpcfg6, 0x3A7 => self.pmpcfg7, 0x3A8 => self.pmpcfg8, 0x3A9 => self.pmpcfg9, 0x3AA => self.pmpcfg10, 0x3AB => self.pmpcfg11, 0x3AC => self.pmpcfg12, 0x3AD => self.pmpcfg13, 0x3AE => self.pmpcfg14, 0x3AF => self.pmpcfg15, 0x3B0 => self.pmpaddr0, 0x3B1 => self.pmpaddr1, 0x3B2 => self.pmpaddr2, 0x3B3 => self.pmpaddr3, 0x3B4 => self.pmpaddr4, 0x3B5 => self.pmpaddr5, 0x3B6 => self.pmpaddr6, 0x3B7 => self.pmpaddr7, 0x3B8 => self.pmpaddr8, 0x3B9 => self.pmpaddr9, 0x3BA => self.pmpaddr10, 0x3BB => self.pmpaddr11, 0x3BC => self.pmpaddr12, 0x3BD => self.pmpaddr13, 0x3BE => self.pmpaddr14, 0x3BF => self.pmpaddr15, 0x3C0 => self.pmpaddr16, 0x3C1 => self.pmpaddr17, 0x3C2 => self.pmpaddr18, 0x3C3 => self.pmpaddr19, 0x3C4 => self.pmpaddr20, 0x3C5 => self.pmpaddr21, 0x3C6 => self.pmpaddr22, 0x3C7 => self.pmpaddr23, 0x3C8 => self.pmpaddr24, 0x3C9 => self.pmpaddr25, 0x3CA => self.pmpaddr26, 0x3CB => self.pmpaddr27, 0x3CC => self.pmpaddr28, 0x3CD => self.pmpaddr29, 0x3CE => self.pmpaddr30, 0x3CF => self.pmpaddr31, 0x3D0 => self.pmpaddr32, 0x3D1 => self.pmpaddr33, 0x3D2 => self.pmpaddr34, 0x3D3 => self.pmpaddr35, 0x3D4 => self.pmpaddr36, 0x3D5 => self.pmpaddr37, 0x3D6 => self.pmpaddr38, 0x3D7 => self.pmpaddr39, 0x3D8 => self.pmpaddr40, 0x3D9 => self.pmpaddr41, 0x3DA => self.pmpaddr42, 0x3DB => self.pmpaddr43, 0x3DC => self.pmpaddr44, 0x3DD => self.pmpaddr45, 0x3DE => self.pmpaddr46, 0x3DF => self.pmpaddr47, 0x3E0 => self.pmpaddr48, 0x3E1 => self.pmpaddr49, 0x3E2 => self.pmpaddr50, 0x3E3 => self.pmpaddr51, 0x3E4 => self.pmpaddr52, 0x3E5 => self.pmpaddr53, 0x3E6 => self.pmpaddr54, 0x3E7 => self.pmpaddr55, 0x3E8 => self.pmpaddr56, 0x3E9 => self.pmpaddr57, 0x3EA => self.pmpaddr58, 0x3EB => self.pmpaddr59, 0x3EC => self.pmpaddr60, 0x3ED => self.pmpaddr61, 0x3EE => self.pmpaddr62, 0x3EF => self.pmpaddr63, _ => panic!("invalid register"), } } pub fn set_reg(&mut self, reg: u8, value: u64) { match reg { 0b0_0000 => (), 0b0_0001 => self.ra = value, 0b0_0010 => self.sp = value, 0b0_0011 => self.gp = value, 0b0_0100 => self.tp = value, 0b0_0101 => self.t0 = value, 0b0_0110 => self.t1 = value, 0b0_0111 => self.t2 = value, 0b0_1000 => self.fp = value, 0b0_1001 => self.s1 = value, 0b0_1010 => self.a0 = value, 0b0_1011 => self.a1 = value, 0b0_1100 => self.a2 = value, 0b0_1101 => self.a3 = value, 0b0_1110 => self.a4 = value, 0b0_1111 => self.a5 = value, 0b1_0000 => self.a6 = value, 0b1_0001 => self.a7 = value, 0b1_0010 => self.s2 = value, 0b1_0011 => self.s3 = value, 0b1_0100 => self.s4 = value, 0b1_0101 => self.s5 = value, 0b1_0110 => self.s6 = value, 0b1_0111 => self.s7 = value, 0b1_1000 => self.s8 = value, 0b1_1001 => self.s9 = value, 0b1_1010 => self.s10 = value, 0b1_1011 => self.s11 = value, 0b1_1100 => self.t3 = value, 0b1_1101 => self.t4 = value, 0b1_1110 => self.t5 = value, 0b1_1111 => self.t6 = value, _ => panic!("invalid register"), } } pub fn set_csr(&mut self, reg: u16, value: u64) { match reg { // supervisor-level csr 0x100 => self.sstatus = value, 0x104 => self.sie = value, 0x105 => self.stvec = value, 0x106 => self.scounteren = value, 0x10A => self.senvcfg = value, 0x140 => self.sscratch = value, 0x141 => self.sepc = value, 0x142 => self.scause = value, 0x143 => self.stval = value, 0x144 => self.sip = value, 0x180 => self.satp = value, 0x5A8 => self.scontext = value, // machine-level csr 0xF11 => self.mvendorid = value, 0xF12 => self.marchid = value, 0xF13 => self.mimpid = value, 0xF14 => self.mhartid = value, 0xF15 => self.mconfigptr = value, 0x300 => self.mstatus = value, 0x301 => self.misa = value, 0x302 => self.medeleg = value, 0x303 => self.mideleg = value, 0x304 => self.mie = value, 0x305 => self.mtvec = value, 0x306 => self.mcounteren = value, 0x310 => self.mstatush = value, 0x340 => self.mscratch = value, 0x341 => self.mepc = value, 0x342 => self.mcause = value, 0x343 => self.mtval = value, 0x344 => self.mip = value, 0x34A => self.mtinst = value, 0x34B => self.mtval2 = value, 0x30A => self.menvcfg = value, 0x31A => self.menvcfgh = value, 0x747 => self.mseccfg = value, 0x757 => self.mseccfgh = value, 0x3A0 => self.pmpcfg0 = value, 0x3A1 => self.pmpcfg1 = value, 0x3A2 => self.pmpcfg2 = value, 0x3A3 => self.pmpcfg3 = value, 0x3A4 => self.pmpcfg4 = value, 0x3A5 => self.pmpcfg5 = value, 0x3A6 => self.pmpcfg6 = value, 0x3A7 => self.pmpcfg7 = value, 0x3A8 => self.pmpcfg8 = value, 0x3A9 => self.pmpcfg9 = value, 0x3AA => self.pmpcfg10 = value, 0x3AB => self.pmpcfg11 = value, 0x3AC => self.pmpcfg12 = value, 0x3AD => self.pmpcfg13 = value, 0x3AE => self.pmpcfg14 = value, 0x3AF => self.pmpcfg15 = value, 0x3B0 => self.pmpaddr0 = value, 0x3B1 => self.pmpaddr1 = value, 0x3B2 => self.pmpaddr2 = value, 0x3B3 => self.pmpaddr3 = value, 0x3B4 => self.pmpaddr4 = value, 0x3B5 => self.pmpaddr5 = value, 0x3B6 => self.pmpaddr6 = value, 0x3B7 => self.pmpaddr7 = value, 0x3B8 => self.pmpaddr8 = value, 0x3B9 => self.pmpaddr9 = value, 0x3BA => self.pmpaddr10 = value, 0x3BB => self.pmpaddr11 = value, 0x3BC => self.pmpaddr12 = value, 0x3BD => self.pmpaddr13 = value, 0x3BE => self.pmpaddr14 = value, 0x3BF => self.pmpaddr15 = value, 0x3C0 => self.pmpaddr16 = value, 0x3C1 => self.pmpaddr17 = value, 0x3C2 => self.pmpaddr18 = value, 0x3C3 => self.pmpaddr19 = value, 0x3C4 => self.pmpaddr20 = value, 0x3C5 => self.pmpaddr21 = value, 0x3C6 => self.pmpaddr22 = value, 0x3C7 => self.pmpaddr23 = value, 0x3C8 => self.pmpaddr24 = value, 0x3C9 => self.pmpaddr25 = value, 0x3CA => self.pmpaddr26 = value, 0x3CB => self.pmpaddr27 = value, 0x3CC => self.pmpaddr28 = value, 0x3CD => self.pmpaddr29 = value, 0x3CE => self.pmpaddr30 = value, 0x3CF => self.pmpaddr31 = value, 0x3D0 => self.pmpaddr32 = value, 0x3D1 => self.pmpaddr33 = value, 0x3D2 => self.pmpaddr34 = value, 0x3D3 => self.pmpaddr35 = value, 0x3D4 => self.pmpaddr36 = value, 0x3D5 => self.pmpaddr37 = value, 0x3D6 => self.pmpaddr38 = value, 0x3D7 => self.pmpaddr39 = value, 0x3D8 => self.pmpaddr40 = value, 0x3D9 => self.pmpaddr41 = value, 0x3DA => self.pmpaddr42 = value, 0x3DB => self.pmpaddr43 = value, 0x3DC => self.pmpaddr44 = value, 0x3DD => self.pmpaddr45 = value, 0x3DE => self.pmpaddr46 = value, 0x3DF => self.pmpaddr47 = value, 0x3E0 => self.pmpaddr48 = value, 0x3E1 => self.pmpaddr49 = value, 0x3E2 => self.pmpaddr50 = value, 0x3E3 => self.pmpaddr51 = value, 0x3E4 => self.pmpaddr52 = value, 0x3E5 => self.pmpaddr53 = value, 0x3E6 => self.pmpaddr54 = value, 0x3E7 => self.pmpaddr55 = value, 0x3E8 => self.pmpaddr56 = value, 0x3E9 => self.pmpaddr57 = value, 0x3EA => self.pmpaddr58 = value, 0x3EB => self.pmpaddr59 = value, 0x3EC => self.pmpaddr60 = value, 0x3ED => self.pmpaddr61 = value, 0x3EE => self.pmpaddr62 = value, 0x3EF => self.pmpaddr63 = value, _ => panic!("invalid register"), } } } /// example: /// println!("zero(0x000):\t0x{:016X}, 0b{:064b}", <zero register value>, <zero register value>); fn non_zero_print(reg_name: &str, reg_code: &str, value: u64, zero_ls: &mut Vec<String>) { if value == 0 { zero_ls.push(reg_name.to_string()); return; } let mut reg_name = format!("{}({}):", reg_name, reg_code); if reg_name.len() < 16 { reg_name += "\t"; } println!("{}0x{:016X}, 0b{:064b}", reg_name, value, value); }
require 'jekyll_asset_pipeline' module JekyllAssetPipeline class SassConverter < JekyllAssetPipeline::Converter require 'sass' def self.filetype '.scss' end def convert paths = [ '.', '_assets/moj_internal_template/app/assets/stylesheets', '_assets/govuk_template/source/assets/stylesheets', '_assets/govuk_frontend_toolkit/stylesheets' ] return Sass::Engine.new(@content, syntax: :scss, :load_paths => paths,).render end end class ImageConverter < JekyllAssetPipeline::Converter def self.filetype '.png' end end end
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Playground.Domain.Events; using Playground.Domain.Model; using Playground.Domain.Persistence.Events; using Playground.Domain.Persistence.Snapshots; using Playground.Messaging; namespace Playground.Domain.Persistence { public class AggregateContext : IAggregateContext { private readonly IEventStore _eventStore; private readonly ISnapshotStore _snapshotStore; private readonly IAggregateHydrator _aggregateHydrator; private readonly IEventDispatcher _eventDispatcher; public AggregateContext( IEventStore eventStore, ISnapshotStore snapshotStore, IAggregateHydrator aggregateHydrator, IEventDispatcher eventDispatcher) { _eventStore = eventStore; _snapshotStore = snapshotStore; _aggregateHydrator = aggregateHydrator; _eventDispatcher = eventDispatcher; } public async Task<TAggregateRoot> Create<TAggregateRoot, TAggregateState>(Guid aggregateRootId) where TAggregateRoot : AggregateRoot<TAggregateState> where TAggregateState : class, IAggregateState, new() { //TODO: access if we should create a new stream at this point. // What if something goes wrong when processing the command that creates this, // then we would have an empty stream // If this should be kept, then the TryLoad and Load method must be able to return // an aggregate when there are no events, but there is a record created for it await _eventStore .CreateEventStream<TAggregateRoot>(aggregateRootId) .ConfigureAwait(false); return GetAggregateInstance<TAggregateRoot, TAggregateState>(aggregateRootId, null, null); } public async Task<TAggregateRoot> TryLoad<TAggregateRoot, TAggregateState>(Guid aggregateRootId) where TAggregateRoot : AggregateRoot<TAggregateState> where TAggregateState : class, IAggregateState, new() { var snapshot = await _snapshotStore .GetLastestSnaptshot<TAggregateState>(aggregateRootId) .ConfigureAwait(false); ICollection<DomainEvent> events; if (snapshot != null) { events = await _eventStore .LoadSelectedEvents(aggregateRootId, snapshot.Version, long.MaxValue) .ConfigureAwait(false); } else { events = await _eventStore .LoadAllEvents(aggregateRootId) .ConfigureAwait(false); } return events == null ? null : GetAggregateInstance<TAggregateRoot, TAggregateState>( aggregateRootId, events, snapshot); } public async Task<TAggregateRoot> Load<TAggregateRoot, TAggregateState>(Guid aggregateRootId) where TAggregateRoot : AggregateRoot<TAggregateState> where TAggregateState : class, IAggregateState, new() { var snapshot = await _snapshotStore .GetLastestSnaptshot<TAggregateState>(aggregateRootId) .ConfigureAwait(false); ICollection<DomainEvent> events; if (snapshot != null) { events = await _eventStore .LoadSelectedEvents( aggregateRootId, snapshot.Version + 1, long.MaxValue) .ConfigureAwait(false); } else { events = await _eventStore .LoadAllEvents(aggregateRootId) .ConfigureAwait(false); } if (snapshot == null && events == null) { throw new InvalidOperationException($"No stream with identifier {aggregateRootId}"); } return GetAggregateInstance<TAggregateRoot, TAggregateState>( aggregateRootId, events, snapshot); } public async Task Save<TAggregateRoot, TAggregateState>(TAggregateRoot aggregateRoot) where TAggregateRoot : AggregateRoot<TAggregateState> where TAggregateState : class, IAggregateState, new() { await _eventStore .StoreEvents( aggregateRoot.Id, aggregateRoot.CurrentVersion, aggregateRoot.UncommittedEvents) .ConfigureAwait(false); // everything worked correctly so lets dispatch the events foreach (var domainEvent in aggregateRoot.UncommittedEvents) { await _eventDispatcher .RaiseEvent(domainEvent) .ConfigureAwait(false); } } private TAggregateRoot GetAggregateInstance<TAggregateRoot, TAggregateState>( Guid aggregateRootId, ICollection<DomainEvent> events, Snapshot<TAggregateState> snapshot) where TAggregateRoot : AggregateRoot<TAggregateState> where TAggregateState : class, IAggregateState, new() { TAggregateRoot instance; if ((events != null && events.Any()) || snapshot != null) { var state = _aggregateHydrator .HydrateAggregateWithEvents<TAggregateState>( events ?? new List<DomainEvent>(), snapshot?.Data); var currentVersion = events != null && events.Any() ? events.Last().Metadata.Version : snapshot?.Version ?? 0; instance = Activator .CreateInstance( typeof(TAggregateRoot), aggregateRootId, state, currentVersion) as TAggregateRoot; } else { instance = Activator .CreateInstance(typeof(TAggregateRoot), aggregateRootId) as TAggregateRoot; } return instance; } } public class AggregateContextForAggregateWithIdentity : IAggregateContextForAggregateWithIdentity { private readonly IEventStoreForGenericIdentity _eventStore; private readonly ISnapshotStoreWithGenericIdentity _snapshotStore; private readonly IAggregateHydratorWithGenericIdentity _aggregateHydrator; private readonly IEventDispatcherWithGenericIdentity _eventDispatcher; public AggregateContextForAggregateWithIdentity( IEventStoreForGenericIdentity eventStore, ISnapshotStoreWithGenericIdentity snapshotStore, IAggregateHydratorWithGenericIdentity aggregateHydrator, IEventDispatcherWithGenericIdentity eventDispatcher) { _eventStore = eventStore; _snapshotStore = snapshotStore; _aggregateHydrator = aggregateHydrator; _eventDispatcher = eventDispatcher; } public async Task<TAggregateRoot> Create<TAggregateRoot, TAggregateState, TIdentity>( TIdentity aggregateRootId) where TAggregateRoot : AggregateRootWithIdentity<TAggregateState, TIdentity> where TAggregateState : class, IAggregateState, new() where TIdentity : IIdentity { //TODO: access if we should create a new stream at this point. // What if something goes wrong when processing the command that creates this, // then we would have an empty stream // If this should be kept, then the TryLoad and Load method must be able to return // an aggregate when there are no events, but there is a record created for it await _eventStore .CreateEventStream<TAggregateRoot>(aggregateRootId.Id) .ConfigureAwait(false); return GetAggregateInstance<TAggregateRoot, TAggregateState, TIdentity>( aggregateRootId, null, null); } public async Task<TAggregateRoot> TryLoad<TAggregateRoot, TAggregateState, TIdentity>( TIdentity aggregateRootId) where TAggregateRoot : AggregateRootWithIdentity<TAggregateState, TIdentity> where TAggregateState : class, IAggregateState, new() where TIdentity : IIdentity { var snapshot = await _snapshotStore .GetLastestSnaptshot<TAggregateState>(aggregateRootId.Id) .ConfigureAwait(false); ICollection<DomainEventForAggregateRootWithIdentity> events; if (snapshot != null) { events = await _eventStore .LoadSelectedEvents(aggregateRootId.Id, snapshot.Version, long.MaxValue) .ConfigureAwait(false); } else { events = await _eventStore .LoadAllEvents(aggregateRootId.Id) .ConfigureAwait(false); } return events == null ? null : GetAggregateInstance<TAggregateRoot, TAggregateState, TIdentity>( aggregateRootId, events, snapshot); } public async Task<TAggregateRoot> Load<TAggregateRoot, TAggregateState, TIdentity>( TIdentity aggregateRootId) where TAggregateRoot : AggregateRootWithIdentity<TAggregateState, TIdentity> where TAggregateState : class, IAggregateState, new() where TIdentity : IIdentity { var snapshot = await _snapshotStore .GetLastestSnaptshot<TAggregateState>(aggregateRootId.Id) .ConfigureAwait(false); ICollection<DomainEventForAggregateRootWithIdentity> events; if (snapshot != null) { events = await _eventStore .LoadSelectedEvents(aggregateRootId.Id, snapshot.Version, long.MaxValue) .ConfigureAwait(false); } else { events = await _eventStore .LoadAllEvents(aggregateRootId.Id) .ConfigureAwait(false); } if (snapshot == null && events == null) { throw new InvalidOperationException($"No stream with identifier {aggregateRootId}"); } return GetAggregateInstance<TAggregateRoot, TAggregateState, TIdentity>( aggregateRootId, events, snapshot); } public async Task Save<TAggregateRoot, TAggregateState, TIdentity>( TAggregateRoot aggregateRoot) where TAggregateRoot : AggregateRootWithIdentity<TAggregateState, TIdentity> where TAggregateState : class, IAggregateState, new() where TIdentity : IIdentity { await _eventStore .StoreEvents( aggregateRoot.Identity.Id, aggregateRoot.CurrentVersion, aggregateRoot.UncommittedEvents) .ConfigureAwait(false); // everything worked correctly so lets dispatch the events foreach (var domainEvent in aggregateRoot.UncommittedEvents) { await _eventDispatcher .RaiseEvent(domainEvent) .ConfigureAwait(false); } } private TAggregateRoot GetAggregateInstance<TAggregateRoot, TAggregateState, TIdentity>( TIdentity aggregateRootId, ICollection<DomainEventForAggregateRootWithIdentity> events, Snapshot<TAggregateState> snapshot) where TAggregateRoot : AggregateRootWithIdentity<TAggregateState, TIdentity> where TAggregateState : class, IAggregateState, new() where TIdentity : IIdentity { TAggregateRoot instance; if ((events != null && events.Any()) || snapshot != null) { var state = _aggregateHydrator .HydrateAggregateWithEvents<TAggregateState>( events ?? new List<DomainEventForAggregateRootWithIdentity>(), snapshot?.Data); var currentVersion = events != null && events.Any() ? events.Last().Metadata.Version : snapshot?.Version ?? 0; instance = Activator .CreateInstance( typeof(TAggregateRoot), aggregateRootId, state, currentVersion) as TAggregateRoot; } else { instance = Activator .CreateInstance(typeof(TAggregateRoot), aggregateRootId) as TAggregateRoot; } return instance; } } }
export const messages = { description: 'Creates a new Lightning Web Components project', help: { examples: [ 'create-lwc-app', 'npm init lwc-app my-app', 'npm init lwc-app my-app --type standard --yes', 'yarn init lwc-app my-app -o yarn,typescript' ] }, errors: { no_silent_with_options: { message: 'You can only set options in silent installation mode.', emoji: 'sos' }, noncompliant_app_types: { message: 'You used invalid app types: %s', emoji: 'sos' }, noncompliant_options: { message: 'You used invalid options: %s', emoji: 'sos' }, no_mix_app_types: { message: "You can't mix different app types: %s", emoji: 'sos' }, no_node_installed: { message: 'Node.js is not installed', emoji: 'sos' }, wrong_node_version_installed: { message: 'Node.js version 10 and higher needs to be installed.', emoji: 'sos' } }, args: { name: 'name', required: false }, flags: { silent: 'runs a silent installation (with defaults/with provided options)', type: 'specificy the project type (standard|pwa)', options: 'set silent installation options, comma-separated (yarn|typescript|edge|rollup|express)' } }
import * as Buildkite from '../../../../api/buildkite'; import type { StreamInterceptor } from '../../../../cli/lint/external'; export const createTscAnnotations = ( tscOk: boolean, tscOutputStream: StreamInterceptor, ): string[] => !tscOk ? [ '**tsc**', Buildkite.md.terminal( tscOutputStream .output() .split('\n') .filter(Boolean) .filter((line) => !line.startsWith('TSFILE: ')) .join('\n') .trim(), ), ] : [];
#!/bin/bash set -eux -o pipefail # docker kill -s HUP nginx docker exec "nginx" nginx -s reload
package main import ( "log" "github.com/kristoiv/wtf/bolt" "github.com/kristoiv/wtf/grpc" ) func main() { client := bolt.NewClient() if err := client.Open(); err != nil { log.Fatalln(err) } srv := grpc.NewServer() srv.TodoListServiceHandler = &grpc.TodoListServiceHandler{TodoListService: client.TodoListService()} if err := srv.Open(); err != nil { log.Fatalln(err) } select {} }
#ifndef SDL_render_d3d11_h_ #define SDL_render_d3d11_h_ #ifdef __WINRT__ #include "../src/core/windows/SDL_windows.h" #include "SDL_hints.h" #include "SDL_loadso.h" #include "SDL_syswm.h" #include "../src/render/SDL_sysrender.h" #include "../src/render/SDL_d3dmath.h" #include <d3d11_1.h> #include "../src/render/direct3d11/SDL_shaders_d3d11.h" #if NTDDI_VERSION > NTDDI_WIN8 #include <DXGI1_3.h> #endif /* !!! FIXME: vertex buffer bandwidth could be significantly lower; move color to a uniform, only use UV coords !!! FIXME: when textures are needed, and don't ever pass Z, since it's always zero. */ /* Vertex shader, common values */ typedef struct { Float4X4 model; Float4X4 projectionAndView; } VertexShaderConstants; /* Per-vertex data */ typedef struct { Float3 pos; Float2 tex; Float4 color; } VertexPositionColor; /* Per-texture data */ typedef struct { ID3D11Texture2D *mainTexture; ID3D11ShaderResourceView *mainTextureResourceView; ID3D11RenderTargetView *mainTextureRenderTargetView; ID3D11Texture2D *stagingTexture; int lockedTexturePositionX; int lockedTexturePositionY; D3D11_FILTER scaleMode; /* YV12 texture support */ SDL_bool yuv; ID3D11Texture2D *mainTextureU; ID3D11ShaderResourceView *mainTextureResourceViewU; ID3D11Texture2D *mainTextureV; ID3D11ShaderResourceView *mainTextureResourceViewV; /* NV12 texture support */ SDL_bool nv12; ID3D11Texture2D *mainTextureNV; ID3D11ShaderResourceView *mainTextureResourceViewNV; Uint8 *pixels; int pitch; SDL_Rect locked_rect; } D3D11_TextureData; /* Blend mode data */ typedef struct { SDL_BlendMode blendMode; ID3D11BlendState *blendState; } D3D11_BlendMode; /* Private renderer data */ typedef struct { void *hDXGIMod; void *hD3D11Mod; IDXGIFactory2 *dxgiFactory; IDXGIAdapter *dxgiAdapter; ID3D11Device1 *d3dDevice; ID3D11DeviceContext1 *d3dContext; IDXGISwapChain1 *swapChain; DXGI_SWAP_EFFECT swapEffect; ID3D11RenderTargetView *mainRenderTargetView; ID3D11RenderTargetView *currentOffscreenRenderTargetView; ID3D11InputLayout *inputLayout; ID3D11Buffer *vertexBuffers[8]; size_t vertexBufferSizes[8]; ID3D11VertexShader *vertexShader; ID3D11PixelShader *pixelShaders[NUM_SHADERS]; int blendModesCount; D3D11_BlendMode *blendModes; ID3D11SamplerState *nearestPixelSampler; ID3D11SamplerState *linearSampler; D3D_FEATURE_LEVEL featureLevel; /* Rasterizers */ ID3D11RasterizerState *mainRasterizer; ID3D11RasterizerState *clippedRasterizer; /* Vertex buffer constants */ VertexShaderConstants vertexShaderConstantsData; ID3D11Buffer *vertexShaderConstants; /* Cached renderer properties */ DXGI_MODE_ROTATION rotation; ID3D11RenderTargetView *currentRenderTargetView; ID3D11RasterizerState *currentRasterizerState; ID3D11BlendState *currentBlendState; ID3D11PixelShader *currentShader; ID3D11ShaderResourceView *currentShaderResource; ID3D11SamplerState *currentSampler; SDL_bool cliprectDirty; SDL_bool currentCliprectEnabled; SDL_Rect currentCliprect; SDL_Rect currentViewport; int currentViewportRotation; SDL_bool viewportDirty; Float4X4 identity; int currentVertexBuffer; } D3D11_RenderData; #endif #endif
'use strict'; const path = require('path'); const fs = require('fs'); /** * package.json リーダ */ class PackageJson { readPackageJsonFromCwd() { this.readPackageJson(path.join(process.cwd(), "package.json")); } readPackageJson(path) { if (fs.existsSync(path)) { try { // package.json をロードする const data = fs.readFileSync(path, "utf8"); this.parsePackageJson(data); } catch (e) { console.error("package.json load error: " + e); throw e; } } else { console.error("no package.json"); throw new Error("No package.json"); } } parsePackageJson(data) { try { const pkgJson = JSON.parse(data); this.json = pkgJson; this.name = pkgJson.name; this.version = pkgJson.version; } catch (e) { console.error("package.json : parse error: " + e); throw e; } if (!this.name || !this.version) { console.error("No name or version info"); throw new Error("No name or version info"); } } } module.exports = PackageJson;
package de.fhg.aisec.ids.camel.idscp2 import de.fraunhofer.iais.eis.ContractAgreement import java.net.URI import java.util.concurrent.ConcurrentHashMap object ProviderDB { val availableArtifactURIs: ConcurrentHashMap<URI, String> = ConcurrentHashMap() val artifactUrisMapped2ContractAgreements: ConcurrentHashMap<URI, URI> = ConcurrentHashMap() val contractAgreements: ConcurrentHashMap<URI, ContractAgreement> = ConcurrentHashMap() init { availableArtifactURIs[URI.create("https://example.com/some_artifact")] = "AVAILABLE" } }
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class postController extends Controller { //Metodo para exibição da view public function create(){ return view('posts.create');//caminho para a view } //Receber os dados da formulario public function store(Request $request){ } }
package case1; public class Birds { private static void doBirdStuff(Bird bird) { bird.layEgg(); bird.fly(); } public static void main(String[] args) { var pigeon = new Pigeon(); doBirdStuff(pigeon); var penguin = new Penguin(); doBirdStuff(penguin); } }
# Supports multiple database types, for this reason preferred way to create migrations for all # at once is this script. [CmdLetBinding()] Param( [Parameter(Mandatory)] [string] $MigrationName, [ValidateSet("Add", "Remove")] [string] $Operation = "Add" ) if($Operation -eq "Remove") { dotnet ef migrations remove --context "NpSqlDataContext" dotnet ef migrations remove --context "MsSqlDataContext" } else { if(-not $MigrationName) { throw "MigrationName parameter is required when adding new migrations." } dotnet ef migrations add --context "NpSqlDataContextForMigrations" $MigrationName -o ./Migrations/NpSql/ dotnet ef migrations add --context "MsSqlDataContextForMigrations" $MigrationName -o ./Migrations/MsSql/ }
import { CHART_SIZE_CHANGE, HEIGHT_CHANGE, RADIUS_CHANGE, ANGLE_CHANGE, DURATION_CHANGE, FONT_SIZE_CHANGE, TOGGLE_ANIMATION, TOGGLE_SLICE_SELECT, TOGGLE_LABEL, TOGGLE_LABEL_COLOR, TOGGLE_TOOLTIP } from '../constants'; export function changeChartSize(data) { return { type: CHART_SIZE_CHANGE, payload: { data } }; } export function changeHeight(data) { return { type: HEIGHT_CHANGE, payload: { data } }; } export function changeRadius(data) { return { type: RADIUS_CHANGE, payload: { data } }; } export function changeAngle(data) { return { type: ANGLE_CHANGE, payload: { data } }; } export function changeDuration(data) { return { type: DURATION_CHANGE, payload: { data } }; } export function changeFontSize(data) { return { type: FONT_SIZE_CHANGE, payload: { data } }; } export function toggleAnimation() { return { type: TOGGLE_ANIMATION }; } export function toggleSliceSelect() { return { type: TOGGLE_SLICE_SELECT }; } export function toggleLabel() { return { type: TOGGLE_LABEL }; } export function toggleLabelColor() { return { type: TOGGLE_LABEL_COLOR }; } export function toggleTooltip() { return { type: TOGGLE_TOOLTIP }; }
#! /bin/sh #$ -S /bin/sh #$ -cwd -sync y -now n #$ -o $JOB_NAME.$JOB_ID.$TASK_ID.out #$ -e $JOB_NAME.$JOB_ID.$TASK_ID.err err=0 dir=/local/gensoft/libexec/taxoptimizer tmpnotaxo="tmpnotaxo.$$.${SGE_TASK_ID}" outputnotaxo="" # arguments: <outfile> <inlist> <taxOopts...> output=$1 shift input=$(cat $1 | head -n ${SGE_TASK_ID} | tail -n 1) shift # Run the blast command on the expected sequence chunk if test "$1" = '-f' then shift outputnotaxo=$1 shift #echo "1- ${dir}/seqpos input | taxoptimizer -i stdin -f ${tmpnotaxo} ${1+"$@"} || err=1" ${dir}/seqpos ${input} | taxoptimizer -i stdin -f ${tmpnotaxo} ${1+"$@"} || err=2 else #echo "2- ${dir}/seqpos ${input} | taxoptimizer -i stdin ${1+"$@"} || err=1" ${dir}/seqpos ${input} | taxoptimizer -i stdin ${1+"$@"} || err=3 fi if test "${outputnotaxo}" != "" ; then ${dir}/resmerge ${outputnotaxo} ${tmpnotaxo} || err=6 fi # Merge results if exists ... if test -s ${SGE_STDOUT_PATH}; then ${dir}/resmerge ${output} ${SGE_STDOUT_PATH} || err=4 fi if test -s ${SGE_STDERR_PATH}; then ${dir}/resmerge ${output}.err ${SGE_STDERR_PATH} || err=5 fi # Cleanup rm -f ${SGE_STDOUT_PATH} ${SGE_STDERR_PATH} rm -f ${tmpnotaxo} exit $err
using System; using System.Reflection; using UnityEngine; using UnityEngine.Purchasing; namespace Scripts.Purchasing { public static class StencilIap { public static void ApplyPlatformHacks(this IAPButton button, bool update = true) { if (update) { var method = typeof(IAPButton).GetMethod("UpdateText",BindingFlags.NonPublic | BindingFlags.Instance); if (method == null) { Debug.LogError("Missing UpdateText Method"); } else { method.Invoke(button, null); } } ApplyAndroidHack(button); // ApplyEditorHack(button); // this gets confusing after a while. } private static void ApplyAndroidHack(this IAPButton button) { #if UNITY_ANDROID && !UNITY_EDITOR var str = button.titleText?.text; if (str?.Contains("(") == true) button.titleText.text = str.Substring(0, str.IndexOf("(", StringComparison.InvariantCulture) - 1); #endif } private static void ApplyEditorHack(this IAPButton button) { #if UNITY_EDITOR if (button.priceText != null && !button.priceText.text.StartsWith("$")) button.priceText.text = "$" + button.priceText.text; #endif } } }
package com.projectcitybuild.core.contracts interface LoggerProvider { fun verbose(message: String) fun debug(message: String) fun info(message: String) fun warning(message: String) fun fatal(message: String) }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DogScript : MonoBehaviour { Rigidbody rb; float MovementRange = 100; //public Collider Trigger; public GameObject FPPlayer; public GameObject self; public GameObject Timer; // Start is called before the first frame update void Start() { rb = gameObject.GetComponent<Rigidbody>(); } // Update is called once per frame void Update() { rb.AddForce(new Vector3 ( Random.Range(MovementRange,-MovementRange), 0, Random.Range(MovementRange,-MovementRange) )); if (DogTimerScript.TimeOut == true){ self.SetActive(false); // once we time out -- remove ourselves } } void OnTriggerEnter (Collider other) { AudioSource Bark = gameObject.GetComponent<AudioSource>(); Bark.Play(); if(other.gameObject == FPPlayer) { //collect the dog GameManager.DogCaught = true; UIStoryScript.SuccessDogCatch(); Timer.SetActive(false); self.SetActive(false); //turn off myself } } }
<?php namespace App\Models; use App\Traits\CustomModel; use App\User; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use App\Traits\EventsTrait; class Type_Info extends Model { use SoftDeletes, EventsTrait, CustomModel; // public $fieldName = 'name'; protected $table = 'type_infos'; protected $with = ['beneficiary_info']; protected $fillable = [ 'deleted_at', 'is_enabled', 'created_by', 'modified_by', 'user_id', 'type_id', ]; /** Relations ----------- */ public function party_info() { return $this->hasOne(Party_Info::class, 'type_infos_id'); } public function beneficiary_info() { return $this->hasOne(Beneficiary_Info::class, 'type_infos_id'); } public function user() { return $this->belongsTo(User::class); } /*======= ========= ============ | extra functionality... | ======= ========= ============*/ public static function getModelAttributes($model) { $classAttributes = ['user_id', 'type_id']; $result = ''; foreach($classAttributes as $attr){ $result.= ($attr . ': ' . $model->$attr . ', '); } return $result; } }
/* * gstat header file * */ #include "gallups.h" #define VERBOSE 1 #define QUIET 2 #define prompt(f...) #define show(f...) if(gsflags&VERBOSE)printf(##f) extern int gsflags; extern char hand[4]; extern char galname[128]; extern int WIDTH; extern struct curargs CA; #if 0 #define _T(t) TEMH_##t,TEMT_##t,TEMF_##t,TEMS_##t,TEMGH_##t,TEMGT_##t,TEMGF_##t,TEMGS_##t #define _TT(t,v) {TEMH_##t, #v"_header", NULL}, \ {TEMT_##t, #v"_template", NULL}, \ {TEMF_##t, #v"_footer", NULL}, \ {TEMS_##t, #v"_separator", NULL}, \ {TEMGH_##t, #v"_gheader", NULL}, \ {TEMGT_##t, #v"_gtemplate", NULL}, \ {TEMGF_##t, #v"_gfooter", NULL}, \ {TEMGS_##t, #v"_gseparator", NULL} /* alsways TEM_LAST should exist at the end */ enum tem_macros { _T(SO), _T(SOS), _T(SOA), _T(SOSA), _T(CO), _T(COS), _T(COA), _T(COSA), TEM_AGES, TEM_BARWIDTH, TEM_LAST}; struct _tem_data { int tem_type; char tem_name[30]; char *template; }; extern struct _tem_data tem_data[]; #endif extern int *ages; struct curargs { int *fields; int curoption; int curfield; int currow; int curcol; int *row_p_sum; int *col_p_sum; int row_t_sum; int col_t_sum; int *fld_p_sum; int comboidx; }; extern struct curargs CA; /* * The implementation of the algorithm is as follows: * make the classes were each question can be put * Classes can be created for every possible key * i.e. answer, age, sex * * Each class is handled by its specific handler */ #define FL_OPT 0x01 #define FL_OPTSEX 0x02 #define FL_OPTAGE 0x04 #define FL_OPTSEXAGE 0x08 #define GMAXCLASS 5 #define CMD_SIZE 1 #define CMD_IDX 2 #define CMD_PRM 3 /* this structure contains every possible class key */ /* add more key fields here */ struct userdata { char userid[24]; int age; char sex; char **anscomidx; int anscomfld; int anscompos; }; extern struct question *curquest; extern struct answer *curans; extern struct userdata user, *curuser; extern char curprompt[128]; /* tree.c */ #define key_set(k,f...) _key_set(k, ##f, -1) /* tree node, leafcount can be used to hold the data wanted */ struct treenode { struct treenode *leafs; int leafcount; }; extern struct treenode tree; /* [0] holds the size of the key */ typedef int treekey_t[GMAXCLASS+1]; void tree_setup(void); void tree_addleaf(struct treenode *n, int size); void tree_addlevel(struct treenode *n, int size); void tree_init(treekey_t key); void tree_freelevel(struct treenode *n); void tree_free(void); struct treenode *tree_getleaf(struct treenode *n, treekey_t key, int idx); struct treenode *tree_search(treekey_t key); void _key_set(treekey_t key, ...); int key_next(treekey_t key, const treekey_t mask); void key_copy(treekey_t dst, treekey_t src); void test_tree(void); /* handler.c */ typedef void (*handler_t)(int, void *); extern handler_t class_handlers[GMAXCLASS]; extern int handler_count; int handler_register(handler_t handler); void handler_init(void); void class_options_handler(int cmd, void *d); void class_sex_handler(int cmd, void *d); void class_age_handler(int cmd, void *d); void class_choices_handler(int cmd, void *d); int handlers_init(void); int class_sum(treekey_t key, treekey_t mask); /* selout.c */ void dump_select(int flag); void dump_select_options(void); void dump_select_options_sex(void); void dump_select_options_age(void); void dump_select_options_sex_age(void); void chart_select_options(void); void chart_select_options_sex(void); void chart_select_options_age(void); void chart_select_options_sex_age(void); /* comout.c */ void dump_combo(int flag); void dump_combo_options(void); void dump_combo_options_sex(void); void dump_combo_options_age(void); void dump_combo_options_sex_age(void); void chart_combo_options(void); void chart_combo_options_sex(void); void chart_combo_options_age(void); void chart_combo_options_sex_age(void); extern int WIDTH; typedef void (*dump_func)(void); /* templates.c */ extern int userlang; void args_init(void); /* gprintf.c */ void init_printf(void); void load_ca(int copt, int cfld, int crow, int ccol); char *strndup(char *s, int c, size_t size); void alloc_ca(int size, int elem); void free_ca(void); void gather_ca(int rows, int cols); void gather_cax(int rows, int cols, int fields, int fcount); int dump(int prm, ...);
#!/usr/bin/env bash cygwin_mount_dir=$(mount | grep "cygwin64 on" | awk '{print $1}') # fix for cygwin64 users tmp_dir=${cygwin_mount_dir}$(mktemp -d -t ci-XXXXXXXXXX) printf "Building ...\n" OUTPUT=$(go build ./...) if echo "$OUTPUT" | grep -q "FAIL"; then echo 'Build failed' >/dev/stderr printf "%s\\n" "$OUTPUT" exit fi # @ToDo: Replace default test coverage tool with https://github.com/grosser/go-testcov printf "Testing ...\n" mkdir -p "${tmp_dir}/.out" OUTPUT=$(go test -v -test.short -coverprofile=${tmp_dir}/.out/c.out -covermode=atomic ./...) if echo "$OUTPUT" | grep -q "FAIL"; then echo 'Tests failed' >/dev/stderr printf "%s\\n" "$OUTPUT" exit fi go tool cover -html=${tmp_dir}/.out/c.out -o ${tmp_dir}/.out/coverage.html printf "%s\n" "Test coverage results has been persisted into: file://${tmp_dir}/.out/coverage.html"
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Tema extends Model { protected $table = 'temas'; public $timestamps = false; public function idiomas(){ return $this->hasMany(Idioma_Tema::class, 'temas_id'); } public function publicaciones(){ return $this->belongsToMany('App\Publicacion', 'publicaciones_has_temas', 'publicaciones_id', 'temas_id'); } public function areasconocimiento(){ return $this->belongsToMany('App\AreasConocimiento', 'areas_conocimiento', 'areas_conocimiento_id', 'temas_id'); } public function getNombreEs(){ return $this->idiomas->where("idiomas_id",1)->first(); } }
package limitedbuffer import "fmt" // CycleBufferStatus cycleBuffer Status type CycleBufferStatus struct { capacity int unreadSize int freeWriteSpace int totalRead int64 totalWrite int64 } // Capacity 缓冲区大小 func (cb *CycleBufferStatus) Capacity() int { return cb.capacity } // UnreadSize 可读数据量 func (cb *CycleBufferStatus) UnreadSize() int { return cb.unreadSize } // FreeWriteSpace 可写数据量 func (cb *CycleBufferStatus) FreeWriteSpace() int { return cb.freeWriteSpace } // TotalRead 已读量 func (cb *CycleBufferStatus) TotalRead() int64 { return cb.totalRead } // TotalWrite 已写量 func (cb *CycleBufferStatus) TotalWrite() int64 { return cb.totalWrite } var _ BufferStatus = (*CycleBufferStatus)(nil) type cycleBuffer struct { capacity int // max length cbuf []byte // fixed buffer rpos int // reader position wpos int // writer position totalRead int64 totalWrite int64 } func (c *cycleBuffer) status() BufferStatus { var unreadSize int = 0 var freeWriteSpace int = 0 var capacity = c.capacity if c.isEmpty() { unreadSize = 0 } else { if c.wpos > c.rpos { unreadSize = c.wpos - c.rpos } else { unreadSize = capacity - c.rpos + c.wpos } } if c.isFull() { freeWriteSpace = 0 } else { if c.rpos == 0 || c.rpos == 1 { freeWriteSpace = capacity - c.wpos } else { if c.wpos == c.rpos { freeWriteSpace = capacity - 1 } else if c.wpos > c.rpos { freeWriteSpace = capacity - c.wpos + c.rpos - 1 } else { freeWriteSpace = c.rpos - c.wpos - 1 } } } return &CycleBufferStatus{ capacity: capacity, unreadSize: unreadSize, freeWriteSpace: freeWriteSpace, totalRead: c.totalRead, totalWrite: c.totalWrite, } } // Status 当前状态 func (c *cycleBuffer) Status() BufferStatus { return c.status() } func (c *cycleBuffer) String() string { status := c.status() return fmt.Sprintf( "<cycleBuffer(cap=%d rpos=%d wpos=%d unread=%d freewrite=%d totalRead=%d totalWrite=%d)> at %p", c.capacity, c.rpos, c.wpos, status.UnreadSize(), status.FreeWriteSpace(), c.totalRead, c.totalWrite, c) } func (c *cycleBuffer) isEmpty() bool { return c.rpos == c.wpos } // 如果 rpos == 1 or 0, wpos == capacity,则不能写 func (c *cycleBuffer) isFull() bool { if c.rpos > 1 { return c.wpos == c.rpos-1 } return c.wpos == c.capacity } func (c *cycleBuffer) reset() { c.rpos = 0 c.wpos = 0 } func (c *cycleBuffer) IsFull() bool { ret := c.isFull() return ret } func (c *cycleBuffer) IsEmpty() bool { ret := c.isEmpty() return ret } func (c *cycleBuffer) Reset() { c.reset() } func (c *cycleBuffer) read(p []byte) (n int, err error) { if c.isEmpty() { n = 0 err = ErrNotAvailableData return } n1 := 0 n2 := 0 if c.wpos > c.rpos { n1 = copy(p, c.cbuf[c.rpos:c.wpos]) } else { n1 = copy(p, c.cbuf[c.rpos:c.capacity]) tail := c.capacity - c.rpos if n1 == tail && c.wpos > 0 { n2 = copy(p[n1:], c.cbuf[0:c.wpos]) } } if n2 > 0 { c.rpos = n2 } else { c.rpos += n1 } n = n1 + n2 if n > 0 { c.totalRead += int64(n) } return } func (c *cycleBuffer) Read(p []byte) (n int, err error) { n, err = c.read(p) return } // 写操作,最多能循环写到 rpos - 1 // // 如果 rpos == 0, wpos == 0 // 最多可以写到 capacity, 写完后 wpos == capacity // // 如果 rpos > 1, wpos >= rpos // 最多可以写 capacity - wpos + rpos - 1,写完后 wpos = rpos - 1 func (c *cycleBuffer) write(p []byte) (n int, err error) { if c.isFull() { n = 0 err = ErrNotAvailableSpace return } if c.isEmpty() && c.wpos == c.capacity { c.reset() } n1 := 0 n2 := 0 tail := c.capacity - c.wpos n1 = copy(c.cbuf[c.wpos:c.capacity], p) if n1 == tail && c.rpos > 1 { n2 = copy(c.cbuf[0:c.rpos-1], p[n1:]) } if n2 > 0 { c.wpos = n2 } else { c.wpos += n1 } n = n1 + n2 if n > 0 { c.totalWrite += int64(n) } return } func (c *cycleBuffer) Write(p []byte) (n int, err error) { n, err = c.write(p) return } func (c *cycleBuffer) Capacity() int { return c.capacity } var _ LimitedBuffer = (*cycleBuffer)(nil) func newCycleBuffer(capacity int) *cycleBuffer { cb := &cycleBuffer{ capacity: capacity, cbuf: make([]byte, capacity), rpos: 0, wpos: 0, totalRead: 0, totalWrite: 0, } return cb } // NewCycleBuffer New CyclyBuffer func NewCycleBuffer(capacity int) LimitedBuffer { return newCycleBuffer(capacity) }
#!/bin/bash -ex CORE="automake autoconf libtool make curl $CC" case "$1" in multiarch/debian-*|multiarch/ubuntu-*) apt-get update apt-get -y install $CORE build-essential ;; multiarch/fedora:*) [ "$CC" == "clang" ] && rt=compiler-rt dnf -y install $CORE $rt ;; multiarch/centos:*) yum -y install $CORE gcc ;; esac autoreconf -if if ! CFLAGS=-coverage LDFLAGS=-lgcov ./configure --prefix=/usr; then cat ./config.log exit 1 fi make -j8 -k check V=1 TESTS= if ! make -j8 check; then cat ./test-suite.log exit 1 fi bash <(curl -s https://codecov.io/bash)
self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request).then(response => { return response || fetch(event.request).then(function (_response) { // console.log("fetch:"+event.request.url); return _response; }); }) ); }); /* const STATIC_CACHE_KEY = '1'; self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request).then(response => { return response || fetch(event.request).then(function(_response) { console.log("cache.put:"+event.request.url); caches.open(STATIC_CACHE_KEY).then(function(cache) { console.log("_response:"+_response); cache.put(event.request, _response.clone()); }); return _response; }); }) ); }); */
## 星座择偶关键词 ### 标签定义 - 1w以下 冷 - 1w~5w ! - 5w~50w !! - 50w~100w !!! - 100w~300w !!!! - 300w以上 !!!!! ### 择偶关键词 - 甜 - 猜不透 #!!! #有歌 - 主动 #!! - 超独立 #冷 - 烂桃花 #冷 - 直觉准 #! - 看似高冷但 #! - 好相处 #! - 外冷内热 #! - 戒备心 #冷 - 看似铁憨憨但 #!! - 暗恋&不主动 #! - 被驾驭 #! - 桃花运 #! - 沙雕 #冷 - 背叛 #!!! - 不能惹 #!! - 好相处 #! - 装傻 #!! - 一个人更好过/high #!!!! #已写 - 第六感强 #!!! - 找对象眼光差 - 逼人分手 #!! - 伤你最深 - 不发脾气 #!! - 渣男 #冷 - 假装快乐 #!!! - 被伤害 #!!!! - 一物降一物 #!! - 别带XX去择偶(eg:酒吧) #!! - 不要死缠烂打 #!! - 难追 #! - 容易说谎 #! - 谈恋爱什么感觉 #!! - 绝配cp #! 这几个对标视频的涨粉数据。针对男号和女号做不同的文案调整,男号是偏小清新,上知乎搜,日文翻译成中文的语言风格。女性需要讨论。怎么起标题,需要控制在35~45s之间。 ## 剧情类 - 星座&吃鸡 #!! #2019 - 星座&第五人格 #!! #2019 ## Changelog 2020-09-21 16:32:32 创建
# PsyCheck - Psychic Checkbook A simple recurring transaction scheduler with balance forcasting ## Setup Create a database using the schema located in `ironsigma/database` directory. Create a `.env` file with the following properties: ``` properties DB_HOST=localhost DB_PORT=3306 DB_USER=user DB_PASS=pass DB_NAME=checkbook ``` ## MariaDB Connector Make sure the following packages are installed: - python3-devel - mariadb-connector-c-devel then install as usual: ```bash pip install mariadb ``` ## Running App To run the app in development mode use the following: ``` shell sanic --debug --reload --access-logs --worker 1 --factory ironsigma.app:create ```
package org.gbif.nub.lookup; import org.gbif.api.model.checklistbank.NameUsageMatch; import org.gbif.api.model.common.LinneanClassification; import org.gbif.api.service.checklistbank.NameUsageMatchingService; import org.gbif.checklistbank.service.mybatis.guice.ChecklistBankServiceMyBatisModule; import org.gbif.utils.file.properties.PropertiesUtil; import java.io.IOException; import java.util.Properties; import com.google.inject.Guice; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NubMatchingServiceTestManual { private static final Logger LOG = LoggerFactory.getLogger(NubMatchingServiceTestManual.class); private final NameUsageMatchingService matcher; public NubMatchingServiceTestManual() throws IOException { LOG.info("Load clb properties"); Properties properties = PropertiesUtil.loadProperties("checklistbank.properties"); LOG.info("Create guice injector"); Injector inj = Guice.createInjector(new ChecklistBankServiceMyBatisModule(properties), new NubMatchingModule()); LOG.info("Create matching service"); matcher = inj.getInstance(NameUsageMatchingService.class); LOG.info("Nub Matching setup complete"); } public void testMatching() throws IOException { LinneanClassification cl = new NameUsageMatch(); // test identical matcher.match("Animalia", null, cl, true, true); matcher.match("Animals", null, cl, true, true); matcher.match("Insects", null, cl, true, true); cl.setKingdom("Animalia"); matcher.match("Puma concolor", null, cl, true, true); cl.setKingdom("Plantae"); matcher.match("Puma concolor", null, cl, true, true); } public static void main (String[] args) throws IOException { NubMatchingServiceTestManual test = new NubMatchingServiceTestManual(); test.testMatching(); } }
rm -f tests/s3.dat if ./mkstu tests/stu3 tests/s3.dat then if [ -f tests/s3.dat ] then ./stu tests/s3.dat fi fi
"""This is the sci_analysis package. Sub packages: data - sci_analysis data types analysis - sci_analysis test and calculation classes and functions graphs - graphing classes The analysis and operations modules are loaded. The following classes are imported so that they are exposed at a high level: Vector, NormTest, GroupNormTest, LinearRegression, Correlation, Anova, Kruskal, EqualVariance, VectorStatistics, GroupStatistics, GraphHisto, GraphScatter and GraphBoxplot. The following methods are imported so that they are exposed at a high level: analyze, clean and strip. """ # from __future__ import absolute_import # from sci_analysis.analysis import analysis # from sci_analysis.graphs import graph # from sci_analysis.data import data __all__ = ["data", "analysis", "graphs"] from .analysis import analyze, analyse # from .analysis.analysis import Comparison, NormTest, TTest, LinearRegression,\ # Correlation, Anova, Kruskal, EqualVariance, VectorStatistics, GroupStatistics
CREATE EXTERNAL TABLE ${0} (id int, str text, num int) using csv location ${table.path};
package kspt.bank import kspt.bank.enums.CellApplicationStatus import kspt.bank.enums.CellSize enum class ChoosableCellSize(val displayName: String) { SMALL ("Малый (1 л)"), MEDIUM ("Средний (2 л)"), BIG ("Большой (4 л)"); override fun toString(): String { return this.displayName } } enum class CellStatus(val displayName: String) { BOOKED ("Ожидает одобрения"), AWAITING ("Ождиает оплаты"), PAID ("Оплачена"); override fun toString(): String { return this.displayName } } enum class ChoosablePaymentMethod(val displayName: String) { CARD ("Банковская карта"), CASH ("Наличные"); override fun toString(): String { return this.displayName } } fun CellSize.asChoosableCellSize(): ChoosableCellSize { return when (this) { CellSize.SMALL -> ChoosableCellSize.SMALL CellSize.MEDIUM -> ChoosableCellSize.MEDIUM CellSize.BIG -> ChoosableCellSize.BIG } } fun CellApplicationStatus.asCellStatus(): CellStatus { return when (this) { CellApplicationStatus.CELL_CHOSEN -> CellStatus.BOOKED; CellApplicationStatus.APPROVED -> CellStatus.AWAITING; CellApplicationStatus.PAID -> CellStatus.PAID; else -> throw IllegalStateException("Non-convertible cell application status!") } }
module Lexer where import Text.Parsec (letter, alphaNum, (<|>), char, between) import Text.Parsec.String (Parser) import Text.Parsec.Language (emptyDef) import qualified Text.Parsec.Token as Token reservedNameImport :: String reservedNameImport = "import" reservedNameFrom :: String reservedNameFrom = "from" -- * Wasp element types reservedNameApp :: String reservedNameApp = "app" reservedNamePage :: String reservedNamePage = "page" reservedNameButton :: String reservedNameButton = "button" reservedNameAction :: String reservedNameAction = "action" reservedNameEntity :: String reservedNameEntity = "entity" reservedNameEntityForm :: String reservedNameEntityForm = "entity-form" reservedNameEntityList :: String reservedNameEntityList = "entity-list" -- * Data types. reservedNameString :: String reservedNameString = "string" reservedNameBoolean :: String reservedNameBoolean = "boolean" reservedNameBooleanTrue :: String reservedNameBooleanTrue = "true" reservedNameBooleanFalse :: String reservedNameBooleanFalse = "false" reservedNames :: [String] reservedNames = [ reservedNameImport , reservedNameFrom -- * Wasp element types , reservedNameApp , reservedNamePage , reservedNameEntity , reservedNameEntityForm , reservedNameButton , reservedNameAction -- * Data types , reservedNameString , reservedNameBoolean , reservedNameBooleanTrue , reservedNameBooleanFalse ] waspLanguageDef :: Token.LanguageDef () waspLanguageDef = emptyDef { Token.commentLine = "//" , Token.reservedNames = reservedNames , Token.caseSensitive = True -- Identifier , Token.identStart = letter , Token.identLetter = alphaNum <|> char '_' } waspLexer :: Token.TokenParser () waspLexer = Token.makeTokenParser waspLanguageDef reserved :: String -> Parser () reserved = Token.reserved waspLexer identifier :: Parser String identifier = Token.identifier waspLexer symbol :: String -> Parser String symbol = Token.symbol waspLexer colon :: Parser String colon = Token.colon waspLexer braces :: Parser a -> Parser a braces = Token.braces waspLexer -- Parses content between '<' and '>'. angles :: Parser a -> Parser a angles = Token.angles waspLexer commaSep :: Parser a -> Parser [a] commaSep = Token.commaSep waspLexer commaSep1 :: Parser a -> Parser [a] commaSep1 = Token.commaSep1 waspLexer whiteSpace :: Parser () whiteSpace = Token.whiteSpace waspLexer singleQuotes :: Parser a -> Parser a singleQuotes p = between (symbol "'") (symbol "'") p stringLiteral :: Parser String stringLiteral = Token.stringLiteral waspLexer -- * Parsing boolean values bool :: Parser Bool bool = boolTrue <|> boolFalse boolTrue :: Parser Bool boolTrue = reserved reservedNameBooleanTrue *> return True boolFalse :: Parser Bool boolFalse = reserved reservedNameBooleanFalse *> return False
export const GROUPS_MAP = { 'москва': -80526909, 'санктпетербург': -112592338, 'дубна': -81471037, 'екатеринбург': -50579357, 'новосибирск': -33347300, 'оренбург': -50657589, 'казань': -132745002, 'челябинск': -90435717, 'красноярск': -50657203, 'сосновыйбор': -92796438, 'нижнийновгород': -60501159, 'тюмень': -127274420, };
package com.example.projectandroidadmin.model import android.media.Image import android.widget.ImageView import java.net.URL data class BannerModel( val id: Int, val name: String, val imageUrl: String ) val bannerList = listOf( BannerModel(1, "Banner 1", "https://blogpictures.99.co/sumber-josscoid.jpg"), BannerModel(2, "Banner 2", "https://picsum.photos/id/1039/6945/4635"), BannerModel(3, "Banner 3", "https://picsum.photos/id/1038/3914/5863"), BannerModel(4, "Banner 4", "https://picsum.photos/id/1037/5760/3840") )
<?php namespace Laravel\Scout\Jobs; use Illuminate\Database\Eloquent\Collection; use Laravel\Scout\Searchable; class RemoveableScoutCollection extends Collection { /** * Get the Scout identifiers for all of the entities. * * @return array */ public function getQueueableIds() { if ($this->isEmpty()) { return []; } return in_array(Searchable::class, class_uses_recursive($this->first())) ? $this->map->getScoutKey()->all() : parent::getQueueableIds(); } }
package generate import "github.com/go-swagger/go-swagger/generator" type Cli struct { // generate a cli includes all client code Client } func (c Cli) apply(opts *generator.GenOpts) { c.Client.apply(opts) opts.IncludeCLi = true opts.CliPackage = "cli" // hardcoded for now, can be exposed via cmd opt later } func (c *Cli) generate(opts *generator.GenOpts) error { return c.Client.generate(opts) } // Execute runs this command func (c *Cli) Execute(args []string) error { return createSwagger(c) }
using System.Collections.Generic; using UnityEngine; public class Projectiled : MonoBehaviour { [HideInInspector] public float damage, range; [SerializeField] float speed, piercing; float _piercing; public string belong; float travelled; Vector2 prevPos; public TrailRenderer trail; [SerializeField] Rigidbody2D rb; List<Collider2D> hitted = new List<Collider2D>(); public Collider2D col; void OnEnable() { //Clear the collider got hit hitted.Clear(); hitted = new List<Collider2D>(); //No longer ignore all the collider has hit foreach (Collider2D hit in hitted) {Physics2D.IgnoreCollision(col, hit, false);} //If there is trial if(trail != null) { //Clear the trail trail.Clear(); //Reassign this trial to be projectile child trail.transform.parent = transform; //Reset the trail position trail.transform.localPosition = Vector2.zero; //Clear the trail trail.Clear(); } //Update the previous position prevPos = transform.position; //Reset piercing _piercing= piercing; //Reset the travelld distance travelled = range; } void Update() { //If the previous position has change if((Vector2)transform.position != prevPos) //Decrease travelled using the distance between current position and previous position {travelled -= Vector2.Distance(transform.position, prevPos);} //Update the previous position prevPos = transform.position; //Deactive the projectile when travel all the range if(travelled <= 0) {DeactiveProjectile();} //Update the bullet velocity as the speed stats at transfrom right rb.velocity = transform.up * speed; } void OnCollisionEnter2D(Collision2D other) { //If this object belong to allies and hit an enemy if(belong == "Allies" && other.collider.CompareTag("Enemy")) { //Deal damage to the enemy other.collider.GetComponent<Heath>().Damaging(damage); //Has pierced Pierced(); } //If this object belong to enemy and hit an allies if(belong == "Enemy" && other.collider.CompareTag("Allies")) { //Deal damage to the allies other.collider.GetComponent<Heath>().Damaging(damage); //Has pierced Pierced(); } //Deactive the projectile if collide with wall if(other.collider.CompareTag("Wall")) {DeactiveProjectile();} //Ignore colliision of the object it collide with Physics2D.IgnoreCollision(col, other.collider); hitted.Add(other.collider); } //Lost an piercing and deactive object when out of piercing void Pierced() {_piercing--; if(_piercing <= 0) {gameObject.SetActive(false);}} //Deactive the propjectile and remove the trial parent void DeactiveProjectile() {gameObject.SetActive(false); if(trail != null) trail.transform.parent = null;} }
/// /// Copyright © 2016-2021 The Thingsboard Authors /// /// 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. /// import { Component, Inject, OnInit, SkipSelf } from '@angular/core'; import { ErrorStateMatcher } from '@angular/material/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { FormBuilder, FormControl, FormGroup, FormGroupDirective, NgForm, Validators } from '@angular/forms'; import { DeviceService } from '@core/http/device.service'; import { EdgeService } from '@core/http/edge.service'; import { EntityType } from '@shared/models/entity-type.models'; import { forkJoin, Observable } from 'rxjs'; import { AssetService } from '@core/http/asset.service'; import { EntityViewService } from '@core/http/entity-view.service'; import { DashboardService } from '@core/http/dashboard.service'; import { DialogComponent } from '@shared/components/dialog.component'; import { Router } from '@angular/router'; import { RuleChainService } from '@core/http/rule-chain.service'; import { RuleChainType } from '@shared/models/rule-chain.models'; export interface AddEntitiesToEdgeDialogData { edgeId: string; entityType: EntityType; } @Component({ selector: 'tb-add-entities-to-edge-dialog', templateUrl: './add-entities-to-edge-dialog.component.html', providers: [{provide: ErrorStateMatcher, useExisting: AddEntitiesToEdgeDialogComponent}], styleUrls: [] }) export class AddEntitiesToEdgeDialogComponent extends DialogComponent<AddEntitiesToEdgeDialogComponent, boolean> implements OnInit, ErrorStateMatcher { addEntitiesToEdgeFormGroup: FormGroup; submitted = false; entityType: EntityType; subType: string; assignToEdgeTitle: string; assignToEdgeText: string; constructor(protected store: Store<AppState>, protected router: Router, @Inject(MAT_DIALOG_DATA) public data: AddEntitiesToEdgeDialogData, private deviceService: DeviceService, private edgeService: EdgeService, private assetService: AssetService, private entityViewService: EntityViewService, private dashboardService: DashboardService, private ruleChainService: RuleChainService, @SkipSelf() private errorStateMatcher: ErrorStateMatcher, public dialogRef: MatDialogRef<AddEntitiesToEdgeDialogComponent, boolean>, public fb: FormBuilder) { super(store, router, dialogRef); this.entityType = data.entityType; } ngOnInit(): void { this.addEntitiesToEdgeFormGroup = this.fb.group({ entityIds: [null, [Validators.required]] }); this.subType = ''; switch (this.data.entityType) { case EntityType.DEVICE: this.assignToEdgeTitle = 'device.assign-device-to-edge-title'; this.assignToEdgeText = 'device.assign-device-to-edge-text'; break; case EntityType.RULE_CHAIN: this.assignToEdgeTitle = 'rulechain.assign-rulechain-to-edge-title'; this.assignToEdgeText = 'rulechain.assign-rulechain-to-edge-text'; this.subType = RuleChainType.EDGE; break; case EntityType.ASSET: this.assignToEdgeTitle = 'asset.assign-asset-to-edge-title'; this.assignToEdgeText = 'asset.assign-asset-to-edge-text'; break; case EntityType.ENTITY_VIEW: this.assignToEdgeTitle = 'entity-view.assign-entity-view-to-edge-title'; this.assignToEdgeText = 'entity-view.assign-entity-view-to-edge-text'; break; case EntityType.DASHBOARD: this.assignToEdgeTitle = 'dashboard.assign-dashboard-to-edge-title'; this.assignToEdgeText = 'dashboard.assign-dashboard-to-edge-text'; break; } } isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean { const originalErrorState = this.errorStateMatcher.isErrorState(control, form); const customErrorState = !!(control && control.invalid && this.submitted); return originalErrorState || customErrorState; } cancel(): void { this.dialogRef.close(false); } assign(): void { this.submitted = true; const entityIds: Array<string> = this.addEntitiesToEdgeFormGroup.get('entityIds').value; const tasks: Observable<any>[] = []; entityIds.forEach( (entityId) => { tasks.push(this.getAssignToEdgeTask(this.data.edgeId, entityId)); } ); forkJoin(tasks).subscribe( () => { this.dialogRef.close(true); } ); } private getAssignToEdgeTask(edgeId: string, entityId: string): Observable<any> { switch (this.data.entityType) { case EntityType.DEVICE: return this.deviceService.assignDeviceToEdge(edgeId, entityId); case EntityType.ASSET: return this.assetService.assignAssetToEdge(edgeId, entityId); case EntityType.ENTITY_VIEW: return this.entityViewService.assignEntityViewToEdge(edgeId, entityId); case EntityType.DASHBOARD: return this.dashboardService.assignDashboardToEdge(edgeId, entityId); case EntityType.RULE_CHAIN: return this.ruleChainService.assignRuleChainToEdge(edgeId, entityId); } } }
#!/bin/bash COUCHDBDIR="/usr/lib/couchdb" COUCHDBBINDIR="$COUCHDBDIR/bin" COUCHDBETCDIR="$COUCHDBDIR/etc" COUCHDBCONFIGDIR="/etc/couchdb" export ERL_FLAGS="-couch_ini $COUCHDBETCDIR/default.ini $COUCHDBCONFIGDIR/local.ini" echo "Welcome!" echo "Starting CouchDB" COUCHDB_BIN_DIR=$(cd $COUCHDBBINDIR && pwd) ERTS_BIN_DIR=$COUCHDB_BIN_DIR/../ cd "$COUCHDB_BIN_DIR/../" export ROOTDIR=${ERTS_BIN_DIR%/*} START_ERL=`cat "$ROOTDIR/releases/start_erl.data"` ERTS_VSN=${START_ERL% *} APP_VSN=${START_ERL#* } export BINDIR="$ROOTDIR/erts-$ERTS_VSN/bin" export EMU=beam export PROGNAME=`echo $0 | sed 's/.*\///'` exec "$BINDIR/erlexec" -boot "$ROOTDIR/releases/$APP_VSN/couchdb" \ -args_file "$COUCHDBCONFIGDIR/vm.args" \ -config "$ROOTDIR/releases/$APP_VSN/sys.config"
require 'game' TEST_CASES = { [0] => [0], [0, 0] => [0], [0, 0, 0] => [0, 0], [0, 0, 0, 0] => [0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] => [30, 60, 90, 120, 150, 180, 210, 240, 270, 300], [0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0] => [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], [1, 4, 4, 5, 6, 4, 5, 5, 10, 0, 1, 7, 3, 6, 4, 10, 2, 8, 6] => [5,14,29,49,60,61,77,97,117,133] } describe Game do describe '.create' do it "should create an instance of a Game" do expect(Game.create).to be_a Game end end context ".score" do it "should receive with one argument" do expect(Game.create).to respond_to(:score).with(1).argument end TEST_CASES.each do |input, output| it "returns #{output} when the input is #{input}" do result = Game.create.score(input) expect(result).to eq output end end end end
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Image } from 'react-native'; import { Container, Content, Text, Icon, List, ListItem } from 'native-base'; import navigateTo from '../../actions/sideBarNav'; import styles from './style'; const singUp = require('../../../images/BG-signUp.png'); class SideBar extends Component { static propTypes = { navigateTo: React.PropTypes.func, } navigateTo(route) { this.props.navigateTo(route, 'home'); } render() { return ( <Container> <Image source={singUp} style={styles.background} > <Content style={styles.drawerContent}> <List foregroundColor={'white'} > <ListItem button iconLeft onPress={() => this.navigateTo('home')} style={styles.links} > <Icon name="ios-grid-outline" /> <Text style={styles.linkText} >HOME</Text> </ListItem> <ListItem button iconLeft onPress={() => this.navigateTo('blankPage')} style={styles.links} > <Icon name="ios-keypad-outline" /> <Text style={styles.linkText}>BLANK PAGE</Text> </ListItem> </List> </Content> </Image> </Container> ); } } function bindAction(dispatch) { return { navigateTo: (route, homeRoute) => dispatch(navigateTo(route, homeRoute)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, }); export default connect(mapStateToProps, bindAction)(SideBar);
@testset "Lines" begin @testset "linesegment intersect" begin a = LineSegment(Point2f0(0,0), Point2f0(1,0)) b = LineSegment(Point2f0(0.5,0.5), Point2f0(0.5,-0.5)) result = intersects(a,b) @test result[1] == true @test result[2] ≈ Point2f0(0.5,0.0) a = LineSegment(Point2f0(0,0), Point2f0(0.499,0)) b = LineSegment(Point2f0(0.5,0.5), Point2f0(0.5,-0.5)) result = intersects(a,b) @test intersects(a,b) == (false, zero(Point2f0)) l = LineSegment(Point(6.0,11), Point(12.0,11)) r1 = LineSegment(Point(9.0,10.0), Point(9.0, 13.0)) r2 = LineSegment(Point(9.34365, 10.890), Point(9.34365, 13.402)) intersect, p = intersects(l, r2) @test intersect @test p ≈ Point(9.34365, 11.0) intersect, p = intersects(l, r1) @test intersect @test p ≈ Point(9.0, 11.0) end @testset "linesegment intersect: #133" begin s1 = LineSegment(Point{2,Float64}[[0.88033, 1.28211], [3.525, 1.28211]]...) s2 = LineSegment(Point{2,Float64}[[2.0375, 1.1625], [2.0375, 1.2875]]...) s1_old = deepcopy(s1) s2_old = deepcopy(s2) result = GeometryTypes.intersects(s1, s2) @test s1 == s1_old # make sure it doesn't mutate inputs @test s2 == s2_old # make sure it doesn't mutate inputs @test result[1] == true @test result[2] ≈ Point(2.0375, 1.28211) end @testset "poly self intersections" begin p1 = Point2f0[(x, sin(x)) for x in 0:.5:6] p2 = Point2f0[(p1[i][1], 0) for i=length(p1):-1:1] points = vcat(p1, p2) inds, intersects = self_intersections(points) @test inds == [7,19] @test intersects ≈ Point2f0[(3.1434426,0.0)] polys = split_intersections(points) @test length(polys) == 2 @test length(polys[1]) == 12 @test length(polys[2]) == 15 u = range(0, stop=2pi, length=200) points = Point2f0[(sin(x), sin(2x)) for x in u] inds, intersects = self_intersections(points) @test inds == [1,100] @test intersects == Point2f0[(0.0,0.0)] polys = split_intersections(points) @test length(polys) == 2 @test length(polys[1]) == 99 @test length(polys[2]) == 102 end end
create table tb_proposal ( id bigint primary key auto_increment, document varchar(255) not null, email varchar(255) not null, name varchar(255) not null, address varchar(255) not null, salary decimal(10,2) not null ) engine=InnoDB default charset=utf8mb4;
# --- !Ups ALTER TABLE roles ADD COLUMN permission BIT(64) NOT NULL DEFAULT B'0'::BIT(64); UPDATE roles r SET permission = (-1)::BIT(64) WHERE r.name = 'Ore_Admin'; UPDATE roles r SET permission = (1::BIT(64) << 27) | (1::BIT(64) << 26) | (1::BIT(64) << 25) | (1::BIT(64) << 24) WHERE r.name = 'Ore_Mod'; UPDATE roles r SET permission = (1::BIT(64) << 32) | (1::BIT(64) << 34) | (1::BIT(64) << 35) | (1::BIT(64) << 40) WHERE r.name = 'Ore_Dev'; UPDATE roles r SET permission = (1::BIT(64) << 32) | (1::BIT(64) << 35) WHERE r.name = 'Web_Dev'; UPDATE roles r SET permission = (1::BIT(64) << 2) | (1::BIT(64) << 4) | (1::BIT(64) << 5) | (1::BIT(64) << 6) | (1::BIT(64) << 10) | (1::BIT(64) << 14) | (1::BIT(64) << 12) | (1::BIT(64) << 13) | (1::BIT(64) << 15) | (1::BIT(64) << 9) WHERE r.name = 'Project_Owner'; UPDATE roles r SET permission = (1::BIT(64) << 12) | (1::BIT(64) << 13) | (1::BIT(64) << 15) | (1::BIT(64) << 9) WHERE r.name = 'Project_Developer'; UPDATE roles r SET permission = (1::BIT(64) << 9) WHERE r.name = 'Project_Editor'; UPDATE roles r SET permission = (1::BIT(64) << 2) | (1::BIT(64) << 6) | (1::BIT(64) << 5) | (1::BIT(64) << 1) | (1::BIT(64) << 10) | (1::BIT(64) << 14) | (1::BIT(64) << 8) | (1::BIT(64) << 4) | (1::BIT(64) << 12) | (1::BIT(64) << 13) | (1::BIT(64) << 15) | (1::BIT(64) << 9) | (1::BIT(64) << 21) WHERE r.name = 'Organization_Owner' OR r.name = 'Organization'; UPDATE roles r SET permission = (1::BIT(64) << 2) | (1::BIT(64) << 5) | (1::BIT(64) << 1) | (1::BIT(64) << 10) | (1::BIT(64) << 14) | (1::BIT(64) << 8) | (1::BIT(64) << 4) | (1::BIT(64) << 12) | (1::BIT(64) << 13) | (1::BIT(64) << 15) | (1::BIT(64) << 9) | (1::BIT(64) << 21) WHERE r.name = 'Organization_Admin'; UPDATE roles r SET permission = (1::BIT(64) << 8) | (1::BIT(64) << 4) | (1::BIT(64) << 12) | (1::BIT(64) << 13) | (1::BIT(64) << 15) | (1::BIT(64) << 9) | (1::BIT(64) << 21) WHERE r.name = 'Organization_Developer'; UPDATE roles r SET permission = (1::BIT(64) << 9) | (1::BIT(64) << 21) WHERE r.name = 'Organization_Editor'; UPDATE roles r SET permission = (1::BIT(64) << 21) WHERE r.name = 'Organization_Support'; DROP VIEW global_trust; DROP VIEW project_trust; DROP VIEW organization_trust; CREATE OR REPLACE VIEW global_trust AS SELECT gr.user_id, coalesce(bit_or(r.permission), B'0'::bit(64)) AS permission FROM user_global_roles gr JOIN roles r ON gr.role_id = r.id GROUP BY gr.user_id; CREATE OR REPLACE VIEW project_trust AS SELECT pm.project_id, pm.user_id, coalesce(bit_or(r.permission), B'0'::bit(64)) AS permission FROM project_members pm JOIN user_project_roles rp ON pm.project_id = rp.project_id AND pm.user_id = rp.user_id AND rp.is_accepted JOIN roles r ON rp.role_type = r.name GROUP BY pm.project_id, pm.user_id; CREATE OR REPLACE VIEW organization_trust AS SELECT om.organization_id, om.user_id, coalesce(bit_or(r.permission), B'0'::bit(64)) AS permission FROM organization_members om JOIN user_organization_roles ro ON om.organization_id = ro.organization_id AND om.user_id = ro.user_id AND ro.is_accepted JOIN roles r ON ro.role_type = r.name GROUP BY om.organization_id, om.user_id; ALTER TABLE roles DROP COLUMN trust; # --- !Downs ALTER TABLE roles ADD COLUMN trust INTEGER NOT NULL DEFAULT 0; UPDATE roles r SET trust = 5 WHERE r.name = 'Ore_Admin'; UPDATE roles r SET trust = 2 WHERE r.name = 'Ore_Mod'; UPDATE roles r SET trust = 5 WHERE r.name = 'Project_Owner'; UPDATE roles r SET trust = 3 WHERE r.name = 'Project_Developer'; UPDATE roles r SET trust = 1 WHERE r.name = 'Project_Editor'; UPDATE roles r SET trust = 5 WHERE r.name = 'Organization'; UPDATE roles r SET trust = 5 WHERE r.name = 'Organization_Owner'; UPDATE roles r SET trust = 4 WHERE r.name = 'Organization_Admin'; UPDATE roles r SET trust = 3 WHERE r.name = 'Organization_Developer'; UPDATE roles r SET trust = 1 WHERE r.name = 'Organization_Editor'; DROP VIEW global_trust; DROP VIEW project_trust; DROP VIEW organization_trust; CREATE OR REPLACE VIEW global_trust AS SELECT gr.user_id, coalesce(max(r.trust), 0) AS trust FROM user_global_roles gr JOIN roles r ON gr.role_id = r.id GROUP BY gr.user_id; CREATE OR REPLACE VIEW project_trust AS SELECT pm.project_id, pm.user_id, coalesce(max(r.trust), 0) AS trust FROM project_members pm JOIN user_project_roles rp ON pm.project_id = rp.project_id AND pm.user_id = rp.user_id JOIN roles r ON rp.role_type = r.name GROUP BY pm.project_id, pm.user_id; CREATE OR REPLACE VIEW organization_trust AS SELECT om.organization_id, om.user_id, coalesce(max(r.trust), 0) AS trust FROM organization_members om JOIN user_organization_roles ro ON om.organization_id = ro.organization_id AND om.user_id = ro.user_id JOIN roles r ON ro.role_type = r.name GROUP BY om.organization_id, om.user_id; ALTER TABLE roles DROP COLUMN permission;
#!/usr/bin/env python from chalice import Chalice from chalicelib.main import get_team DEFAULT_PARAM = "WSH" app = Chalice(app_name='resetter') @app.route('/',methods=['GET']) def index(): """Route used for Slack""" try: team = app.current_request.query_params['text'] if team == '': team = DEFAULT_PARAM except: team = DEFAULT_PARAM # allows /scoreboard try: team = app.current_request.query_params['override'] except: pass print("getting for team " + team) rtext = get_team(team) return { "response_type": "in_channel", "text": rtext }
<h1 align="center"> <img src="http://www.zxlee.cn/AppStoreMonitorLogo.png" width="200" height="200" style="margin-left:100px"/> </h1> ## 在线地址👉 https://static.ifafu.cn/AppStoreMonitor/index.html ## 开始使用 * 请允许AppStoreMonitor显示通知 * 输入您的App对应的AppID,点击开始 * AppStoreMonitor会每隔1分钟获取一次应用最新版本信息 * 若检测到新版本,可通过浏览器推送通知您 * 再也无需反复打开AppStore查看应用更新是否生效 * 仅限AppStore的应用 ## 预览通知效果 ![](http://www.zxlee.cn/AppStoreMonitorLogoDemo2.png)
using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using Xunit; namespace Ben.Demystifier.Test { public class GenericMethodDisplayStringTests { private static class Example<T> { // ReSharper disable once StaticMemberInGenericType public static readonly StackFrame StackFrame; static Example() { var fun = new Func<StackFrame>(() => new StackFrame(0, true)); StackFrame = fun(); } } [Fact] public void DiagnosesGenericMethodDisplayString() { var sf = Example<Type>.StackFrame; try { var s = EnhancedStackTrace.GetMethodDisplayString(sf.GetMethod()); Assert.True(true, "Does not throw exception when diagnosing generic method display string."); } catch (Exception) { Assert.True(false, "Must not throw an exception when diagnosing generic method display string."); } } private static class ThrowsInCtor { #pragma warning disable CS0649 public static readonly string Field; #pragma warning restore CS0649 static ThrowsInCtor() { var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures) .Select(x => new RegionInfo("qwerty")) //this will throw .Where(x => x.DisplayName != "World").ToList(); } } [Fact] public void ThrowsInCtorMethodDisplayString() { var type = typeof(ThrowsInCtor).GetNestedTypes(BindingFlags.NonPublic).Single(); var method = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) .Single(x => x.ReturnType == typeof(bool)); var displayString = EnhancedStackTrace.GetMethodDisplayString(method); Assert.StartsWith(".cctor", displayString.Name!); } } }