text
stringlengths
184
4.48M
package com.example.endgame.controller; import com.example.endgame.service.ThanhToanService; import com.example.endgame.dto.ThanhToanDto; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("payment") @CrossOrigin(origins = "http://localhost:3000") @AllArgsConstructor @Tag( name = "CRUD REST API FOR PAYMENTS RESOURCES", description = "CRUD REST API'S = CREATE, READ, UPDATE, DELETE" ) public class ThanhToanController { private ThanhToanService service; @Operation( summary = "Create a payment REST API", description = "CREATE A PAYMENT FROM DATABASE" ) @ApiResponse( responseCode = "201", description = "HTTP Status CREATED" ) @PostMapping("/create") public ResponseEntity<?> createPayment(@RequestBody ThanhToanDto thanhToanDto) { return new ResponseEntity<>(service.createPayment(thanhToanDto), HttpStatus.OK); } @Operation( summary = "Get all payment REST API", description = "GET ALL PAYMENT FROM DATABASE" ) @ApiResponse( responseCode = "200", description = "HTTP Status FOUNDED" ) @GetMapping("/get-all") public ResponseEntity<?> getAllPayment() { return new ResponseEntity<>(service.getAllThanhToan(), HttpStatus.OK); } @Operation( summary = "Get payment by ID REST API", description = "GET PAYMENT BY ID FROM DATABASE" ) @ApiResponse( responseCode = "200", description = "HTTP Status FOUNDED" ) @GetMapping("/get/{id}") public ResponseEntity<?> getPaymentByid(@PathVariable("id") Long paymentId) { ThanhToanDto thanhToanDto = service.getById(paymentId); return new ResponseEntity<>(thanhToanDto, HttpStatus.OK); } }
package com.xuliwen.basecode.javacode.concurrent.util.semaphore; import java.util.concurrent.Semaphore; /** * Created by xlw on 2017/6/12. */ public class MutexPrint { private Semaphore semaphore=new Semaphore(1); private void print() throws InterruptedException { semaphore.acquire(); System.out.println(Thread.currentThread().getName()+" enter ..."); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "正在打印 ..."); System.out.println(Thread.currentThread().getName()+" out ..."); semaphore.release(); } public static void main(String[] args) { final MutexPrint print = new MutexPrint(); /** * 开启10个线程,抢占打印机 */ for (int i = 0; i < 10; i++) { new Thread() { public void run() { try { print.print(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); } } }
// ignore_for_file: invalid_annotation_target import 'package:freezed_annotation/freezed_annotation.dart'; part 'base_request_response.freezed.dart'; part 'base_request_response.g.dart'; @freezed class BaseResponse with _$BaseResponse { const factory BaseResponse({ @Default(false) bool isSuccess, Map<String, dynamic>? data, @JsonKey(name: 'message') String? info, String? error, @JsonKey(name: 'errorCode') int? code, }) = _BaseResponse; factory BaseResponse.fromJson(Map<String, dynamic> json) => _$BaseResponseFromJson(json); } @freezed class BaseRequest with _$BaseRequest { const factory BaseRequest({ String? appVersion, String? deviceRef, String? deviceToken, String? deviceModel, String? language, String? lob, String? nic, String? requestType, String? platformName, String? platformVersion, String? provider, int? appLanguage, int? userId, }) = _BaseRequest; factory BaseRequest.fromJson(Map<String, dynamic> json) => _$BaseRequestFromJson(json); } @freezed class OsrmResponse with _$OsrmResponse { const factory OsrmResponse({ required String code, required List<Route>? routes, required List<Waypoint>? waypoints, }) = _OsrmResponse; factory OsrmResponse.fromJson(Map<String, dynamic> json) => _$OsrmResponseFromJson(json); } @freezed class Route with _$Route { const factory Route({ required String geometry, required List<Leg> legs, @JsonKey(name: 'weight_name') required String weightName, required double weight, required double duration, required double distance, }) = _Route; factory Route.fromJson(Map<String, dynamic> json) => _$RouteFromJson(json); } @freezed class Leg with _$Leg { const factory Leg({ required List<dynamic> steps, required String summary, required double weight, required double duration, required double distance, }) = _Leg; factory Leg.fromJson(Map<String, dynamic> json) => _$LegFromJson(json); } @freezed class Waypoint with _$Waypoint { const factory Waypoint({ required String hint, required double distance, required String name, required List<double> location, }) = _Waypoint; factory Waypoint.fromJson(Map<String, dynamic> json) => _$WaypointFromJson(json); }
mod cargo; mod dependency; mod format; mod package; mod parse_target; use clap::{Args, Parser}; use package::{parse_mod_tree, ModTree}; use parse_target::parse_target_dependencies; use proc_macro2::{Ident, TokenStream}; use quote::quote; use std::path::Path; use cargo::{find_cargo_toml, parse_package_name}; use crate::dependency::ModPath; #[derive(Parser)] // requires `derive` feature #[command(name = "cargo")] #[command(bin_name = "cargo")] enum CargoCli { Cpack(CpackArgs), } /// Parses the source code in the bin directory and bundles it into a single file. #[derive(Args, Debug)] #[command(author, version, about, long_about = None)] struct CpackArgs { /// Path to the source to be packed. path: String, /// Formatting output /// (default: false) #[clap(short, long, default_value = "false")] format: bool, /// Generated code only /// (default: false) #[clap(short, long, default_value = "false")] gen_code_only: bool, } fn main() { let CargoCli::Cpack(args) = CargoCli::parse(); match process(args) { Ok(()) => {} Err(e) => { println!("Error: {}", e); } } } fn process(args: CpackArgs) -> Result<(), Box<dyn std::error::Error>> { let path = Path::new(&args.path); // Cargo.tomlを探す let cargo_toml_path = find_cargo_toml(path).ok_or("Cargo.toml not found")?; // 変換対象のプロジェクト名を取得する let package_crate_name = parse_package_name(&cargo_toml_path)?; // pack対象のファイルを読み込む let target_str = std::fs::read_to_string(path)?; let target_syntax = syn::parse_file(&target_str)?; let target_dependencies = parse_target_dependencies(&target_syntax, &package_crate_name); // println!("{:#?}", target_dependencies); // Cargo.tomlの内容を元に、lib.rsを読み込む let lib_path = cargo_toml_path.parent().unwrap().join("src").join("lib"); // lib.rsに記載されているmodの情報から再起的にModTreeを生成する let mut mod_tree = parse_mod_tree( &lib_path, ModPath::from(&package_crate_name), true, &target_dependencies, ); mod_tree.name = syn::Ident::new(&package_crate_name, proc_macro2::Span::call_site()); // TokenStreamを生成する let generated_token = gen_mod_token(&mod_tree, true); // macro_rules内の$crateの挙動が変わるので、$crateを$crate::package_crate_nameに置換する // (もっとスマートな書き方に直したい) let generated_token = generated_token.to_string().replace( "$ crate ::", format!("$crate::{}::", package_crate_name).as_str(), ); // 対象ファイルの内容を出力する if !args.gen_code_only { println!("{}", target_str); } if args.format { // rustfmtを実行する let formatted_code = format::format_code(&generated_token)?; println!("{}", formatted_code); } else { // そのまま出力する println!("{}", generated_token); } Ok(()) } fn gen_mod_token(mod_tree: &ModTree, is_root: bool) -> TokenStream { let mod_name = &mod_tree.name; let mod_tokens = if mod_tree.is_gen_target { mod_tree.tokens.clone() } else { TokenStream::new() }; let mut child_tokens = TokenStream::new(); for child in &mod_tree.children { child_tokens.extend(gen_mod_token(child, false)); } if child_tokens.is_empty() && mod_tokens.is_empty() { return TokenStream::new(); } let mut dummy_macro_tokens = TokenStream::new(); if is_root { // マクロと同名の関数を定義する for macro_name in mod_tree.get_exported_macros() { let m = Ident::new(&macro_name, proc_macro2::Span::call_site()); dummy_macro_tokens.extend(quote! { pub fn #m() {} }); } } quote! { pub mod #mod_name { #dummy_macro_tokens #mod_tokens #child_tokens } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.zookeeper.server.quorum; import java.io.File; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import org.apache.zookeeper.PortAssignment; import org.apache.zookeeper.server.quorum.QuorumPeer; import org.apache.zookeeper.server.quorum.FastLeaderElection.Notification; import org.apache.zookeeper.server.quorum.Vote; import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer; import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState; import org.apache.zookeeper.server.util.ZxidUtils; import org.apache.zookeeper.test.ClientBase; import org.apache.zookeeper.test.FLETest; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Test FastLeaderElection with out of election servers. */ public class FLEOutOfElectionTest { private FastLeaderElection fle; @Before public void setUp() throws Exception { File tmpdir = ClientBase.createTmpDir(); Map<Long, QuorumServer> peers = new HashMap<Long,QuorumServer>(); for(int i = 0; i < 5; i++) { peers.put(Long.valueOf(i), new QuorumServer(Long.valueOf(i), new InetSocketAddress("127.0.0.1", PortAssignment.unique()))); } QuorumPeer peer = new QuorumPeer(peers, tmpdir, tmpdir, PortAssignment.unique(), 3, 3, 1000, 2, 2); fle = new FastLeaderElection(peer, peer.createCnxnManager()); } @Test public void testIgnoringZxidElectionEpoch() { Map<Long, Vote> votes = new HashMap<Long, Vote>(); votes.put(0L, new Vote(0x1, 4L, ZxidUtils.makeZxid(1, 1), 1, 2, ServerState.FOLLOWING)); votes.put(1L, new Vote(0x1, 4L, ZxidUtils.makeZxid(1, 2), 1, 2, ServerState.FOLLOWING)); votes.put(3L, new Vote(0x1, 4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)); votes.put(4L, new Vote(0x1, 4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LEADING)); Assert.assertTrue(fle.termPredicate(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING))); } @Test public void testElectionWIthDifferentVersion() { Map<Long, Vote> votes = new HashMap<Long, Vote>(); votes.put(0L, new Vote(0x1, 4L, ZxidUtils.makeZxid(1, 1), 1, 1, ServerState.FOLLOWING)); votes.put(1L, new Vote(0x1, 4L, ZxidUtils.makeZxid(1, 1), 1, 1, ServerState.FOLLOWING)); votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)); votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LEADING)); Assert.assertTrue(fle.termPredicate(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING))); } @Test public void testLookingNormal() { Map<Long, Vote> votes = new HashMap<Long, Vote>(); votes.put(0L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING)); votes.put(1L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING)); votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING)); votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LEADING)); Assert.assertTrue(fle.termPredicate(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING))); } @Test public void testLookingDiffRounds() { HashMap<Long, Vote> votes = new HashMap<Long, Vote>(); votes.put(0L, new Vote(4L, ZxidUtils.makeZxid(1, 1), 1, 1, ServerState.LOOKING)); votes.put(1L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LOOKING)); votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 3, 2, ServerState.LOOKING)); votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 3, 2, ServerState.LEADING)); Assert.assertFalse(fle.termPredicate(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LOOKING))); } @Test public void testOutofElection() { HashMap<Long,Vote> outofelection = new HashMap<Long,Vote>(); outofelection.put(1L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(2L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(4L, new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.FOLLOWING)); Vote vote = new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.LEADING); outofelection.put(5L, vote); Notification n = new Notification(); n.version = vote.getVersion(); n.leader = vote.getId(); n.zxid = vote.getZxid(); n.electionEpoch = vote.getElectionEpoch(); n.state = vote.getState(); n.peerEpoch = vote.getPeerEpoch(); n.sid = 5L; // Set the logical clock to 1 on fle instance of server 3. fle.logicalclock.set(0x1); Assert.assertTrue("Quorum check failed", fle.termPredicate(outofelection, new Vote(n.version, n.leader, n.zxid, n.electionEpoch, n.peerEpoch, n.state))); Assert.assertTrue("Leader check failed", fle.checkLeader(outofelection, n.leader, n.electionEpoch)); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CreateSplitTestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('split_tests', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('user_id')->unsigned()->index(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->bigInteger('bar_id')->unsigned()->index(); $table->foreign('bar_id')->references('id')->on('bars')->onDelete('cascade'); $table->string('split_bar_name')->index(); $table->double('split_bar_weight'); $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')); $table->unique(['id', 'user_id', 'bar_id']); $table->engine = 'InnoDB'; }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('split_tests'); } }
/* * MoXie ([email protected]) 2009-2-1 15:59:59 * * Copyright &copy; 2008-2009 Zoeey.Org * Code license: GNU Lesser General Public License Version 3 * http://www.gnu.org/licenses/lgpl-3.0.txt */ package org.zoeey.route; import java.util.ArrayList; import org.zoeey.dispatch.exceptions.RouterConnectException; import java.util.List; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.zoeey.util.ArrayHelper; import org.zoeey.util.StringHelper; /** * 路由参数标准分析器 * 格式规则较为严谨,使用 / 分割不同的参数 。默认多值参数使用逗号分隔。 * ex. * Router router = new Router(); * router.add("/:action")// * // 正则匹配已出现的变量 * .addRegexp("action", "(list)", "/:page/:label")// * // 已出现变量在某集合内 * .addArray("action", new String[]{"view"}, "/:id/:title")// * .addArray("action", new String[]{"edit", "delete"}, "/:id")// * // 参数个数是某值 * .addParamCount(5, "/:id/:page/:label/:highlight")// * // 全QueryString正则匹配 * .addAllRegexp("/track/([^/]+)/?$", "/:trackSn"); * * @author MoXie([email protected]) */ public class Router { /** * 默认分隔符 */ public static final char DEFAULT_SEP = '/'; /** * 规则列表 */ private List<RouterRule> ruleList; /** * 间隔符 */ private char sep = DEFAULT_SEP; /** * 参数分析器 */ public Router() { ruleList = new ArrayList<RouterRule>(); } /** * 新增规则 * @param ruleItem 路由规则项 * @return */ public Router add(RouterRule ruleItem) { ruleList.add(ruleItem); return this; } /** * 普通规则 * .add("/:action") * @param pattern 规则描述 * @return */ public Router add(String pattern) { ruleList.add(new RouterRule(pattern, sep)); return this; } /** * 正则匹配已出现的变量 * .addRegexp("action", "(list)", "/:page/:label") * @param varName 变量名称 * @param regexp 正则表达式 * @param pattern 规则描述 * @return */ public Router addRegexp(String varName, String regexp, String pattern) { ruleList.add(new RouterRule(varName, regexp, pattern, sep)); return this; } /** * 已出现变量在某集合内 * .addArray("action", new String[]{"view"}, "/:id/:title")// * @param varName 变量名称 * @param strs 字符串集 * @param pattern 规则描述 * @return */ public Router addArray(String varName, String[] strs, String pattern) { ruleList.add(new RouterRule(varName, strs, pattern, sep)); return this; } /** * 参数个数是某值 * .add(5, "/:id/:page/:label/:highlight") * @param paramCount 参数个数 * @param pattern 规则描述 * @return */ public Router addParamCount(int paramCount, String pattern) { ruleList.add(new RouterRule(paramCount, pattern, sep)); return this; } /** * 全QueryString正则匹配 * addAllRegexp("track/([^/]+)/?$", new String[]{"trackSn"}); * 注意:queryString 的起始“/”会被剔除掉。 * @param regexp 正则表达式 * @param keys 键列表 * @return */ public Router addAllRegexp(String regexp, String[] keys) { ruleList.add(new RouterRule(regexp, keys)); return this; } /** * 复制上一规则,追加规则描述 * 注意:全QueryString正则匹配不可追加 * @param pattern 规则描述 * @param sep 间隔符。此方法常用于追加不定参数,设定此参数方便切换间隔符, * @return */ public Router append(String pattern, char sep) { int size = ruleList.size(); if (size > 0) { RouterRule lastRule = null; RouterRule rule = null; lastRule = ruleList.get(size - 1); if (lastRule != null) { switch (lastRule.getType()) { case TYPE_NORMAL: rule = new RouterRule(pattern, sep); break; case TYPE_VARREGEXP: rule = new RouterRule(lastRule.getVarName(), lastRule.getRegexp(), pattern, sep); break; case TYPE_VARINSET: rule = new RouterRule(lastRule.getVarName(), lastRule.getStrs(), pattern, sep); break; case TYPE_VARCOUNT: rule = new RouterRule(lastRule.getParamCount(), pattern, sep); break; /* case TYPE_ALLREGEXP: rule = new RouterRule(rule.getRegexp(), rule.getStrs()); break; */ } if (rule != null) { ruleList.add(rule); } } } return this; } /** * 切换间隔符,对其后添加的规则有效 * @param sep 间隔符 * @return */ public Router shiftSep(char sep) { this.sep = sep; return this; } /** * 匹配上一规则,则终止。 * @return */ public Router end() { int size = ruleList.size(); if (size > 0) { RouterRule rule = ruleList.get(size - 1); rule.end(); } return this; } /** * 分析普通规则 * @param paramList * @param varName * @param value * @throws RouterConnectException */ private void parseNormalRule(List<ParamEntry> paramList, String varName, String value) { if (varName == null) { return; } int len = varName.length(); int size = 0; if (len > 2) { char left = varName.charAt(len - 3); char right = varName.charAt(len - 1); char _sep = varName.charAt(len - 2); // name[,] --> name // name{-} --> name // name[,] if (len > 3 && left == '[' && right == ']') { varName = varName.substring(0, len - 3); paramList.add(new ParamEntry(varName, StringHelper.split(value, _sep))); return; } else if (left == '{' && right == '}') { List<ParamEntry> valList = new ArrayList<ParamEntry>(); value = StringHelper.trim(value, new char[]{_sep}); String[] vals = StringHelper.split(value, _sep); size = vals.length; int i = 0; for (; i < size; i++) { if ((i + 1) % 2 == 0) { valList.add(new ParamEntry(vals[i - 1], vals[i])); } } if (size % 2 == 1) { valList.add(new ParamEntry(vals[i - 1], null)); } // name{-} if (len > 3) { varName = varName.substring(0, len - 3); paramList.add(new ParamEntry(varName, valList)); } else { paramList.addAll(valList); } return; } } paramList.add(new ParamEntry(varName, value)); } /** * 获取值处理器 * @param query 请求字符串 * @return */ public ParamHandler getHandler(Query query) { return new ParamHandler(parse(query.getQueryString())); } /** * 获取值处理器 * @param queryString 请求字符串 * @return */ public ParamHandler getHandler(String queryString) { return new ParamHandler(parse(queryString)); } /** * 解析参数 * @param query 请求项 * @return * @throws RouterConnectException */ public List<ParamEntry> parse(Query query) { return parse(query.getQueryString()); } /** * 解析参数 * @param queryString 请求字符串 * @return * @throws RouterConnectException */ public List<ParamEntry> parse(String queryString) { /** * 整理资源 */ List<ParamEntry> paramList = new ArrayList<ParamEntry>(); if (queryString != null && queryString.length() > 0 // && ruleList != null && ruleList.size() > 0) { if (queryString.startsWith("/")) { queryString = queryString.substring(1); } StringTokenizer queryTokenizer = new StringTokenizer(queryString); StringTokenizer tempQueryTokenizer; StringTokenizer varNameTokenizer; boolean hasMoreValue; String refer_val = null; String sepStr; char _sep; char lastSep = 0; boolean isParse; char[] varPrefix = new char[]{':', '/', '/'}; int matchCount = 0; ruleList_for: for (RouterRule ruleItem : ruleList) { _sep = ruleItem.getSep(); sepStr = String.valueOf(_sep); varPrefix[1] = _sep; varPrefix[2] = lastSep; isParse = false; /** * 装载规则 */ switch (ruleItem.getType()) { case TYPE_NORMAL: isParse = true; break; case TYPE_VARREGEXP: refer_val = getLastValue(paramList, ruleItem.getVarName()); if (refer_val != null && refer_val.matches(ruleItem.getRegexp())) { isParse = true; } break; case TYPE_VARINSET: refer_val = getLastValue(paramList, ruleItem.getVarName()); if (refer_val != null && ArrayHelper.inArray(ruleItem.getStrs(), refer_val)) { isParse = true; } break; case TYPE_VARCOUNT: tempQueryTokenizer = new StringTokenizer(queryString, sepStr); int paramsSize = tempQueryTokenizer.countTokens(); tempQueryTokenizer = null; if (paramsSize == ruleItem.getParamCount()) { isParse = true; } break; case TYPE_ALLREGEXP: Pattern pattern = Pattern.compile(ruleItem.getRegexp()); Matcher matcher = pattern.matcher(queryString); String keys[] = ruleItem.getStrs(); if (!matcher.matches() // || (matchCount = matcher.groupCount()) != keys.length) { break; } matcher.reset(); if (matcher.find()) { for (int j = 0; j < matchCount; j++) { paramList.add(new ParamEntry(keys[j], matcher.group(j + 1))); } } break; } if (isParse) { varNameTokenizer = new StringTokenizer(ruleItem.getPattern()); while (varNameTokenizer.hasMoreTokens() // && (hasMoreValue = queryTokenizer.hasMoreTokens())) { if (!hasMoreValue) { break ruleList_for; } parseNormalRule(paramList // , StringHelper.ltrim(varNameTokenizer.nextToken(sepStr), varPrefix, 1)// , StringHelper.ltrim(queryTokenizer.nextToken(sepStr), varPrefix, 1)// ); } if (ruleItem.isIsEnd()) { break ruleList_for; } } lastSep = _sep; } } return paramList; } private String getLastValue(List<ParamEntry> paramList, String key) { Object value = null; for (ParamEntry param : paramList) { if (param.getKey().equals(key)) { value = param.getValue(); } } if (value instanceof String) { return (String) value; } return null; } }
<?php namespace App\Controller; use App\Entity\Card; use App\Repository\UserRepository; use Doctrine\ORM\EntityManagerInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\SerializerInterface; class CardController extends AbstractController { public function __construct(TokenStorageInterface $tokenStorageInterface) { $this->tokenStorageInterface = $tokenStorageInterface; $this->getUserInfos = function($object) { return [ "email" => $object->getEmail(), "id" => $object->getId() ]; }; } #[Route('/api/card', name: 'user-add-card', methods: ['POST'])] #[IsGranted("ROLE_USER", message: "Vous n'êtes pas autorisé à accéder à cette page")] public function create(Request $request, SerializerInterface $serializer, EntityManagerInterface $em, UserRepository $userRepository): JsonResponse { $datas = $request->toArray(); $card = $serializer->deserialize($request->getContent(), Card::class, 'json'); if (empty($datas['user'])) { $user = $this->tokenStorageInterface->getToken()->getUser(); $card->setUser($user); } else { $user = $userRepository->find($datas['user']); $card->setUser($user); } $em->persist($card); $em->flush($card); $context = [ AbstractNormalizer::CALLBACKS => [ "user" => $this->getUserInfos ] ]; $jsonCard = $serializer->serialize($card, 'json', $context); return new JsonResponse($jsonCard, Response::HTTP_CREATED, json: true); } #[Route('/api/card', name: 'user-get-card', methods: ['GET'])] #[IsGranted("ROLE_USER", message: "Vous n'êtes pas autorisé à accéder à cette page")] public function read(SerializerInterface $serializer): JsonResponse { $cards = $this->tokenStorageInterface->getToken()->getUser()->getCards(); $context = [ AbstractNormalizer::CALLBACKS => [ "user" => $this->getUserInfos ] ]; $jsonCards = $serializer->serialize($cards, 'json', $context); return new JsonResponse($jsonCards, Response::HTTP_CREATED, json: true); } #[Route('/api/card/{id}', name: 'user-update-card', methods: ['PUT'])] #[IsGranted("ROLE_USER", message: "Vous n'êtes pas autorisé à accéder à cette page")] public function update(Card $previousCard, SerializerInterface $serializer, Request $request, EntityManagerInterface $em): JsonResponse { $user = $this->tokenStorageInterface->getToken()->getUser(); if ($previousCard->getUser() == $user || in_array("ROLE_ADMIN", $user->getRoles())) { $newCard = $serializer->deserialize($request->getContent(), Card::class, 'json', [ AbstractNormalizer::OBJECT_TO_POPULATE => $previousCard ]); $em->persist($newCard); $em->flush(); return new JsonResponse(null, Response::HTTP_OK); } return new JsonResponse(null, Response::HTTP_BAD_REQUEST); } #[Route('/api/card/{id}', name: 'user-delete-card', methods: ['DELETE'])] #[IsGranted("ROLE_USER", message: "Vous n'êtes pas autorisé à accéder à cette page")] public function delete(Card $card, EntityManagerInterface $em): JsonResponse { $user = $this->tokenStorageInterface->getToken()->getUser(); if ($card->getUser() == $user || in_array("ROLE_ADMIN", $user->getRoles())) { $em->remove($card); $em->flush(); return new JsonResponse(null, Response::HTTP_OK); } return new JsonResponse(null, Response::HTTP_BAD_REQUEST); } }
import { Typography, IconButton, Button } from "@mui/material"; import ClearIcon from "@mui/icons-material/Clear"; import { deleteNotification, readOne } from "../../api/notifications"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { AvatarWithStatus } from "../AvatarWithStatus"; import useNotificationQuery from "../../components/hooks/useNotificationQuery"; // import { useDispatch } from 'react-redux'; // import { setToken } from '../../pages/Login/features/loginSlice'; import "./style/style.scss"; import { useRef } from "react"; import RefreshIcon from "../MessageSection/Helpers/RefreshIcon"; export const CreateNotificationCards = () => { const queryClient = useQueryClient(); const query = useNotificationQuery(); const notificationQuery = queryClient.getQueryData(["notifications"]); const scrollPosition = useRef(); // const dispatch = useDispatch(); const deleteQuery = useMutation({ mutationFn: deleteNotification, onMutate: async (variables) => { await queryClient.cancelQueries(["notifications"]); const oldNotifications = queryClient.getQueryData(["notifications"]); queryClient.setQueryData(["notifications"], (old) => { const newPages = old.pages.map((page) => { return { ...page, notifications: page.notifications.filter( (notification) => notification._id !== variables ), }; }); return { ...old, pages: newPages, }; }); return { oldNotifications }; }, onSettled: () => queryClient.invalidateQueries(["notifications"]), onError: (err, variables, context) => { queryClient.setQueryData(["notifications"], context.oldNotifications); // dispatch(setToken()) }, }); const readOneNotification = useMutation({ mutationFn: (id) => readOne(id), onMutate: async (variables) => { await queryClient.cancelQueries({ queryKey: ["notifications"] }); const prevData = queryClient.getQueryData(["notifications"]); await queryClient.setQueryData(["notifications"], (old) => { const newPages = old.pages.map((page) => { return { ...page, notifications: page.notifications.map((notification) => notification._id === variables ? { ...notification, status: "read" } : notification ), }; }); return { ...old, pages: newPages, }; }); return { prevData }; }, onError: (err, newNotifications, context) => { queryClient.setQueryData(["notifications"], context.prevData); }, onSettled: (data, variables, context) => { queryClient.invalidateQueries(["notifications"]); }, }); const handleRead = (id) => { const [alreadyRead] = queryClient .getQueryData(["notifications"]) .pages.map((page) => page.notifications.find( (notification) => notification._id === id && notification.status === "unread" ) ); if (alreadyRead) readOneNotification.mutate(id); }; const handleScroll = () => { if ( scrollPosition.current.scrollHeight === scrollPosition.current.scrollTop + scrollPosition.current.clientHeight && query.hasNextPage ) query.fetchNextPage(); }; return ( <div className="notification-section" ref={scrollPosition} onScroll={handleScroll} > {notificationQuery?.pages?.map((page, indx) => page.notifications.map((notification, idx) => { return ( <div className={`small-card notification-card-${notification.status}`} onMouseEnter={() => handleRead(notification._id)} key={notification._id} > <div className="post-avatar flex1"> <AvatarWithStatus user={notification.requester} /> <Typography sx={{ ml: 0.5, textOverflow: "ellipsis" }} noWrap> {notification.msg} </Typography> </div> <div> <IconButton onClick={() => deleteQuery.mutate(notification._id)} > <ClearIcon color="error" /> </IconButton> </div> </div> ); }) )} {(scrollPosition.current?.scrollHeight <= scrollPosition.current?.clientHeight || !scrollPosition.current) && query.hasNextPage && ( <Button onClick={() => query.fetchNextPage()}>Load More</Button> )} {query.isFetchingNextPage && <RefreshIcon />} {notificationQuery?.isSuccess && notificationQuery?.pages[0].length > 0 && ( <Typography mt={5} variant="h5" component="h2" textAlign="center"> No new notifications </Typography> )} </div> ); };
using BookingApplication.Application.Features.CQRS.Commands.AirportCommands; using BookingApplication.Application.Features.CQRS.Handlers.AirportHandlers; using BookingApplication.Application.Features.CQRS.Queries.AirportQueries; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace BookingApplication.WebApi.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class AirportController : ControllerBase { private readonly CreateAirportCommandHandler _createAirportCommandHandler; private readonly GetAirportByIdQueryHandler _getAirportByIdQueryHandler; private readonly GetAirportQueryHandler _getAirportQueryHandler; private readonly RemoveAirportCommandHandler _removeAirportCommandHandler; private readonly UpdateAirportCommandHandler _updateAirportCommandHandler; public AirportController(CreateAirportCommandHandler createAirportCommandHandler, GetAirportByIdQueryHandler getAirportByIdQueryHandler, GetAirportQueryHandler getAirportQueryHandler, RemoveAirportCommandHandler removeAirportCommandHandler, UpdateAirportCommandHandler updateAirportCommandHandler) { _createAirportCommandHandler = createAirportCommandHandler; _getAirportByIdQueryHandler = getAirportByIdQueryHandler; _getAirportQueryHandler = getAirportQueryHandler; _removeAirportCommandHandler = removeAirportCommandHandler; _updateAirportCommandHandler = updateAirportCommandHandler; } [HttpGet] public async Task<IActionResult> AirportList() { var values = await _getAirportQueryHandler.Handle(); return Ok(values); } [HttpGet("{id}")] public async Task<IActionResult> GetAirport(int id) { var value = await _getAirportByIdQueryHandler.Handle(new GetAirportByIdQuery(id)); return Ok(value); } [HttpPost] public async Task<IActionResult> CreateAirport(CreateAirportCommand command) { await _createAirportCommandHandler.Handle(command); return Ok("Airport Eklendi"); } [HttpPut] public async Task<IActionResult> UpdateAirport(UpdateAirportCommand command) { await _updateAirportCommandHandler.Handle(command); return Ok("Airport Güncellendi"); } [HttpDelete] public async Task<IActionResult> RemoveAirport(int id) { await _removeAirportCommandHandler.Handle(new RemoveAirportCommand(id)); return Ok("Airport Silindi"); } } }
const express = require('express') const app = express() const port = 3000 const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const config = require('./config/key'); const { auth } =require("./middleware/auth"); const { User } = require("./models/User"); app.use(bodyParser.urlencoded({extended : true})); app.use(bodyParser.json() ); app.use(cookieParser()); const mongoose = require('mongoose') mongoose.connect(config.mongoURI) .then(() => console.log('MongoDB Connected...')) .catch((e) => console.log('MongoDB error: ', e)) app.get('/', (req, res) => res.send('Hello World! ohyeah~ 새해 복 많이 받으세요 오신기')) app.post('/api/users/register',(req, res) => { //회원가입할 때 필요한 정보들을 클라이언트에서 가져오면 //그것들을 데이터베이스에 넣어준다. const user = new User(req.body) user.save((err,doc) => { if(err) return res.json({success: false, err}) return res.status(200).json({ success : true }) }) }) app.post('/api/users/login', (req, res) => { // 요청된 이메일을 데이터베이스에 있는지 찾는다 User.findOne({ email : req.body.email}, (err, user) => { if(!user){ return res.json({ loginSuccess : false, message: "제공된 이메일에 해당하는 유저가 없습니다." }) } // 요청한 이메일이 데이터베이스에 있으면 비밀번호 같은지도 확인한다 user.comparePassword(req.body.password,(err, isMatch) => { if(!isMatch) return res.json({loginSuccess : false, message : "비밀번호가 틀렸습니다."}) // 비밀번호까지 같다면 토큰을 생성한다 user.generateToken((err, user) => { if(err) return res.status(400).send(err); // 토큰을 저장한다. 어디에 ? 쿠키, 로컬스토리지 등등 res.cookie("x_auth", user.token) .status(200) .json({loginSuccess:true, userId : user._id}) }) }) }) //auth는 미드웨어 app.get('/api/users/auth',auth,(req,res) => { //여기까지 미들웨어를 통과해 왔다는 얘기는 // authentication이 true라는 말 res.status(200).json({ _id: req.user._id, isAdmin : req.user.role === 0? false : true, isAuth : true, email : req.user.email, name : req.user.name, lastname : req.user.lastname, role : req.user.role, image:req.user.image }) }) }) app.listen(port, () => console.log(`Example app listening on port ${port}!`))
.TH "pyslide" "1" "0.3" "" "" .SH "NAME" .LP pyslide \- A presentation program .SH "SYNTAX" .LP pyslide [\fIoptions\fR] <\fIfilename(s)\fP> .SH "DESCRIPTION" .LP The presentation is loaded from an XML file. You can compile the presentation if you want to not depend on python\-xml and load it a little bit faster. .LP You can open more than one presentation. Pyslide will show them sequentially. .SH "OPTIONS" .LP .TP \fB-v\fR Verbose mode. Put more -v (max 5) if you want more output. .TP \fB\-f\fR Set fullscreen mode on start. .TP \fB\-c\fR \fB\-\-compile\fR Writes to stdout the python code necesary to create the presentation. The code will load the presentation faster (since it doesn't need to parse an XML file) and doesn't depend on python\-xml. You still depend on the Pyslide package. .TP \fB-H\fR \fB--html\fR <\fIoutdir\fP> Export to HTML. Pyslide will create html files and png images, with the presentation content. .TP \fB-s\fR \fB--size\fR <\fIsize\fP> Set the window/screen size. If you set this argument, Pyslide will ignore the size attribute of the presentation. .TP \fB\-k\fR By default, Pyslide will set the current working directory to the place where the XML file is located. This is useful to load images and other files that are in that directory. If you don't want to change the directory, use this option. .TP \fB-p\fR \fIpage-number\fP Starts the presentation directly in \fIpage-number\fP. If \fIpage-number\fP is negative, it will start at the end; ie, -1 is the last page, -2 the last but one, etc. .TP \fB-x\fR \fB--script\fR Load the file as a script. See below more information. .TP \fB-S\fR \fB--standalone\fR Make an standalone XML. See below for more information. .TP \fB-I\fR Ignore errors on images. That is, if an image can't be loaded, Pyslide will substitute it with an empty surface (and do a warning) instead of exists .TP \fB--color-names\fP Show all the available color names and exit. .TP \fB--help\fR \fB\-h\fR Print help information and exit. .TP \fB\-\-version\fR Print version information and exit. .SH "KEYS" .LP .TP \fBQ\fR Stop the presentation and exit .TP \fBF\fR Toggle fullscreen .TP \fB->\fR or \fBespace\fR Next item. If there is no more item, go to the next page .TP \fB<-\fR Previous item. .TP \fBPage down\fR Next page .TP \fBPage up\fR Previous page .TP \fBT\fR Shows a timer. .TP \fBS\fR Shows the current page number. .LP When you press `S' once, a little bar will be showed at the bottom of the page. You can see the current page in that bar. .LP if you want to see the bar all the time, you have open it with `S' and, before it is hidden, press again `S'. The bar will be always showed, and updated when you change page. If you want to hide it again, press `S'. .SH "SCRIPT MODE" If you want to use your presentations as ``scripts'' (that is, use it as ejecutables files) you can do this with the \fB-x\fR or \fB--script\fR option. .LP When you load the XML files as scripts, Pyslide will ignore the lines which begin with a ``#''. After the first line that does not start with a ``#'', the rest of content will be loaded completly. .LP Renember that you have to start the XML file with something like .LP #!/usr/bin/pyslide -x # Some commments if you want :-) <presentation ...> .. .SH "STANDALONE FILES" When you make a presentation, you normally use external files (CSS, images, etc). Pyslide lets you make an unique XML with everything in it. That is, CSS will disappear (alias and classes will be expanded) and images will be embedded. The new XML will be dumped to stdout. .SH "EXAMPLES" .LP To run the presentation in full screen mode .LP pyslide \-f foo.xml .LP To compile the presentation and run it .LP pyslide \-c myslide.xml > myslide.py .br python myslide.py .SH "AUTHORS" .LP Ayose Cazorla <[email protected]>
import React, { useContext, useRef, useState } from "react"; import { InputWrapper, StyledForm, SubmitButton } from "./styled"; import IDatePicker from "../datePicker"; import ISelectField from "../selectField"; import ITextFields from "../textField"; import DataContext from "../../contexts/dataContext"; import Alert from "../Alert"; import dayjs from "dayjs"; import dayjsBusinessDays from "dayjs-business-days"; dayjs.extend(dayjsBusinessDays); function Form() { const now = dayjs(); const ref = useRef(); const { data, setData } = useContext(DataContext); const [state, setState] = useState(true); const handleSubmit = (e) => { e.preventDefault(); if ( (now.isBefore(data.orderDate, "day") == true || now.isSame(data.orderDate, "day") == true) && data.orderDate !== null && data.fabricType !== "" && typeof +data.quantity === "number" && +data.quantity <= 100 ) { setState(true); ref.current.openAlert(); if (data.fabricType == "cotton") { if (data.quantity < 50) { setData({ ...data, shippingDay: dayjs(data.orderDate).businessDaysAdd(2), }); } else { setData({ ...data, shippingDay: dayjs(data.orderDate).businessDaysAdd(3), }); } } if (data.fabricType == "linen") { if (data.quantity < 50) { setData({ ...data, shippingDay: dayjs(data.orderDate).businessDaysAdd(4), }); } else { setData({ ...data, shippingDay: dayjs(data.orderDate).businessDaysAdd(5), }); } } } else { setState(false); ref.current.openAlert(); } }; return ( <> <StyledForm onSubmit={(e) => handleSubmit(e)}> <IDatePicker /> <ISelectField /> <ITextFields /> <SubmitButton type="submit">Calculate</SubmitButton> </StyledForm> <Alert state={state} ref={ref} /> </> ); } export default Form;
// Copyright (c) All contributors. All rights reserved. Licensed under the MIT license. namespace QuickStart; public class ConfigurationExampleClass { public ConfigurationExampleClass(Crystalizer crystalizer, FirstData firstData) { this.crystalizer = crystalizer; this.firstData = firstData; } public async Task Process() { Console.WriteLine($"First: {this.firstData.ToString()}"); this.firstData.Id += 2; Console.WriteLine($"First: {this.firstData.ToString()}"); // Get or create an ICrystal interface of the data. var crystal = this.crystalizer.GetOrCreateCrystal<SecondData>( new CrystalConfiguration( SavePolicy.Manual, new LocalFileConfiguration("Local/ConfigurationTimingExample/SecondData.tinyhand"))); var secondData = crystal.Data; Console.WriteLine($"Second: {secondData.ToString()}"); secondData.Id += 1; Console.WriteLine($"Second: {secondData.ToString()}"); // You can create multiple crystals from single data class. var crystal2 = this.crystalizer.CreateCrystal<SecondData>(); crystal2.Configure(new CrystalConfiguration( SavePolicy.Manual, new LocalFileConfiguration("Local/ConfigurationTimingExample/SecondData2.tinyhand"))); var secondData2 = crystal2.Data; Console.WriteLine($"Second: {secondData2.ToString()}"); secondData2.Id += 3; Console.WriteLine($"Second: {secondData2.ToString()}"); } private readonly Crystalizer crystalizer; private FirstData firstData; } public partial class Program { public static async Task<BuiltUnit> ConfigurationTimingExample() { var builder = new CrystalControl.Builder() .Configure(context => { context.AddSingleton<ConfigurationExampleClass>(); }) .ConfigureCrystal(context => { // Register SimpleData configuration. context.AddCrystal<FirstData>( new CrystalConfiguration() { SavePolicy = SavePolicy.Manual, // Timing of saving data is controlled by the application. SaveFormat = SaveFormat.Utf8, // Format is utf8 text. NumberOfFileHistories = 0, // No history file. FileConfiguration = new LocalFileConfiguration("Local/ConfigurationTimingExample/FirstData.tinyhand"), // Specify the file name to save. }); }); var unit = builder.Build(); // Build. var crystalizer = unit.Context.ServiceProvider.GetRequiredService<Crystalizer>(); // Obtains a Crystalizer instance for data storage operations. await crystalizer.PrepareAndLoadAll(); // Prepare resources for storage operations and read data from files. var example = unit.Context.ServiceProvider.GetRequiredService<ConfigurationExampleClass>(); await example.Process(); return unit; } }
const express = require('express') const bodyParser = require('body-parser') const cors = require('cors') const db = require('./db') const ProfesorRouter = require('./routes/profesor-router') const CursoRouter = require('./routes/cursos-router') const NoticiaRouter = require('./routes/noticia-router') const app = express() const apiPort = 3000 app.use(bodyParser.urlencoded({ extended: true })) app.use(cors()) app.use(bodyParser.json()) db.on('error', console.error.bind(console, 'MongoDB connection error:')) app.get('/', (req, res) => { res.send('Hello World!') }) app.use('/api', ProfesorRouter) app.use('/api', CursoRouter) app.use('/api', NoticiaRouter) app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`))
package com.pscoding.tasktrek.presentation.components.new_task_screen.category import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Placeable @Composable fun CategoryList( modifier: Modifier = Modifier, horizontalSpacing: Int = 0, verticalSpacing: Int = 0, content: @Composable () -> Unit ) { Layout( modifier = modifier, measurePolicy = { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val groupedPlaceables = mutableListOf<List<Placeable>>() var currentGroup = mutableListOf<Placeable>() var currentGroupWidth = 0 placeables.forEach { placeable -> if (currentGroupWidth + placeable.width <= constraints.maxWidth - horizontalSpacing - 10) { currentGroup.add(placeable) currentGroupWidth += placeable.width } else { groupedPlaceables.add(currentGroup) currentGroup = mutableListOf(placeable) currentGroupWidth = placeable.width } } if (currentGroup.isNotEmpty()) { groupedPlaceables.add(currentGroup) } var layoutHeight = 0 groupedPlaceables.forEach { row -> layoutHeight += row.maxOfOrNull { it.height + verticalSpacing } ?: 0 } layout( width = constraints.maxWidth, height = layoutHeight - verticalSpacing ) { var yPosition = 0 groupedPlaceables.forEach { row -> var xPosition = 0 row.forEach { placeable -> placeable.place( x = xPosition, y = yPosition ) xPosition += placeable.width + horizontalSpacing } yPosition += row.maxOfOrNull { it.height + verticalSpacing } ?: 0 } } }, content = content ) }
/// Return integer part of the logarithm of x in given base. Use only integer arithmetic. 10 # IntLog(_x, _base) _ (base<=1) <-- Undefined; /// Use variable steps to speed up operation for large numbers x 20 # IntLog(_x, _base) <-- [ Local(result, step, old'step, factor, old'factor); result := 0; old'step := step := 1; old'factor := factor := base; // first loop: increase step While (x >= factor) [ old'factor := factor; factor := factor*factor; old'step := step; step := step*2; ]; If(x >= base, [ step := old'step; result := step; x := Div(x, old'factor); ], step := 0 ); // second loop: decrease step While (step > 0 And x != 1) [ step := Div(step,2); // for each step size down to 1, divide by factor if x is up to it factor := base^step; If( x >= factor, [ x:=Div(x, factor); result := result + step; ] ); ]; result; ]; /// obtain next number that has good chances of being prime (not divisible by 2,3) 1# NextPseudoPrime(i_IsInteger)_(i<=1) <-- 2; 2# NextPseudoPrime(2) <-- 3; //2# NextPseudoPrime(3) <-- 5; 3# NextPseudoPrime(i_IsOdd) <-- [ // this sequence generates numbers not divisible by 2 or 3 i := i+2; If(Mod(i,3)=0, i:=i+2, i); /* commented out because it slows things down without a real advantage // this works only for odd i>=5 i := If( Mod(-i,3)=0, i + 2, i + 2*Mod(-i, 3) ); // now check if divisible by 5 If( Mod(i,5)=0, NextPseudoPrime(i), i ); */ ]; // this works only for even i>=4 4# NextPseudoPrime(i_IsEven) <-- NextPseudoPrime(i-1); /// obtain the real next prime number -- use primality testing 1# NextPrime(_i) <-- [ Until(IsPrime(i)) i := NextPseudoPrime(i); i; ]; /* Returns whether n is a small by a lookup table, very fast. The largest prime number in the table is returned by FastIsPrime(0). */ 2 # IsSmallPrime(0) <-- False; 3 # IsSmallPrime(n_IsInteger) <-- (FastIsPrime(n)>0); 2 # IsPrime(_n)_(Not IsInteger(n) Or n<=1) <-- False; 3 # IsPrime(n_IsInteger)_(n<=FastIsPrime(0)) <-- IsSmallPrime(n); /* Fast pseudoprime testing: if n is a prime, then 24 divides (n^2-1) */ 5 # IsPrime(n_IsPositiveInteger)_(n > 4 And Mod(n^2-1,24)!=0) <-- False; /* Determine if a number is prime, using Rabin-Miller primality testing. Code submitted by Christian Obrecht */ 10 # IsPrime(n_IsPositiveInteger) <-- RabinMiller(n); 5 # IsComposite(1) <-- False; 10 # IsComposite(n_IsPositiveInteger) <-- (Not IsPrime(n)); /* Returns whether n is a prime^m. */ 10 # IsPrimePower(n_IsPrime) <-- True; 10 # IsPrimePower(0) <-- False; 10 # IsPrimePower(1) <-- False; 20 # IsPrimePower(n_IsPositiveInteger) <-- (GetPrimePower(n)[2] > 1); /// Check whether n is a power of some prime integer and return that integer and the power. /// This routine uses only integer arithmetic. /// Returns {p, s} where p is a prime and n=p^s. /// If no powers found, returns {n, 1}. Primality testing of n is not done. 20 # GetPrimePower(n_IsPositiveInteger) <-- [ Local(s, factors, new'factors); // first, separate any small prime factors factors := TrialFactorize(n, 257); // "factors" = {n1, {p1,s1},{p2,s2},...} or just {n} if no factors found If( Length(factors) > 1, // factorized into something // now we return {n, 1} either if we haven't completely factorized, or if we factorized into more than one prime factor; otherwise we return the information about prime factors If( factors[1] = 1 And Length(factors) = 2, // factors = {1, {p, s}}, so we have a prime power n=p^s factors[2], {n, 1} ), // not factorizable into small prime factors -- use main algorithm [ factors := CheckIntPower(n, 257); // now factors = {p, s} with n=p^s If( factors[2] > 1, // factorized into something // now need to check whether p is a prime or a prime power and recalculate "s" If( IsPrime(factors[1]), factors, // ok, prime power, return information [ // not prime, need to check if it's a prime power new'factors := GetPrimePower(factors[1]); // recursive call; now new'factors = {p1, s1} where n = (p1^s1)^s; we need to check that s1>1 If( new'factors[2] > 1, {new'factors[1], new'factors[2]*factors[2]}, // recalculate and return prime power information {n, 1} // not a prime power ); ] ), // not factorizable -- return {n, 1} {n, 1} ); ] ); ]; /// Check whether n is a power of some integer, assuming that it has no prime factors <= limit. /// This routine uses only integer arithmetic. /// Returns {p, s} where s is the smallest prime integer such that n=p^s. (p is not necessarily a prime!) /// If no powers found, returns {n, 1}. Primality testing of n is not done. CheckIntPower(n, limit) := [ Local(s0, s, root); If(limit<=1, limit:=2); // guard against too low value of limit // compute the bound on power s s0 := IntLog(n, limit); // loop: check whether n^(1/s) is integer for all prime s up to s0 root := 0; s := 0; While(root = 0 And NextPseudoPrime(s)<=s0) // root=0 while no root is found [ s := NextPseudoPrime(s); root := IntNthRoot(n, s); If( root^s = n, // found root True, root := 0 ); ]; // return result If( root=0, {n, 1}, {root, s} ); ]; /// Compute integer part of s-th root of (positive) integer n. // algorithm using floating-point math 10 # IntNthRoot(_n, 2) <-- Floor(MathSqrt(n)); 20 # IntNthRoot(_n, s_IsInteger) <-- [ Local(result, k); GlobalPush(Builtin'Precision'Get()); // find integer k such that 2^k <= n^(1/s) < 2^(k+1) k := Div(IntLog(n, 2), s); // therefore we need k*Ln(2)/Ln(10) digits for the floating-point calculation Builtin'Precision'Set(2+Div(k*3361, 11165)); // 643/2136 < Ln(2)/Ln(10) < 3361/11165 result := Round(MathExp(MathDivide(Internal'LnNum(MathDivide(n, 2^(k*s))), s))*2^k); Builtin'Precision'Set(GlobalPop()); // result is rounded and so it may overshoot (we do not use Floor above because numerical calculations may undershoot) If(result^s>n, result-1, result); ]; /* algorithm using only integer arithmetic. (this is slower than the floating-point algorithm for large numbers because all calculations are with long integers) IntNthRoot1(_n, s_IsInteger) <-- [ Local(x1, x2, x'new, y1); // initial guess should always undershoot // x1:= 2 ^ Div(IntLog(n, 2), s); // this is worse than we can make it x1 := IntLog(n,2); // select initial interval using (the number of bits in n) mod s // note that if the answer is 1, the initial guess must also be 1 (not 0) x2 := Div(x1, s); // save these values for the next If() x1 := Mod(x1, s)/s; // this is kept as a fraction // now assign the initial interval, x1 <= root <= x2 {x1, x2} := If( x1 >= 263/290, // > Ln(15/8)/Ln(2) Div({15,16}*2^x2, 8), If( x1 >= 373/462, // > Ln(7/4)/Ln(2) Div({7,8}*2^x2, 4), If( x1 >= 179/306, // > Ln(3/2)/Ln(2) Div({6,7}*2^x2, 4), If( x1 >= 113/351, // > Ln(5/4)/Ln(2) Div({5,6}*2^x2, 4), Div({4,5}*2^x2, 4) // between x1 and (5/4)*x1 )))); // check whether x2 is the root y1 := x2^s; If( y1=n, x1 := x2, // x2 is not a root, so continue as before with x1 y1 := x1^s // henceforth, y1 is always x1^s ); // Newton iteration combined with bisection While(y1 < n) [ // Echo({x1, x2}); x'new := Div(x1*((s-1)*y1+(s+1)*n), (s+1)*y1+(s-1)*n) + 1; // add 1 because the floating-point value undershoots If( x'new < Div(x1+x2, 2), // x'new did not reach the midpoint, need to check progress If( Div(x1+x2, 2)^s <= n, // Newton's iteration is not making good progress, so leave x2 in place and update x1 by bisection x'new := Div(x1+x2, 2), // Newton's iteration knows what it is doing. Update x2 by bisection x2 := Div(x1+x2, 2) ) // else, x'new reached the midpoint, good progress, continue ); x1 := x'new; y1 := x1^s; ]; If(y1=n, x1, x1-1); // subtract 1 if we overshot ]; */ CatalanNumber(_n) <-- [ Check( IsPositiveInteger(n), "CatalanNumber: Error: argument must be positive" ); Bin(2*n,n)/(n+1); ]; /// Product of small primes <= 257. Computed only once. LocalSymbols(p, q) [ // p:= 1; ProductPrimesTo257() := 2*3*[ If( IsInteger(p), p, p := Factorize(Select({{q}, Mod(q^2,24)=1 And IsSmallPrime(q)}, 5 .. 257)) ); // p; ]; ]; 10 # Repunit(0) <-- 0; // Number consisting of n 1's Repunit(n_IsPositiveInteger) <-- [ (10^n-1)/9; ]; 10 # HarmonicNumber(n_IsInteger) <-- HarmonicNumber(n,1); HarmonicNumber(n_IsInteger,r_IsPositiveInteger) <-- [ // small speed up if( r=1 )[ Sum(k,1,n,1/k); ] else [ Sum(k,1,n,1/k^r); ]; ]; Function("FermatNumber",{n})[ Check(IsPositiveInteger(n), "FermatNumber: argument must be a positive integer"); 2^(2^n)+1; ]; // Algorithm adapted from: // Elementary Number Theory, David M. Burton // Theorem 6.2 p112 5 # Divisors(0) <-- 0; 5 # Divisors(1) <-- 1; // Unsure about if there should also be a function that returns // n's divisors, may have to change name in future 10 # Divisors(_n) <-- [ Check(IsPositiveInteger(n), "Divisors: argument must be positive integer"); Local(len,sum,factors,i); sum:=1; factors:=Factors(n); len:=Length(factors); For(i:=1,i<=len,i++)[ sum:=sum*(factors[i][2]+1); ]; sum; ]; 10 # ProperDivisors(_n) <-- [ Check(IsPositiveInteger(n), "ProperDivisors: argument must be positive integer"); Divisors(n)-1; ]; 10 # ProperDivisorsSum(_n) <-- [ Check(IsPositiveInteger(n), "ProperDivisorsSum: argument must be positive integer"); DivisorsSum(n)-n; ]; // Algorithm adapted from: // Elementary Number Theory, David M. Burton // Theorem 6.2 p112 5 # DivisorsSum(0) <-- 0; 5 # DivisorsSum(1) <-- 1; 10 # DivisorsSum(_n) <-- [ Check(IsPositiveInteger(n), "DivisorsSum: argument must be positive integer"); Local(factors,i,sum,len,p,k); p:=0;k:=0; factors:={}; factors:=Factors(n); len:=Length(factors); sum:=1; For(i:=1,i<=len,i++)[ p:=factors[i][1]; k:=factors[i][2]; sum:=sum*(p^(k+1)-1)/(p-1); ]; sum; ]; // Algorithm adapted from: // Elementary Number Theory, David M. Burton // Definition 6.3 p120 5 # Moebius(1) <-- 1; 10 # Moebius(_n) <-- [ Check(IsPositiveInteger(n), "Moebius: argument must be positive integer"); Local(factors,i,repeat); repeat:=0; factors:=Factors(n); len:=Length(factors); For(i:=1,i<=len,i++)[ If(factors[i][2]>1,repeat:=1); ]; If(repeat=0,(-1)^len,0); ]; // Algorithm adapted from: // Elementary Number Theory, David M. Burton // Theorem 7.3 p139 10 # Totient(_n) <-- [ Check(IsPositiveInteger(n), "Totient: argument must be positive integer"); Local(i,sum,factors,len); sum:=n; factors:=Factors(n); len:=Length(factors); For(i:=1,i<=len,i++)[ sum:=sum*(1-1/factors[i][1]); ]; sum; ]; // Algorithm adapted from: // Elementary Number Theory, David M. Burton // Definition 9.2 p191 10 # LegendreSymbol(_a,_p) <-- [ Check( IsInteger(a) And IsInteger(p) And p>2 And IsCoprime(a,p) And IsPrime(p), "LegendreSymbol: Invalid arguments"); If(IsQuadraticResidue(a,p), 1, -1 ); ]; IsPerfect(n_IsPositiveInteger) <-- ProperDivisorsSum(n)=n; 5 # IsCoprime(list_IsList) <-- (Lcm(list) = Product(list)); 10 # IsCoprime(n_IsInteger,m_IsInteger) <-- (Gcd(n,m) = 1); // Algorithm adapted from: // Elementary Number Theory, David M. Burton // Theorem 9.1 p187 10 # IsQuadraticResidue(_a,_p) <-- [ Check( IsInteger(a) And IsInteger(p) And p>2 And IsCoprime(a,p) And IsPrime(p), "IsQuadraticResidue: Invalid arguments"); If(a^((p-1)/2) % p = 1, True, False); ]; // Digital root of n (repeatedly add digits until reach a single digit). 10 # DigitalRoot(n_IsPositiveInteger) <-- If(n%9=0,9,n%9); IsTwinPrime(n_IsPositiveInteger) <-- (IsPrime(n) And IsPrime(n+2)); IsAmicablePair(m_IsPositiveInteger,n_IsPositiveInteger) <-- ( ProperDivisorsSum(m)=n And ProperDivisorsSum(n)=m ); 5 # IsIrregularPrime(p_IsComposite) <-- False; // First irregular prime is 37 5 # IsIrregularPrime(_p)_(p<37) <-- False; // an odd prime p is irregular iff p divides the numerator of a Bernoulli number B(2*n) with // 2*n+1<p 10 # IsIrregularPrime(p_IsPositiveInteger) <-- [ Local(i,irregular); i:=1; irregular:=False; While( 2*i + 1 < p And (irregular = False) )[ If( Abs(Numer(Bernoulli(2*i))) % p = 0, irregular:=True ); i++; ]; irregular; ]; IsSquareFree(n_IsInteger) <-- ( Moebius(n) != 0 ); // Carmichael numbers are odd,squarefree and have at least 3 prime factors 5 # IsCarmichaelNumber(n_IsEven) <-- False; 5 # IsCarmichaelNumber(_n)_(n<561) <-- False; 10 # IsCarmichaelNumber(n_IsPositiveInteger) <-- [ Local(i,factors,length,carmichael); factors:=Factors(n); carmichael:=True; length:=Length(factors); if( length < 3)[ carmichael:=False; ] else [ For(i:=1,i<=length And carmichael,i++)[ //Echo( n-1,"%",factors[i][1]-1,"=", Mod(n-1,factors[i][1]-1) ); If( Mod(n-1,factors[i][1]-1) != 0, carmichael:=False ); If(factors[i][2]>1,carmichael:=False); // squarefree ]; ]; carmichael; ]; IsCarmichaelNumber(n_IsList) <-- MapSingle("IsCarmichaelNumber",n); /// the restricted partition function /// partitions of length k 5 # PartitionsP(n_IsInteger,0) <-- 0; 5 # PartitionsP(n_IsInteger,n_IsInteger) <-- 1; 5 # PartitionsP(n_IsInteger,1) <-- 1; 5 # PartitionsP(n_IsInteger,2) <-- Floor(n/2); 5 # PartitionsP(n_IsInteger,3) <-- Round(n^2/12); 6 # PartitionsP(n_IsInteger,k_IsInteger)_(k>n) <-- 0; 10 # PartitionsP(n_IsInteger,k_IsInteger) <-- PartitionsP(n-1,k-1)+PartitionsP(n-k,k); /// the number of additive partitions of an integer 5 # PartitionsP(0) <-- 1; 5 # PartitionsP(1) <-- 1; // decide which algorithm to use 10 # PartitionsP(n_IsInteger)_(n<250) <-- PartitionsP'recur(n); 20 # PartitionsP(n_IsInteger) <-- PartitionsP'HR(n); /// Calculation using the Hardy-Ramanujan series. 10 # PartitionsP'HR(n_IsPositiveInteger) <-- [ Local(P0, A, lambda, mu, mu'k, result, term, j, k, l, prec, epsilon); result:=0; term:=1; // initial value must be nonzero GlobalPush(Builtin'Precision'Get()); // precision must be at least Pi/Ln(10)*Sqrt(2*n/3)-Ln(4*n*Sqrt(3))/Ln(10) // here Pi/Ln(10) < 161/118, and Ln(4*Sqrt(3))/Ln(10) <1 so it is disregarded. Add 2 guard digits and compensate for round-off errors by not subtracting Ln(n)/Ln(10) now prec := 2+Div(IntNthRoot(Div(2*n+2,3),2)*161+117,118); Builtin'Precision'Set(prec); // compensate for round-off errors epsilon := MathPower(10,-prec)*n*10; // stop when term < epsilon // get the leading term approximation P0 - compute once at high precision lambda := N(Sqrt(n - 1/24)); mu := N(Pi*lambda*Sqrt(2/3)); // the hoops with MathDivide are needed to avoid roundoff error at large n due to fixed precision: // Exp(mu)/(n) must be computed by dividing by n, not by multiplying by 1/n P0 := N(1-1/mu)*MathDivide(MathExp(mu),(n-MathDivide(1,24))*4*MathSqrt(3)); /* the series is now equal to P0*Sum(k,1,Infinity, ( Exp(mu*(1/k-1))*(1/k-1/mu) + Exp(-mu*(1/k+1))*(1/k+1/mu) ) * A(k,n) * Sqrt(k) ) */ A := 0; // this is also used as a flag // this is a heuristic, because the next term error is expensive // to calculate and the theoretic bounds have arbitrary constants // use at most 5+Sqrt(n)/2 terms, stop when the term is nonzero and result stops to change at precision prec For(k:=1, k<=5+Div(IntNthRoot(n,2),2) And (A=0 Or Abs(term)>epsilon), k++) [ // compute A(k,n) A:=0; For(l:=1,l<=k,l++) [ If( Gcd(l,k)=1, A := A + Cos(Pi* ( // replace Exp(I*Pi*...) by Cos(Pi*...) since the imaginary part always cancels Sum(j,1,k-1, j*(Mod(l*j,k)/k-1/2)) - 2*l*n // replace (x/y - Floor(x/y)) by Mod(x,y)/y for integer x,y )/k) ); A:=N(A); // avoid accumulating symbolic Cos() expressions ]; term := If( A=0, // avoid long calculations if the term is 0 0, N( A*Sqrt(k)*( [ mu'k := mu/k; // save time, compute mu/k once Exp(mu'k-mu)*(mu'k-1) + Exp(-mu'k-mu)*(mu'k+1); ] )/(mu-1) ) ); // Echo("k=", k, "term=", term); result := result + term; // Echo("result", new'result* P0); ]; result := result * P0; Builtin'Precision'Set(GlobalPop()); Round(result); ]; // old code for comparison 10 # PartitionsP1(n_IsPositiveInteger) <-- [ Local(C,A,lambda,m,pa,k,h,term); GlobalPush(Builtin'Precision'Get()); // this is an overshoot, but seems to work up to at least n=4096 Builtin'Precision'Set(10 + Floor(N(Sqrt(n))) ); pa:=0; C:=Pi*Sqrt(2/3)/k; lambda:=Sqrt(m - 1/24); term:=1; // this is a heuristic, because the next term error is expensive // to calculate and the theoretic bounds have arbitrary constants For(k:=1,k<=5+Floor(MathSqrt(n)*0.5) And ( term=0 Or Abs(term)>0.1) ,k++)[ A:=0; For(h:=1,h<=k,h++)[ if( Gcd(h,k)=1 )[ A:=A+Exp(I*Pi*Sum(j,1,k-1,(j/k)*((h*j)/k - Floor((h*j)/k) -1/2)) - 2*Pi*I*h*n/k ); ]; ]; If(A!=0, term:= N(A*Sqrt(k)*(Deriv(m) Sinh(C*lambda)/lambda) Where m==n ),term:=0 ); // Echo("Term ",k,"is ",N(term/(Pi*Sqrt(2)))); pa:=pa+term; // Echo("result", N(pa/(Pi*Sqrt(2)))); ]; pa:=N(pa/(Pi*Sqrt(2))); Builtin'Precision'Set(GlobalPop()); Round(pa); ]; /// integer partitions by recurrence relation P(n) = Sum(k,1,n, (-1)^(k+1)*( P(n-k*(3*k-1)/2)+P(n-k*(3*k+1)/2) ) ) = P(n-1)+P(n-2)-P(n-5)-P(n-7)+... /// where 1, 2, 5, 7, ... is the "generalized pentagonal sequence" /// this method is faster with internal math for number<300 or so. PartitionsP'recur(number_IsPositiveInteger) <-- [ // need storage of n values PartitionsP(k) for k=1,...,n Local(sign, cache, n, k, pentagonal, P); cache:=Array'Create(number+1,1); // cache[n] = PartitionsP(n-1) n := 1; While(n<number) // this will never execute if number=1 [ n++; // compute PartitionsP(n) now P := 0; k := 1; pentagonal := 1; // pentagonal is always equal to the first element in the k-th pair of the "pentagonal sequence" of pairs {k*(3*k-1)/2, k*(3*k+1)/2} sign := 1; While(pentagonal<=n) [ P := P + (cache[n-pentagonal+1]+If(pentagonal+k<=n, cache[n-pentagonal-k+1], 0))*sign; pentagonal := pentagonal + 3*k+1; k++; sign := -sign; ]; cache[n+1] := P; // P(n) computed, store result ]; cache[number+1]; ]; PartitionsP'recur(0) <-- 1; // the product of all the elements of a list Product(list_IsList) <-- [ Local(product); product:=1; ForEach(i,list) product:=product*i; product; ]; Eulerian(n_IsInteger,k_IsInteger) <-- Sum(j,0,k+1,(-1)^j*Bin(n+1,j)*(k-j+1)^n); 10 # StirlingNumber1(n_IsInteger,0) <-- If(n=0,1,0); 10 # StirlingNumber1(n_IsInteger,1) <-- (-1)^(n-1)*(n-1)!; 10 # StirlingNumber1(n_IsInteger,2) <-- (-1)^n*(n-1)! * HarmonicNumber(n-1); 10 # StirlingNumber1(n_IsInteger,n-1) <-- -Bin(n,2); 10 # StirlingNumber1(n_IsInteger,3) <-- (-1)^(n-1)*(n-1)! * (HarmonicNumber(n-1)^2 - HarmonicNumber(n-1,2))/2; 20 # StirlingNumber1(n_IsInteger,m_IsInteger) <-- Sum(k,0,n-m,(-1)^k*Bin(k+n-1,k+n-m)*Bin(2*n-m,n-k-m)*StirlingNumber2(k-m+n,k)); 10 # StirlingNumber2(n_IsInteger,0) <-- If(n=0,1,0); 20 # StirlingNumber2(n_IsInteger,k_IsInteger) <-- Sum(i,0,k-1,(-1)^i*Bin(k,i)*(k-i)^n)/ k! ; 10 # BellNumber(n_IsInteger) <-- Sum(k,1,n,StirlingNumber2(n,k)); 5 # Euler(0) <-- 1; 10 # Euler(n_IsOdd) <-- 0; 10 # Euler(n_IsEven) <-- - Sum(r,0,n/2-1,Bin(n,2*r)*Euler(2*r)); 10 # Euler(n_IsNonNegativeInteger,_x) <-- Sum(i,0,Round(n/2),Bin(n,2*i)*Euler(2*i)*(x-1/2)^(n-2*i)/2^(2*i)); /** Compute an array of Euler numbers using recurrence relations. */ 10 # EulerArray(n_IsInteger) <-- [ Local(E,i,sum,r); E:=ZeroVector(n+1); E[1]:=1; For(i:=1,2*i<=n,i++)[ sum:=0; For(r:=0,r<=i-1,r++)[ sum:=sum+Bin(2*i,2*r)*E[2*r+1]; ]; E[2*i+1] := -sum; ]; E; ];
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.seq.db.emblcd; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import junit.framework.TestCase; /** * <code>EntryNamRandomAccessTest</code> is a unit test of random * access reading the binary entrynam.idx file type. * * @author Keith James * @since 1.2 */ public class EntryNamRandomAccessTest extends TestCase { protected EntryNamRandomAccess rand; protected String [] seqID; protected long [] rPos; protected long [] sPos; protected int [] fileNum; public EntryNamRandomAccessTest(String name) { super(name); } protected void setUp() throws Exception { URL url = EntryNamRandomAccessTest.class.getResource("entrynam.idx"); File f = new File(url.toURI()); rand = new EntryNamRandomAccess(f, 300, 30, 30); // First 10 sequence IDs. seqID = new String [] {"NMA0001", "NMA0003", "NMA0004", "NMA0007", "NMA0011", "NMA0012", "NMA0013", "NMA0020", "NMA0021", "NMA0022" }; // First 10 sequence byte offsets. There is more than one 0 // byte offset because the database consists of more than one // sequence file. rPos = new long [] { 0, 917, 1097, 1811, 0, 156, 270, 2379, 0, 283}; // First 10 sequence file numbers. fileNum = new int [] { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3 }; } protected void tearDown() throws Exception { rand.close(); } public void testFindRecord() throws IOException { for (int i = 0; i < 10; i++) { Object [] rec = rand.findRecord(seqID[i]); assertEquals(seqID[i], (String) rec[0]); assertEquals(rPos[i], ((Long) rec[1]).longValue()); assertEquals(0, ((Long) rec[2]).longValue()); assertEquals(fileNum[i], ((Integer) rec[3]).intValue()); } } public void testGetFile() { assertEquals("entrynam.idx", rand.getFile().getName()); } }
import axios from "axios"; import { useEffect , useState } from "react"; function Weather() { const [weatherTemp,setWeatherTemp] = useState (''); const [weatherDesc,setWeatherDesc] = useState (''); const [weatherIcon,setWeatherIcon] = useState (''); const [weatherLocation,setWeatherLocation] = useState (''); useEffect(() => { const cityName = 'Seoul'; const apiKey = process.env.REACT_APP_WEATHER_API_KEY; const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}`; axios.get(url).then((res) => { const data = res.data; const temp = data.main.temp; setWeatherTemp((temp - 273.15).toFixed(1)); setWeatherDesc(data.weather[0].description); setWeatherIcon(data.weather[0].icon); setWeatherLocation(data.name); console.log(res); }).catch((err) => { console.log(err); }); },[]); const img = `http://openweathermap.org/img/wn/${weatherIcon}.png`; return ( <> <div className="weatherWrap"> <div className="weatherContainer"> <div className="weatherImg"> {weatherIcon && <img src={img} alt="weather"/>} </div> <div className="weatherDesc"> <span className="temp">{weatherTemp}°C</span> <span className="desc hidden">{weatherDesc}</span> </div> </div> <div className="location"> <span className="locationName">{weatherLocation}</span> </div> </div> </> ); } export default Weather;
import styled from 'styled-components'; import {useEffect, useState} from "react"; import {API} from "../Service/API/API"; import {filteredByCode} from "../config"; import {useNavigate} from "react-router-dom"; export const Info = (props) => { const { name, nativeName, flag, capital, population, region, subregion, topLevelDomain, currencies = [], languages = [], borders = [], } = props; const [neighbors, setNeighbors] = useState([]); useEffect(() => { API.get(filteredByCode(borders)) .then(({data}) => setNeighbors(data.map(el => el.name))) }, [borders]) const navigate = useNavigate(); return ( <Wrapper> <InfoImage src={flag} alt={name}/> <div> <InfoTitle>{name}</InfoTitle> <ListGroup> <List> <ListItem> <b>Native name:</b> {nativeName} </ListItem> <ListItem> <b>Population:</b> {population} </ListItem> <ListItem> <b>Region:</b> {region} </ListItem> <ListItem> <b>Sub region:</b> {subregion} </ListItem> <ListItem> <b>Capital:</b> {capital} </ListItem> </List> <List> <ListItem> <b>Top Level Domain</b> {topLevelDomain.map(el => (<span key={el}>{el}</span>))} </ListItem> <ListItem> <b>Currencies</b> {currencies.map(el => (<span key={el.code}>{el.name}</span>))} </ListItem> <ListItem> <b>Languages</b> {languages.map(el => (<span key={el.name}>{el.name}</span>))} </ListItem> </List> </ListGroup> <Meta> <b>Border Countries</b> {!borders.length ? ( <span>There is no border countries</span> ) : ( <TagGroup> {neighbors.map(el => (<Tag key={el} onClick={() => navigate(`/country/${el}`)}>{el}</Tag>))} </TagGroup> )} </Meta> </div> </Wrapper> ) } const Wrapper = styled.section` margin-top: 3rem; width: 100%; display: grid; grid-template-columns: 100%; gap: 2rem; @media(min-width: 767px) { grid-template-columns: minmax(100px, 400px) 1fr; align-items: center; gap: 5rem; } @media(min-width: 1240px) { grid-template-columns: minmax(400px, 600px) 1fr; } `; const InfoImage = styled.img` display: block; width: 100%; height: 100%; object-fit: contain; `; const InfoTitle = styled.h1` font-weight: var(--fw-normal); `; const ListGroup = styled.div` display: flex; flex-direction: column; gap: 2rem; @media (min-width: 1024px) { flex-direction: row; gap: 4rem; } ` const List = styled.ul` list-style: none; `; const ListItem = styled.li` line-height: 1.8; & > b { font-weight: var(--fw-bold); } `; const Meta = styled.div` margin-top: 3rem; display: flex; gap: 1.5rem; flex-direction: column; align-items: flex-start; & > b { font-weight: var(--fw-bold); } @media (min-width: 767px) { flex-direction: row; align-items: center; } `; const TagGroup = styled.div` display: flex; gap: 1rem; flex-wrap: wrap; `; const Tag = styled.span` padding: 0 1rem; background-color: var(--colors-ui-base); box-shadow: var(--shadow); line-height: 1.5; cursor: pointer; `
<?php /** * Template part for displaying post content slider */ if ( have_rows( 'post_slider' ) ) : ?> <div class="post-slider"> <div id="carouselPostSlider" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <?php while( have_rows( 'post_slider' ) ) : the_row(); ?> <div class="carousel-item <?php echo get_row_index() == 1 ? 'active' : ''; ?>"> <img src="<?php the_sub_field( 'image' ); ?>" alt="slide"> <?php if ( get_sub_field( 'image_note' ) ) : ?> <div class="carousel-caption"><?php the_sub_field( 'image_note' ); ?></div> <?php endif; ?> </div> <?php endwhile; ?> </div> <a class="carousel-control-prev" href="#carouselPostSlider" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselPostSlider" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <?php endif;
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'; import Home from './pages/Home'; import Profile from './pages/Profile'; import Login from './pages/Login'; import Register from './pages/Register'; import Header from './components/Header'; import { Toaster } from 'react-hot-toast'; import { useEffect } from 'react'; import axios from 'axios'; import { server } from './main'; import { Context } from './main'; import { useContext } from 'react'; function App() { const {setUser, setIsAuthenticated, setLoading} = useContext(Context); useEffect(() => { setLoading(true); axios.get(`${server}/users/me`, { withCredentials: true, }).then(res=> { setUser(res.data.user); setIsAuthenticated(true); setLoading(false); }).catch((error) => { setUser({}); setIsAuthenticated(true); setLoading(false); }) }, []) return ( <Router> <Header/> <Routes> <Route path='/' element={<Home/>} /> <Route path='/profile' element={<Profile/>} /> <Route path='/login' element={<Login/>} /> <Route path='/register' element={<Register/>} /> </Routes> <Toaster/> </Router> ); } export default App
<ion-header> <ion-navbar color="one"> <ion-title>اضافة بطاقة</ion-title> </ion-navbar> </ion-header> <ion-content no-bounce> <ion-list> <form novalidate (ngSubmit)="saveCard()" [formGroup]="accountForm"> <ion-item> <ion-label floating>الأسم</ion-label> <ion-input type="text" maxlength="30" minlength="4" [(ngModel)]="accountData.name" formControlName="name" [class.error1]="!accountForm.controls.name.valid && accountForm.controls.name.dirty"></ion-input> </ion-item> <ion-item no-lines *ngIf="( accountForm.get('name').hasError('minlength') || accountForm.get('name').hasError('maxlength') ||accountForm.get('name').hasError('pattern') ||accountForm.get('name').hasError('required') ) && accountForm.get('name').touched"> <div class="error" *ngIf="accountForm.get('name').hasError('required') && accountForm.get('name').touched"> الرجاء اضافة اسم للبطاقة </div> <div class="error" *ngIf="accountForm.get('name').hasError('minlength') && accountForm.get('name').touched"> اقل عدد للحروف 3 </div> <div class="error" *ngIf="accountForm.get('name').hasError('maxlength') && accountForm.get('name').touched"> لا يمكن اضافة اكثر من 10 حرف </div> <div class="error" *ngIf="accountForm.get('name').hasError('pattern') && accountForm.get('name').touched"> فقط حروف بدون ارقام\رموز\فواصل </div> </ion-item> <ion-item> <ion-label floating>رقم البطاقة:</ion-label> <ion-input type="number" maxlength="19" minlength="4" [(ngModel)]="accountData.PAN" formControlName="PAN" [class.error1]="!accountForm.controls.PAN.valid && accountForm.controls.PAN.dirty"></ion-input> </ion-item> <ion-item no-lines *ngIf="( accountForm.get('PAN').hasError('minlength') || accountForm.get('PAN').hasError('maxlength') ||accountForm.get('PAN').hasError('pattern') ||accountForm.get('PAN').hasError('required') ) && accountForm.get('PAN').touched"> <div class="error" *ngIf="accountForm.get('PAN').hasError('PAN') && accountForm.get('PAN').touched"> الرجاء ادخال رقم البطاقة </div> <div class="error" *ngIf="accountForm.get('PAN').hasError('minlength') && accountForm.get('PAN').touched"> اقل عدد لرقم البطاقة 16 </div> <div class="error" *ngIf="accountForm.get('PAN').hasError('maxlength') && accountForm.get('PAN').touched"> لا بمكن اضافة اكثر من 19 رقم </div> <div class="error" *ngIf="accountForm.get('PAN').hasError('pattern') && accountForm.get('PAN').touched"> فقط ارقام </div> </ion-item> <!--<ion-item>--> <!--<ion-label floating>الرقم السري</ion-label>--> <!--<ion-input type="password" maxlength="4" minlength="4" [(ngModel)]="accountData.IPIN" formControlName="IPIN"--> <!--[class.error1]="!accountForm.controls.IPIN.valid && accountForm.controls.IPIN.dirty"></ion-input>--> <!--</ion-item>--> <!--<ion-item no-lines *ngIf="( accountForm.get('IPIN').hasError('minlength') || accountForm.get('IPIN').hasError('maxlength') ||accountForm.get('IPIN').hasError('pattern') ||accountForm.get('IPIN').hasError('required') ) && accountForm.get('IPIN').touched">--> <!--<div class="error" *ngIf="accountForm.get('IPIN').hasError('IPIN') && accountForm.get('IPIN').touched">--> <!--الرجاء ادخال الرقم السر المكونة من 4 اراقم الخاص بالبطاقة--> <!--</div>--> <!--<div class="error" *ngIf="accountForm.get('IPIN').hasError('minlength') && accountForm.get('IPIN').touched">--> <!--اقل عدد 4--> <!--</div>--> <!--<div class="error" *ngIf="accountForm.get('IPIN').hasError('maxlength') && accountForm.get('IPIN').touched">--> <!--لا يمكن اضافة اكثر من 4 ارقام--> <!--</div>--> <!--<div class="error" *ngIf="accountForm.get('IPIN').hasError('pattern') && accountForm.get('IPIN').touched">--> <!--فقط ارقام--> <!--</div>--> <!--</ion-item>--> <ion-item> <ion-label floating>تاريخ انتهاء البطاقة</ion-label> <ion-datetime displayFormat="MM, YY" pickerFormat="MM YYYY" [(ngModel)]="accountData.expDate" placeholder="شهر - عام" min="{{min}}" max="2090-10-20" formControlName="expDate"></ion-datetime> </ion-item> <button type="submit" ion-button block color="one" [disabled]="accountForm.invalid">حفظ</button> </form> </ion-list> </ion-content>
/*############################################################################################### ####################################### VECCHIATRON ############################################# ################################################################################################# $ Title : Atmega32 Registers $ Author : A.Ali Mahrez $ Author contact : [email protected] $ Target : AVR Atmega32 $ Date : Oct 25th, 2022 $ Version : V005.22 $ Description : None $ Notes : None ################################################################################################## ##################################################################################################*/ #include "../../02_LIB/stdtypes.h" #include "../../02_LIB/bitmath.h" #include "../../02_LIB/atmega32_Registers.h" #include "DIO_interface.h" /* ******************************************************************************************************* ************************************* PORT DIRECTION ************************************************** ******************************************************************************************************* */ void DIO_vidPortDirection(Port_Name port, Port_Direction direction) { switch (port) { case PA: DDRA_REG = (direction == OUTPUT) ? 0xFF : 0X00; break; case PB: DDRB_REG = (direction == OUTPUT) ? 0xFF : 0X00; break; case PC: DDRC_REG = (direction == OUTPUT) ? 0xFF : 0X00; break; case PD: DDRD_REG = (direction == OUTPUT) ? 0xFF : 0X00; break; } } void DIO_vidPinDirection(Port_Name port, Pin_Number pin, Port_Direction direction) { switch (port) { case PA: (direction == OUTPUT) ? SET_BIT(DDRA_REG, pin) : CLR_BIT(DDRA_REG, pin); break; case PB: (direction == OUTPUT) ? SET_BIT(DDRB_REG, pin) : CLR_BIT(DDRB_REG, pin); break; case PC: (direction == OUTPUT) ? SET_BIT(DDRC_REG, pin) : CLR_BIT(DDRC_REG, pin); break; case PD: (direction == OUTPUT) ? SET_BIT(DDRD_REG, pin) : CLR_BIT(DDRD_REG, pin); break; } } void DIO_vidPinInDirectionWithPullState(Port_Name port, Pin_Number pin, Pull_State pull) { switch (port) { case PA: CLR_BIT(DDRA_REG, pin); if (pull == INTERNAL_PULLUP) { SET_BIT(PORTA_REG, pin); CLR_BIT(SFIOR_REG, 2); } else { CLR_BIT(PORTA_REG, pin); SET_BIT(SFIOR_REG, 2); } break; case PB: CLR_BIT(DDRB_REG, pin); if (pull == INTERNAL_PULLUP) { SET_BIT(PORTB_REG, pin); CLR_BIT(SFIOR_REG, 2); } else { CLR_BIT(PORTB_REG, pin); SET_BIT(SFIOR_REG, 2); } break; case PC: CLR_BIT(DDRC_REG, pin); if (pull == INTERNAL_PULLUP) { SET_BIT(PORTC_REG, pin); CLR_BIT(SFIOR_REG, 2); } else { CLR_BIT(PORTC_REG, pin); SET_BIT(SFIOR_REG, 2); } break; case PD: CLR_BIT(DDRD_REG, pin); if (pull == INTERNAL_PULLUP) { SET_BIT(PORTD_REG, pin); CLR_BIT(SFIOR_REG, 2); } else { CLR_BIT(PORTD_REG, pin); SET_BIT(SFIOR_REG, 2); } break; } } void DIO_vidPortRangeDirection(Port_Name port, Pin_Number stPin, Pin_Number endPin, Port_Direction direction) { U16 i; switch (port) { case PA: for (i = stPin; i <= endPin; i++) SET_BIT(DDRA_REG, i); break; case PB: for (i = stPin; i <= endPin; i++) SET_BIT(DDRB_REG, i); break; case PC: for (i = stPin; i <= endPin; i++) SET_BIT(DDRC_REG, i); break; case PD: for (i = stPin; i <= endPin; i++) SET_BIT(DDRD_REG, i); break; } } /* ******************************************************************************************************* ************************************* WRITING TO PORT ************************************************* ******************************************************************************************************* */ void DIO_vidPortWrite(Port_Name port, PinState value) { switch (port) { case PA: PORTA_REG = (value == HIGH) ? 0xFF : 0X00; break; case PB: PORTB_REG = (value == HIGH) ? 0xFF : 0X00; break; case PC: PORTC_REG = (value == HIGH) ? 0xFF : 0X00; break; case PD: PORTD_REG = (value == HIGH) ? 0xFF : 0X00; break; } } void DIO_vidPinWrite(Port_Name port, Pin_Number pin, PinState value) { switch (port) { case PA: (value == HIGH) ? SET_BIT(PORTA_REG, pin) : CLR_BIT(PORTA_REG, pin); break; case PB: (value == HIGH) ? SET_BIT(PORTB_REG, pin) : CLR_BIT(PORTB_REG, pin); break; case PC: (value == HIGH) ? SET_BIT(PORTC_REG, pin) : CLR_BIT(PORTC_REG, pin); break; case PD: (value == HIGH) ? SET_BIT(PORTD_REG, pin) : CLR_BIT(PORTD_REG, pin); break; } } void DIO_vidPortRangeWrite(Port_Name port, Pin_Number stPin, Pin_Number endPin, PinState value) { U16 i; switch (port) { case PA: if (value == HIGH) for (i = stPin; i <= endPin; i++) SET_BIT(PORTA_REG, i); else for (i = stPin; i <= endPin; i++) CLR_BIT(PORTA_REG, i); break; case PB: if (value == HIGH) for (i = stPin; i <= endPin; i++) SET_BIT(PORTB_REG, i); else for (i = stPin; i <= endPin; i++) CLR_BIT(PORTB_REG, i); break; case PC: if (value == HIGH) for (i = stPin; i <= endPin; i++) SET_BIT(PORTC_REG, i); else for (i = stPin; i <= endPin; i++) CLR_BIT(PORTC_REG, i); break; case PD: if (value == HIGH) for (i = stPin; i <= endPin; i++) SET_BIT(PORTD_REG, i); else for (i = stPin; i <= endPin; i++) CLR_BIT(PORTD_REG, i); break; } } /* ******************************************************************************************************* ************************************* READING FROM PORT *********************************************** ******************************************************************************************************* */ void DIO_vidPortRead(Port_Name port, U8 *value) { switch (port) { case PA: *value = PINA_REG; break; case PB: *value = PINB_REG; break; case PC: *value = PINC_REG; break; case PD: *value = PIND_REG; break; } } void DIO_vidPinRead(Port_Name port, Pin_Number pin, U8 *pinValue) { switch (port) { case PA: *pinValue = GET_BIT(PINA_REG, pin); break; case PB: *pinValue = GET_BIT(PINB_REG, pin); break; case PC: *pinValue = GET_BIT(PINC_REG, pin); break; case PD: *pinValue = GET_BIT(PIND_REG, pin); break; } } U8 DIO_u8PinReadValue(Port_Name port, Pin_Number pin) { switch (port) { case PA: return GET_BIT(PINA_REG, pin); break; case PB: return GET_BIT(PINB_REG, pin); break; case PC: return GET_BIT(PINC_REG, pin); break; case PD: return GET_BIT(PIND_REG, pin); break; } return 'X'; } void DIO_vidPortRangeRead(Port_Name port, Pin_Number stPin, Pin_Number endPin, U8 *pinValue) { U16 i; switch (port) { case PA: *pinValue = 0x00; for (i = stPin; i <= endPin; i++) *pinValue = GET_BIT(PINA_REG, i); break; case PB: *pinValue = 0x00; for (i = stPin; i <= endPin; i++) *pinValue = GET_BIT(PINB_REG, i); break; case PC: *pinValue = 0x00; for (i = stPin; i <= endPin; i++) *pinValue = GET_BIT(PINC_REG, i); break; case PD: *pinValue = 0x00; for (i = stPin; i <= endPin; i++) *pinValue = GET_BIT(PIND_REG, i); break; } } /* ******************************************************************************************************* ******************************************* TOGGLE PORT *********************************************** ******************************************************************************************************* */ void DIO_vidPortToggle(Port_Name port) { U16 i; switch (port) { case PA: for (i = 0; i <= 8; i++) TOG_BIT(PORTA_REG, i); break; case PB: for (i = 0; i <= 8; i++) TOG_BIT(PORTB_REG, i); break; case PC: for (i = 0; i <= 8; i++) TOG_BIT(PORTC_REG, i); break; case PD: for (i = 0; i <= 8; i++) TOG_BIT(PORTD_REG, i); break; } } void DIO_vidPinToggle(Port_Name port, Pin_Number pin) { switch (port) { case PA: TOG_BIT(PORTA_REG, pin); break; case PB: TOG_BIT(PORTB_REG, pin); break; case PC: TOG_BIT(PORTC_REG, pin); break; case PD: TOG_BIT(PORTD_REG, pin); break; } } void DIO_vidPortRangeToggle(Port_Name port, Pin_Number stPin, Pin_Number endPin) { U16 i; switch (port) { case PA: for (i = stPin; i <= endPin; i++) TOG_BIT(PORTA_REG, i); break; case PB: for (i = stPin; i <= endPin; i++) TOG_BIT(PORTB_REG, i); break; case PC: for (i = stPin; i <= endPin; i++) TOG_BIT(PORTC_REG, i); break; case PD: for (i = stPin; i <= endPin; i++) TOG_BIT(PORTD_REG, i); break; } }
import { useDispatch, useSelector } from 'react-redux'; import { useEffect } from 'react'; import { ContactForm } from './ContactForm/ContactForm'; import { ContactList } from './ContactList/ContactList'; import { Filter } from './Filter/Filter'; import { Loader } from './Loader/Loader'; import { selectContacts, selectIsLoading } from 'redux/selectors'; import { fetchContacts } from 'redux/operations'; export const App = () => { const contacts = useSelector(selectContacts); const isLoading = useSelector(selectIsLoading); const dispatch = useDispatch(); useEffect(() => { dispatch(fetchContacts()); }, [dispatch]); return ( <div> <section title="Phonebook"> <ContactForm /> </section> <section title="Contacts"> {isLoading && <Loader />} {!isLoading && contacts.length !== 0 && <Filter />} {!isLoading && contacts.length !== 0 && <ContactList />} </section> </div> ); };
/* * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the dreamlu.net developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: Chill 庄骞 ([email protected]) */ package org.springblade.modules.archives.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; import lombok.EqualsAndHashCode; import org.springblade.core.tenant.mp.TenantEntity; /** * 激活码 实体类 * * @author BladeX * @since 2023-03-11 */ @Data @TableName("xy_active_code") @ApiModel(value = "ActiveCode对象", description = "激活码") @EqualsAndHashCode(callSuper = true) public class ActiveCodeEntity extends TenantEntity { /** * 激活码 */ @ApiModelProperty(value = "激活码") private String code; /** * 手机号 */ @ApiModelProperty(value = "手机号") private String phone; /** * mac地址 */ @ApiModelProperty(value = "mac地址") private String mac; /** * 激活码结束时间 */ @ApiModelProperty(value = "激活码结束时间") private Date endTime; /** * 激活码限制下载次数 */ @ApiModelProperty(value = "激活码限制下载次数") private Integer downloadTimes; }
import csv import io from uuid import uuid4 from rest_framework.test import APITestCase from app.factories import ConsumerFactory from app.models import Consumer from app.tests.utils import TestCaseMixin class TestPost(TestCaseMixin, APITestCase): def test_that_it_returns_expected_response(self): client_ref = str(uuid4()) csv_file = io.StringIO() csv.writer(csv_file).writerows( [ ["ssn", "client reference no", "consumer name", "consumer address", "balance", "status"], ["123-45-6789", client_ref, "Jane Doe", "123 Main St", "1000", Consumer.StatusChoices.IN_COLLECTION], ] ) csv_file.seek(0) response = self.client.post("/consumers/upload_csv/", {"file": csv_file}, format="multipart") expected_data = [ { "address": "123 Main St", "balance": 1000.0, "client_ref_number": client_ref, "name": "Jane Doe", "status": Consumer.StatusChoices.IN_COLLECTION, }, ] self.assertOkResponse(response, expected_data) def test_when_consumer_does_not_exist_then_creates_it(self): ssn = "123-45-6789" client_ref = str(uuid4()) csv_file = io.StringIO() csv.writer(csv_file).writerows( [ ["ssn", "client reference no", "consumer name", "consumer address", "balance", "status"], [ssn, client_ref, "Jane Doe", "123 Main St", "1000", Consumer.StatusChoices.IN_COLLECTION], [ssn, client_ref, "Jane Doe", "123 Main St", "1020", Consumer.StatusChoices.PAID_IN_FULL], ] ) csv_file.seek(0) self.client.post("/consumers/upload_csv/", {"file": csv_file}, format="multipart") queryset = Consumer.objects.filter( ssn=ssn, client_ref_number=client_ref, name="Jane Doe", balance=1020.0, status=Consumer.StatusChoices.PAID_IN_FULL, address="123 Main St", ) self.assertTrue(queryset.exists()) def test_when_there_are_multiple_entries_then_correctly_updates_the_consumer(self): consumer = ConsumerFactory() csv_file = io.StringIO() csv.writer(csv_file).writerows( [ ["ssn", "client reference no", "consumer name", "consumer address", "balance", "status"], [ consumer.ssn, consumer.client_ref_number, consumer.name, consumer.address, str(consumer.balance), consumer.status, ], [ consumer.ssn, consumer.client_ref_number, consumer.name, consumer.address, str(consumer.balance + 20), Consumer.StatusChoices.INACTIVE, ], [ consumer.ssn, consumer.client_ref_number, consumer.name, consumer.address, str(consumer.balance + 10), Consumer.StatusChoices.IN_COLLECTION, ], [ consumer.ssn, consumer.client_ref_number, consumer.name, consumer.address, str(consumer.balance + 30), Consumer.StatusChoices.PAID_IN_FULL, ], ] ) csv_file.seek(0) self.client.post("/consumers/upload_csv/", {"file": csv_file}, format="multipart") expected_balance = consumer.balance + 30 consumer.refresh_from_db() self.assertListEqual( [consumer.balance, consumer.status], [expected_balance, Consumer.StatusChoices.PAID_IN_FULL], ) def test_that_it_performs_expected_amount_of_queries(self): consumer = ConsumerFactory() csv_file = io.StringIO() csv.writer(csv_file).writerows( [ ["ssn", "client reference no", "consumer name", "consumer address", "balance", "status"], [ consumer.ssn, consumer.client_ref_number, consumer.name, consumer.address, str(consumer.balance), consumer.status, ], ["123-45-6789", str(uuid4()), "Cool Name", "1 Cool Street", "2", Consumer.StatusChoices.INACTIVE], ["123-45-6789", str(uuid4()), "Cool Name", "1 Cool Street", "500", Consumer.StatusChoices.PAID_IN_FULL], [ consumer.ssn, consumer.client_ref_number, consumer.name, consumer.address, str(consumer.balance + 30), Consumer.StatusChoices.IN_COLLECTION, ], ] ) csv_file.seek(0) with self.assertNumQueries(5): """ Captured queries were: 1. SAVEPOINT "s140150754138888_x2" 2. SELECT "app_consumer"."ssn", "app_consumer"."client_ref_number", "app_consumer"."name", "app_consumer"."balance", "app_consumer"."status", "app_consumer"."address", "app_consumer"."created_date" FROM "app_consumer" WHERE "app_consumer"."ssn" IN ('325-58-2568', '123-45-6789') 3. INSERT INTO "app_consumer" ("ssn", "client_ref_number", "name", "balance", "status", "address", "created_date") VALUES ('123-45-6789', '3d13ab8b-1fc9-43fd-8ffd-baaaefffc7d1'::uuid, 'Cool Name', 500.0, 'PAID_IN_FULL', '1 Cool Street', '2024-02-21T15:24:12.797534+00:00'::timestamptz) 4. UPDATE "app_consumer" SET "balance" = (CASE WHEN ("app_consumer"."ssn" = '325-58-2568') THEN 962.0 WHEN ("app_consumer"."ssn" = '123-45-6789') THEN 500.0 ELSE NULL END)::double precision, "status" = (CASE WHEN ("app_consumer"."ssn" = '325-58-2568') THEN 'IN_COLLECTION' WHEN ("app_consumer"."ssn" = '123-45-6789') THEN 'PAID_IN_FULL' ELSE NULL END)::varchar(13), "client_ref_number" = (CAST(CASE WHEN ("app_consumer"."ssn" = '325-58-2568') THEN 'c31d50ac-bb42-46e4-b351-e4357cf8d21c'::uuid WHEN ("app_consumer"."ssn" = '123-45-6789') THEN '3d13ab8b-1fc9-43fd-8ffd-baaaefffc7d1'::uuid ELSE NULL END AS uuid))::uuid, "name" = (CASE WHEN ("app_consumer"."ssn" = '325-58-2568') THEN 'Consumer 0' WHEN ("app_consumer"."ssn" = '123-45-6789') THEN 'Cool Name' ELSE NULL END)::varchar(255), "address" = (CASE WHEN ("app_consumer"."ssn" = '325-58-2568') THEN 'PSC 4887, Box 3493 APO AP 01800' WHEN ("app_consumer"."ssn" = '123-45-6789') THEN '1 Cool Street' ELSE NULL END)::varchar(255) WHERE "app_consumer"."ssn" IN ('325-58-2568', '123-45-6789') 5. RELEASE SAVEPOINT "s140150754138888_x2" """ self.client.post("/consumers/upload_csv/", {"file": csv_file}, format="multipart")
# # (C) Tenable Network Security, Inc. # include("compat.inc"); if (description) { script_id(86853); script_version("1.9"); script_cvs_date("Date: 2019/11/20"); script_cve_id( "CVE-2015-7651", "CVE-2015-7652", "CVE-2015-7653", "CVE-2015-7654", "CVE-2015-7655", "CVE-2015-7656", "CVE-2015-7657", "CVE-2015-7658", "CVE-2015-7659", "CVE-2015-7660", "CVE-2015-7661", "CVE-2015-7662", "CVE-2015-7663", "CVE-2015-8042", "CVE-2015-8043", "CVE-2015-8044", "CVE-2015-8046" ); script_name(english:"Adobe AIR for Mac <= 19.0.0.213 Multiple Vulnerabilities (APSB15-28)"); script_summary(english:"Checks the version of AIR."); script_set_attribute(attribute:"synopsis", value: "The remote Mac OS X host has a browser plugin installed that is affected by multiple vulnerabilities."); script_set_attribute(attribute:"description", value: "The version of Adobe AIR installed on the remote Mac OS X host is equal or prior to version 19.0.0.213. It is, therefore, affected by multiple vulnerabilities : - A type confusion error exists that allows an attacker to execute arbitrary code. (CVE-2015-7659) - A security bypass vulnerability exists that allows an attacker to write arbitrary data to the file system under user permissions. (CVE-2015-7662) - Multiple use-after-free vulnerabilities exist that allow an attacker to execute arbitrary code. (CVE-2015-7651, CVE-2015-7652, CVE-2015-7653, CVE-2015-7654, CVE-2015-7655, CVE-2015-7656, CVE-2015-7657, CVE-2015-7658, CVE-2015-7660, CVE-2015-7661, CVE-2015-7663, CVE-2015-8042, CVE-2015-8043, CVE-2015-8044, CVE-2015-8046)"); script_set_attribute(attribute:"see_also", value:"https://helpx.adobe.com/security/products/flash-player/apsb15-28.html"); script_set_attribute(attribute:"solution", value: "Upgrade to Adobe AIR version 19.0.0.241 or later."); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:C/I:C/A:C"); script_set_cvss_temporal_vector("CVSS2#E:POC/RL:OF/RC:C"); script_set_attribute(attribute:"cvss_score_source", value:"CVE-2015-8046"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"vuln_publication_date", value:"2015/11/10"); script_set_attribute(attribute:"patch_publication_date", value:"2015/11/10"); script_set_attribute(attribute:"plugin_publication_date", value:"2015/11/11"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"cpe:/a:adobe:air"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_family(english:"MacOS X Local Security Checks"); script_copyright(english:"This script is Copyright (C) 2015-2019 and is owned by Tenable, Inc. or an Affiliate thereof."); script_dependencies("macosx_adobe_air_installed.nasl"); script_require_keys("MacOSX/Adobe_AIR/Version"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("misc_func.inc"); kb_base = "MacOSX/Adobe_AIR"; version = get_kb_item_or_exit(kb_base+"/Version"); path = get_kb_item_or_exit(kb_base+"/Path"); # nb: we're checking for versions less than *or equal to* the cutoff! cutoff_version = '19.0.0.213'; fixed_version_for_report = '19.0.0.241'; if (ver_compare(ver:version, fix:cutoff_version, strict:FALSE) <= 0) { if (report_verbosity > 0) { report = '\n Path : ' + path + '\n Installed version : ' + version + '\n Fixed version : ' + fixed_version_for_report + '\n'; security_hole(port:0, extra:report); } else security_hole(0); exit(0); } else audit(AUDIT_INST_PATH_NOT_VULN, "Adobe AIR", version, path);
@extends('layouts.app') @section('content') <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Stripe Payment</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://js.stripe.com/v3/"></script> <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css')}}"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-4"> <img class="img-rounded" style="width:360px;" src = "{{ asset('img/stripe.jpeg') }}"> <div class="panel-body"> <form action="/api/pay" method="post" id="payment-form"> <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div class="panel-body"> <div id="card-element"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display Element errors. --> <div id="card-errors" role="alert"></div> </div> </div> <button class="btn btn-default">Submit Payment</button> </form> <a href = "{{route('payments.index')}}" class = "btn btn-default">Back</a> </div> </div> <div class="col-md-3"> </div> </div> </div> <script type="text/javascript"> var stripe = Stripe('pk_test_Ulg5Z8eY3NSJk2TtlmaAsMnU'); var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. var style = { base: { // Add your base input styles here. For example: fontSize: '16px', color: "#32325d", } }; // Create an instance of the card Element. var card = elements.create('card', {style: style}); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element'); card.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); // Create a token or display an error when the form is submitted. //var token=""; //var form =""; var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { // Inform the customer that there was an error. var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // Send the token to your server. stripeTokenHandler(result.token); } }); }); function stripeTokenHandler(token) { //console.log(token); // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); //Submit the form form.submit(); } </script> </body> </html> @endsection
[[vk::binding(0, 0)]] StructuredBuffer<uint> values; [[vk::binding(1, 0)]] RWByteAddressBuffer histogram; struct PushConstant { uint bin_size; }; // Use push constants to define the bin size [[vk::push_constant]] PushConstant constants; groupshared uint g_ScratchBuffer[256]; // scratch buffer /** * Entrypoint for compute shader. Computes a histogram working on 4096 bytes at a time (4 bytes per dispatch). * * @param group_index - Index of the local dispatch within the group * @param global_id - Indiex of the global dispatch */ [numthreads(1024, 1, 1)] void CSMain(uint group_index : SV_GROUPINDEX, uint3 global_id : SV_DISPATCHTHREADID) { uint stride; uint structs; values.GetDimensions(structs, stride); // Verify the current dispatch thread isn't any larger than the size of the array // This allows the shader to correctly handle value arrays not sized as a multiple // of 4096 bytes if (global_id.x >= structs) { return; } uint local = group_index / 4; g_ScratchBuffer[local] = 0; // Wait for scratch buffer clear before writing GroupMemoryBarrierWithGroupSync(); // Read 4 bytes uint value = values[global_id.x]; uint b0 = (value >> 24) & 0xFF; uint b1 = (value >> 16) & 0xFF; uint b2 = (value >> 8) & 0xFF; uint b3 = (value >> 0) & 0xFF; // Compute the bin for each byte and increment the size of that bin in the scratch buffer InterlockedAdd(g_ScratchBuffer[b0 / constants.bin_size], 1); InterlockedAdd(g_ScratchBuffer[b1 / constants.bin_size], 1); InterlockedAdd(g_ScratchBuffer[b2 / constants.bin_size], 1); InterlockedAdd(g_ScratchBuffer[b3 / constants.bin_size], 1); // Wait for all writes to scratch buffer before uploading GroupMemoryBarrierWithGroupSync(); // Apply this group's histograms to the global histogram bool is_write_eligible = (group_index % 4) == 0; // check if the local thread is aligned for a bin write bool is_legal_bin = local < ceil(256.0 / constants.bin_size); // check if the bin written to is in bounds if (is_write_eligible && is_legal_bin) { histogram.InterlockedAdd(group_index, g_ScratchBuffer[local]); } }
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Http\Requests\StoreOrderItemRequest; use App\Models\OrderItem; use App\Http\Resources\OrderItemResource; /*** *** operation_object: OrderItem *** operation_heading: Order Item ***/ class OrderItemController extends Controller { function __construct() { parent::__construct($this); } /** * Display a listing of the resource. * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Resources\Json\JsonResource */ /*** * operation_name: list * operation_label: List */ function index(Request $request) { $query = OrderItem:: with([ 'user', 'product', 'order', ]); $keyword = $request->get("keyword"); if ($keyword) { $query->where("name", "like", "%{$keyword}%"); } $orderItems = $query->paginate(); return OrderItemResource::collection($orderItems); } /** * Form data required to add new record * @param \Illuminate\Http\Request $request * @return Array; */ /*** * operation_name: create * operation_label: Create */ function data(Request $request) { $data = [ "users" => \App\Http\Resources\UserResource::collection(\App\Models\User::all())->toArray(), "products" => \App\Http\Resources\ProductResource::collection(\App\Models\Product::all())->toArray(), "orders" => \App\Http\Resources\OrderResource::collection(\App\Models\Order::all())->toArray(), ]; return $data; } /** * Store new record * @param \App\Http\StoreOrderItemRequest $request * @return \Illuminate\Http\Resources\Json\JsonResource */ /*** * operation_name: create * operation_label: Create */ function store(StoreOrderItemRequest $request) { $data = $request->validated(); $data = array_filter($data); try { $orderitem = OrderItem::create($data); if ($request->hasFile("logo")) { $uploader = new \App\Services\Uploader("logo", "orders"); $filename = $uploader->upload(); \App\Models\Image::create([ "object_type" => get_class($orderitem), "object_id" => $orderitem->id, "name" => "logo", "type" => "image", "file_name" => $filename ]); } return response()->json([ "code" => 200, "message" => "Order Item Created Successfully!" ], 201); } catch (\Exception $ex) { return response()->json([ "code" => 500, "message" => $ex->getMessage() ], 500); } } /** * Update record * @param \Illuminate\Http\Request $request * @param integer $id * @return \Illuminate\Http\Resources\Json\JsonResource */ /*** * operation_name: edit * operation_label: Edit */ function update(StoreOrderItemRequest $request, int $id) { $data = $request->validated(); $orderitem = OrderItem::find($id); if (!is_object($orderitem)) { return response()->json([ "code" => 404, "message" => "No record associated with id '{$id}' found" ], 404); } try { $orderitem->update($data); if ($request->hasFile("logo")) { try { $uploader = new \App\Services\Uploader("logo", "orders"); $file = $uploader->upload(); \App\Models\Image::create([ "object_type" => get_class($orderitem), "object_id" => $orderitem->id, "name" => "logo", "image" => $file ]); } catch (\Exception $ex) { return response()->json([ "code" => 500, "message" => $ex->getMessage() ], 500); } } return response()->json([ "code" => 200, "message" => "Order Item Updated Successfully!" ], 200); } catch (\Exception $ex) { return response()->json([ "code" => 500, "message" => $ex->getMessage() ], 500); } } /** * Delete record * @param integer $id * @return \Illuminate\Http\Resources\Json\JsonResource; */ /*** * operation_name: delete * operation_label: Delete */ function destroy(int $id) { $orderitem = OrderItem::find($id); if (!is_object($orderitem)) { return response()->json([ "code" => 404, "message" => "No record associated with id '{$id}' found" ], 404); } try { $orderitem->delete(); return response()->json([ "code" => 200, "message" => "Orderitem Deleted Successfully!" ], 200); } catch (\Exception $ex) { return response()->json([ "code" => 500, "message" => $ex->getMessage() ], 500); } } }
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(16316); script_version("1.22"); script_set_attribute(attribute:"plugin_modification_date", value:"2022/06/01"); script_cve_id("CVE-2004-1825"); script_bugtraq_id(9890); script_name(english:"Mambo Site Server mos_change_template XSS"); script_set_attribute(attribute:"synopsis", value: "The remote web server contains a PHP script that is prone to cross- site scripting attacks."); script_set_attribute(attribute:"description", value: "An attacker may use the installed version of Mambo Site Server to perform a cross-site scripting attack on this host because of its failure to sanitize input to the 'return' and 'mos_change_template' parameters of the 'index.php' script."); script_set_attribute(attribute:"see_also", value:"http://www.gulftech.org/?node=research&article_id=00032-03152004"); script_set_attribute(attribute:"see_also", value:"https://seclists.org/bugtraq/2004/Mar/147"); script_set_attribute(attribute:"solution", value: "Upgrade at least to version 4.5 (1.0.4)."); script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:N/I:P/A:N"); script_set_cvss_temporal_vector("CVSS2#E:H/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"No exploit is required"); script_set_attribute(attribute:"exploit_available", value:"false"); script_cwe_id(20, 74, 79, 442, 629, 711, 712, 722, 725, 750, 751, 800, 801, 809, 811, 864, 900, 928, 931, 990); script_set_attribute(attribute:"vuln_publication_date", value:"2004/03/16"); script_set_attribute(attribute:"plugin_publication_date", value:"2005/02/07"); script_set_attribute(attribute:"plugin_type", value:"remote"); script_set_attribute(attribute:"thorough_tests", value:"true"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_family(english:"CGI abuses : XSS"); script_copyright(english:"This script is Copyright (C) 2005-2022 Tenable Network Security, Inc."); script_dependencies("mambo_detect.nasl", "cross_site_scripting.nasl"); script_require_keys("www/mambo_mos"); script_exclude_keys("Settings/disable_cgi_scanning"); script_require_ports("Services/www", 80); exit(0); } include("global_settings.inc"); include("http_func.inc"); include("http_keepalive.inc"); port = get_http_port(default:80, embedded:TRUE); if(!get_port_state(port))exit(0); if(get_kb_item(string("www/", port, "/generic_xss"))) exit(0); if(!can_host_php(port:port)) exit(0); # Test an install. install = get_kb_item(string("www/", port, "/mambo_mos")); if (isnull(install)) exit(0); matches = eregmatch(string:install, pattern:"^(.+) under (/.*)$"); if (!isnull(matches)) { dir = matches[2]; url = string(dir, "/index.php?mos_change_template=<script>foo</script>"); req = http_get(item:url, port:port); buf = http_keepalive_send_recv(port:port, data:req, bodyonly:1); if( buf == NULL ) exit(0); if ( '<form action="/index.php?mos_change_template=<script>foo</script>' >< buf ) { security_warning(port); set_kb_item(name: 'www/'+port+'/XSS', value: TRUE); } }
import * as React from "react"; import Link from "next/link"; import { useRouter } from "next/router"; import Chip from "@mui/material/Chip"; import { DataGrid } from "@mui/x-data-grid"; import Button from "@mui/material/Button"; import { CircularProgress } from "@mui/material"; import Title from "./Title"; import ErrorBox from "./ErrorBox"; import { italianShortDate } from "../lib/dateUtils"; import { useInvoices, usePatients } from "../lib/hooks"; export default function LastInvoices() { const router = useRouter(); const { invoices, isLoading: isLoadingInvoices, error: invoicesError, } = useInvoices(); const { patients, isLoading: isLoadingPatients, error: patientsError, } = usePatients(); if (patientsError) return ( <ErrorBox title="Errore nel caricamento del paziente" text={patientsError} /> ); if (invoicesError) return ( <ErrorBox title="Errore nel caricamento delle fatture" text={invoicesError} /> ); if ( invoices === undefined || patients === undefined || isLoadingPatients || isLoadingInvoices ) return ( <> <Title>Ultime fatture</Title> <CircularProgress sx={{ mx: "auto", my: 10 }} /> </> ); const now = new Date(); const oneYearAgo = new Date(); oneYearAgo.setFullYear(now.getFullYear() - 1); const lastInvoices = invoices .filter((i) => Date.parse(i.dataEmissione) > Date.parse(oneYearAgo)) .sort((i1, i2) => Date.parse(i1.dataEmissione) > Date.parse(i2.dataEmissione) ? -1 : 1 ); const fatturatoUltimoAnno = {}; patients.forEach((p) => { fatturatoUltimoAnno[p._id] = 0; }); lastInvoices.forEach((i) => { fatturatoUltimoAnno[i.paziente] += Number.parseFloat(i.valore); }); const rows = patients.slice(0, 21).map((p, i) => { let lastInvoiceFound = undefined; lastInvoices.forEach((i) => { if (i.paziente === p._id) { if (!lastInvoiceFound) lastInvoiceFound = Number.parseFloat(i.valore); } }); return { id: i, value: `${lastInvoiceFound || 0}€ (${fatturatoUltimoAnno[p._id]}€)`, p, name: `${p.cognome.toUpperCase()} ${p.nome}`, }; }); const columns = [ { field: "name", headerName: "Paziente", renderCell: (params) => ( <Link href={`/patients/${params.row.p._id}`} passHref> <Button variant="text" size="small"> {`${params.row.p.cognome} ${params.row.p.nome}`} </Button> </Link> ), flex: 1, }, { field: "date", headerName: "Data", flex: 1, renderCell: (params) => italianShortDate(new Date(params.row.p.ultimaModifica)), sortComparator: (a, b) => (Date.parse(a) > Date.parse(b) ? -1 : 1), }, { field: "email", headerName: "email", flex: 1.5, sortable: false, renderCell: (params) => params.row.p.email && ( <Chip component="a" variant="filled" label={`${params.row.p.email}`} href={`mailto:${params.row.p.email}`} clickable onClick={(ev) => { ev.stopPropagation(); }} /> ), }, { field: "value", headerName: "Valore (ultimi 12 mesi)", flex: 1, sortComparator: (a, b) => Number.parseFloat(a.substring(a.indexOf("(") + 1, a.indexOf("€)"))) - Number.parseFloat(b.substring(b.indexOf("(") + 1, b.indexOf("€)"))), }, ]; return ( <> <Title>Ultime fatture</Title> <DataGrid rows={rows} columns={columns} autoHeight={true} density="compact" disableExtendRowFullWidth={false} disableSelectionOnClick={true} hideFooter={true} onRowClick={(params) => { router.push(`/patients/${params.row.p._id}`); }} /> </> ); }
<!DOCTYPE html> <html ng-app="myApp"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Examples</title> <script src="js/angular.js"></script> <style> input.ng-valid{border:1px solid green;} input.ng-invalid{border:1px solid red;} </style> <script> var m1 = angular.module('myApp',[]); m1.controller('A',['$scope',function($scope){ $scope.text = 'hello'; }]); </script> </head> <body> <div ng-controller = 'A'> <form name="myForm"> <input type="text" ng-model = "text" name="myText" required ng-minlength= "5" ng-pattern='/^[a-zA-z]+$/'> <p>{{ myForm.myText.$valid }}</p> <p>{{ myForm.myText.$invalid }}</p> <p>{{ myForm.myText.$pristine }}</p> <p>{{ myForm.myText.$dirty }}</p> <p>{{ myForm.myText.$error }}</p> </form> </div> </body> </html>
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from openSUSE Security Update openSUSE-2019-1808. # # The text description of this plugin is (C) SUSE LLC. # include('compat.inc'); if (description) { script_id(127088); script_version("1.4"); script_set_attribute(attribute:"plugin_modification_date", value:"2022/12/06"); script_cve_id("CVE-2019-0199", "CVE-2019-0221"); script_xref(name:"CEA-ID", value:"CEA-2021-0025"); script_name(english:"openSUSE Security Update : tomcat (openSUSE-2019-1808)"); script_set_attribute(attribute:"synopsis", value: "The remote openSUSE host is missing a security update."); script_set_attribute(attribute:"description", value: "This update for tomcat to version 9.0.21 fixes the following issues : Security issues fixed : - CVE-2019-0199: Fixed a denial of service in the HTTP/2 implementation related to streams with excessive numbers of SETTINGS frames (bsc#1131055). - CVE-2019-0221: Fixed a cross site scripting vulnerability with the SSI printenv command (bsc#1136085). Non-security issues fixed : - Increase maximum number of threads and open files for tomcat (bsc#1111966). This update was imported from the SUSE:SLE-15-SP1:Update update project."); script_set_attribute(attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1111966"); script_set_attribute(attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1131055"); script_set_attribute(attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1136085"); script_set_attribute(attribute:"solution", value: "Update the affected tomcat packages."); script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:N/I:P/A:N"); script_set_cvss_temporal_vector("CVSS2#E:POC/RL:OF/RC:C"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"); script_set_cvss3_temporal_vector("CVSS:3.0/E:P/RL:O/RC:C"); script_set_attribute(attribute:"cvss_score_source", value:"CVE-2019-0221"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"vuln_publication_date", value:"2019/04/10"); script_set_attribute(attribute:"patch_publication_date", value:"2019/07/25"); script_set_attribute(attribute:"plugin_publication_date", value:"2019/07/26"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-admin-webapps"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-docs-webapp"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-el-3_0-api"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-embed"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-javadoc"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-jsp-2_3-api"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-jsvc"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-lib"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-servlet-4_0-api"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:tomcat-webapps"); script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:opensuse:15.1"); script_set_attribute(attribute:"generated_plugin", value:"current"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_family(english:"SuSE Local Security Checks"); script_copyright(english:"This script is Copyright (C) 2019-2022 and is owned by Tenable, Inc. or an Affiliate thereof."); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/SuSE/release", "Host/SuSE/rpm-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); release = get_kb_item("Host/SuSE/release"); if (isnull(release) || release =~ "^(SLED|SLES)") audit(AUDIT_OS_NOT, "openSUSE"); if (release !~ "^(SUSE15\.1)$") audit(AUDIT_OS_RELEASE_NOT, "openSUSE", "15.1", release); if (!get_kb_item("Host/SuSE/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); flag = 0; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-admin-webapps-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-docs-webapp-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-el-3_0-api-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-embed-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-javadoc-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-jsp-2_3-api-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-jsvc-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-lib-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-servlet-4_0-api-9.0.21-lp151.3.3.1") ) flag++; if ( rpm_check(release:"SUSE15.1", reference:"tomcat-webapps-9.0.21-lp151.3.3.1") ) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:rpm_report_get()); else security_warning(0); exit(0); } else { tested = pkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "tomcat / tomcat-admin-webapps / tomcat-docs-webapp / etc"); }
package app import ( "context" "github.com/materials-resources/s-prophet/pkg/models" "github.com/rs/zerolog" "net" "sync" "github.com/uptrace/bun" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/sdk/metric" tracesdk "go.opentelemetry.io/otel/sdk/trace" "google.golang.org/grpc" ) type App struct { Config *Config server *grpc.Server serverOnce sync.Once tp *tracesdk.TracerProvider mp *metric.MeterProvider bunOnce sync.Once bun *bun.DB log *zerolog.Logger } func NewApp(config *Config) (*App, error) { a := &App{ Config: config, } a.tp = a.newTracer() a.newLogger() otel.SetTracerProvider(a.tp) return a, nil } func (a *App) Start() { ctx := context.Background() if err := onStart.Run(ctx, a); err != nil { a.Logger().Fatal().Err(err).Msg("failed to run onStart hooks") } lis, err := net.Listen( "tcp", "0.0.0.0:50058", ) if err != nil { a.Logger().Fatal().Err(err).Msg("failed to create listener") } err = a.GetGrpcServer().Serve(lis) if err != nil { a.Logger().Fatal().Err(err).Msg("failed to start server") } } // Stop stops the application. func (a *App) Stop() { a.GetGrpcServer().Stop() } func (a *App) GetGrpcServer() *grpc.Server { a.serverOnce.Do( func() { a.server = a.newGrpcServer() }, ) return a.server } // GetDB returns an initialized instance of bun.DB. func (a *App) GetDB() *bun.DB { a.bunOnce.Do( func() { a.newBun() }) return a.bun } // GetTP returns initialized instance of tracesdk.TracerProvider. func (a *App) GetTP() *tracesdk.TracerProvider { return a.tp } // GetModels returns an initialized instance of data.Models. func (a *App) GetModels() models.Models { return *models.NewModels(a.GetDB()) } func (a *App) GetMP() *metric.MeterProvider { return a.mp }
<h4 class="text-center">Sign up</h4> <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= render "devise/shared/error_messages", resource: resource %> <div class="input-group my-3"> <div class="input-group-prepend"> <%= f.label :first_name, '<i class="fa fa-user-circle"></i>'.html_safe, class: "input-group-text justify-content-center" %> </div> <%= f.text_field :first_name, autofocus: true, class: "form-control", placeholder: "First Name" %> </div> <div class="input-group my-3"> <div class="input-group-prepend"> <%= f.label :last_name, '<i class="fa fa-users"></i>'.html_safe, class: "input-group-text justify-content-center" %> </div> <%= f.text_field :last_name, class: "form-control", placeholder: "Last Name" %> </div> <div class="input-group my-3"> <div class="input-group-prepend"> <%= f.label :email, '<i class="fa fa-envelope"></i>'.html_safe, class: "input-group-text justify-content-center" %> </div> <%= f.email_field :email, autocomplete: "email", class: "form-control", placeholder: "Email" %> </div> <div class="input-group my-3"> <div class="input-group-prepend"> <%= f.label :password, '<i class="fa fa-lock"></i>'.html_safe, class: "input-group-text justify-content-center" %> </div> <%= f.password_field :password, autocomplete: "new-password", class: "form-control", placeholder: "Password" %> </div> <div class="input-group mt-3 mb-2"> <div class="input-group-prepend"> <%= f.label :password_confirmation, '<i class="fa fa-lock"></i>'.html_safe, class: "input-group-text justify-content-center" %> </div> <%= f.password_field :password_confirmation, autocomplete: "new-password", class: "form-control", placeholder: "Password confirmation" %> </div> <div> <% if @minimum_password_length %> <span class="text-secondary small">*<%= @minimum_password_length %> characters minimum</span> <% end %> </div> <div class="form-row"> <div class="col"> <div class="float-right d-flex align-items-center"> <%= render "devise/shared/links" %> <%= f.submit "Sign up", class: "btn btn-primary"%> </div> </div> <% end %> <% =begin%> <%= render "devise/shared/links" %> <% =end%>
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Gentoo Linux Security Advisory GLSA 201512-11. # # The advisory text is Copyright (C) 2001-2016 Gentoo Foundation, Inc. # and licensed under the Creative Commons - Attribution / Share Alike # license. See http://creativecommons.org/licenses/by-sa/3.0/ # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(87711); script_version("2.3"); script_set_attribute(attribute:"plugin_modification_date", value:"2021/01/11"); script_cve_id("CVE-2013-2492"); script_xref(name:"GLSA", value:"201512-11"); script_name(english:"GLSA-201512-11 : Firebird: Buffer Overflow"); script_summary(english:"Checks for updated package(s) in /var/db/pkg"); script_set_attribute( attribute:"synopsis", value: "The remote Gentoo host is missing one or more security-related patches." ); script_set_attribute( attribute:"description", value: "The remote host is affected by the vulnerability described in GLSA-201512-11 (Firebird: Buffer Overflow) The vulnerability is caused due to an error when processing requests from remote clients. Impact : A remote attacker could possibly execute arbitrary code with the privileges of the process, or cause a Denial of Service condition. Workaround : There is no known workaround at this time." ); script_set_attribute( attribute:"see_also", value:"https://security.gentoo.org/glsa/201512-11" ); script_set_attribute( attribute:"solution", value: "All Firebird users should upgrade to the latest version: # emerge --sync # emerge --ask --oneshot --verbose '>=dev-db/firebird-2.5.3.26780.0-r3' NOTE: Firebird package was moved to the testing branch (unstable) of Gentoo. There is currently no stable version of Firebird, and there will be no further GLSAs for this package." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:P/I:P/A:P"); script_set_cvss_temporal_vector("CVSS2#E:F/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"exploit_framework_core", value:"true"); script_set_attribute(attribute:"metasploit_name", value:'Firebird Relational Database CNCT Group Number Buffer Overflow'); script_set_attribute(attribute:"exploit_framework_metasploit", value:"true"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:gentoo:linux:firebird"); script_set_attribute(attribute:"cpe", value:"cpe:/o:gentoo:linux"); script_set_attribute(attribute:"patch_publication_date", value:"2015/12/30"); script_set_attribute(attribute:"plugin_publication_date", value:"2016/01/04"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2016-2021 and is owned by Tenable, Inc. or an Affiliate thereof."); script_family(english:"Gentoo Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/Gentoo/release", "Host/Gentoo/qpkg-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("qpkg.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/Gentoo/release")) audit(AUDIT_OS_NOT, "Gentoo"); if (!get_kb_item("Host/Gentoo/qpkg-list")) audit(AUDIT_PACKAGE_LIST_MISSING); flag = 0; if (qpkg_check(package:"dev-db/firebird", unaffected:make_list("ge 2.5.3.26780.0-r3"), vulnerable:make_list("lt 2.5.3.26780.0-r3"))) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:qpkg_report_get()); else security_warning(0); exit(0); } else { tested = qpkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "Firebird"); }
<ion-content> <div id="survey"> <div class="searchBarDiv"> <ion-searchbar id="open-modal" class="search" (ionChange)="search($event)" placeholder="Nach Emissionswerte suchen"></ion-searchbar> </div> <div id="surveyList"> <ng-container *ngFor="let survey of setSurveys"> <div [class.categoryActive]="survey.category" *ngIf="survey.activated == 1"> <div class="left"><ion-icon name="{{survey.iconName}}"></ion-icon> <p>{{survey.title}}</p><p *ngIf="survey.category.activated == 0" class="deactivatedInCategory">(Kategorie deaktiviert)</p> </div> <div class="right"> <div (click)="editModal(survey)"><ion-icon name="create-outline"></ion-icon></div> <div class="ban" (click)="deactivate(survey)"> <ion-icon name="ban-outline"></ion-icon> </div> <div class="bin" (click)="deleteSurvey(survey)"><ion-icon name="trash-outline"></ion-icon></div> </div> </div> </ng-container> </div> <div id="deactivated" (click)="changeCollapsed()"> <ion-icon *ngIf="collapsed" name="chevron-forward-outline"></ion-icon><ion-icon *ngIf="!collapsed" name="chevron-down-outline"></ion-icon> <p class="deactivatedText">Deaktiviert</p> </div> <div *ngIf="!collapsed" id="deactivatedList"> <ng-container *ngFor="let survey of setSurveys"> <div *ngIf="survey.activated == 0" [class.categoryActive]="survey.category"> <div class="left"><ion-icon name="{{survey.iconName}}"></ion-icon> <p>{{survey.title}}</p><p *ngIf="survey.category" class="deactivatedInCategory">(Kategorie deaktiviert)</p> </div> <div class="right" [class.categoryActive]="survey.category"> <div (click)="editModal(survey)"><ion-icon name="create-outline"></ion-icon></div> <div class="unban" (click)="activate(survey)"> <ion-icon name="checkmark-outline"></ion-icon> </div> <div class="bin" (click)="deleteSurvey(survey)"><ion-icon name="trash-outline"></ion-icon></div> </div> </div> </ng-container> </div> </div> <ion-modal #modal> <ng-template> <div class="positioning"> <form [formGroup]="surveyForm" class="editForm"> <ion-item> <ion-label position="floating">Title</ion-label> <ion-input type="text" formControlName="surveyTitle"></ion-input> </ion-item> <ion-item (click)="modal2.present()"> <div class="iconSelection"> <ion-input type="text" *ngIf="selectedIcon == ''" readonly value="Icon auswählen"></ion-input> <ion-icon *ngIf="selectedIcon != ''" [name]="selectedIcon"></ion-icon> <ion-icon class="linkTo" name="open-outline"></ion-icon> </div> </ion-item> <ion-item> <ion-label position="floating">Typ</ion-label> <ion-select formControlName="surveyType"> <ion-label position="floating">Typ</ion-label> <ion-select-option *ngFor="let type of types" [value]="type.value">{{type.key}}</ion-select-option> </ion-select> </ion-item> <ion-item *ngIf="surveyForm.get('surveyType')?.value == 'e'"> <ion-label position="floating">Maß</ion-label> <ion-select formControlName="surveyMeasurements"> <ion-label position="floating">Maß</ion-label> <ion-select-option *ngFor="let measurement of measurements" [value]="measurement.name">{{measurement.fullName}}</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label position="floating">Standardwert</ion-label> <ion-input type="number" formControlName="surveyStandard"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Kategorie</ion-label> <ion-select formControlName="surveyCat"> <ion-label position="floating">Kategorie</ion-label> <ion-select-option *ngFor="let category of categories" [value]="category.id">{{category.title}}</ion-select-option> </ion-select> </ion-item> <div id="subBtnDiv"> <input *ngIf="edit" class="subBtn" value="Speichern" type="button" (click)="updateSurvey()"> <input *ngIf="!edit" class="subBtn" value="Erstellen" type="button" (click)="createSurvey()"> <p (click)="modal.dismiss()">Abbrechen</p> </div> </form> </div> </ng-template> </ion-modal> <ion-modal #modal2> <ng-template> <app-search-icon class="ion-page" title="Icons" [selectedIcon]="selectedIcon" (selectionChange)="iconSelectionChange($event)" (selectionCancel)="modal2.dismiss()"></app-search-icon> </ng-template> </ion-modal> <div id="addBtn" (click)="createModal()"> <ion-icon name="add-outline"></ion-icon> </div> </ion-content>
<!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Portfólio</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Nunito&family=Press+Start+2P&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./reset.css"> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="menu"> <img class="menu_logo" src="codificacao.png" alt="Logo de duas chaves {}"> <ul class="menu_lista"> <li> <a class="menu_lista_item" href="#home">Home</a> </li> <li> <a class="menu_lista_item" href="#sobre">Sobre</a> </li> <li> <a class="menu_lista_item" href="#cursos">Cursos</a> </li> <li> <a class="menu_lista_item" href="#projetos">Projetos</a> </li> </ul> <a class="menu_curriculo" href="">Currículo</a> </header> <main id="#home" class="home"> <div class="home_infos"> <img class="home_img" src="estude.png" alt="Minha foto"> <h1 class="home_nome">acamDeveloper</h1> <p class="home_area">Desenvolvedor Front-End</p> </div> </main> <section class="sobre" id="sobre"> <div class="sobre_infos"> <h2 class="sobre_titulo">Sobre</h2> <p class="sobre_texto"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa eveniet molestiae maxime, cupiditate perferendis ipsum sed nam quas accusantium iure, sequi magni, ducimus unde nulla odio ipsam aperiam quos nostrum? </p> <p class="sobre_texto"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sequi pariatur fuga voluptate at, voluptas aspernatur eligendi. Laudantium debitis adipisci ea quis, consequuntur enim et, at error nulla magnam rem numquam. </p> </div> <img class="sobre_imagem" src="reactimg.png" alt="logo img"> </section> <section class="cursos"> <h2 class="cursos_titulo">Cursos</h2> <div class="cursos_lista"> <div class="curso"> <div class="divdiv"> <div class="div"></div> <h3 class="curso_titulo">Infinity School</h3> </div> <h4 class="curso_subtitulo">Programação FullStack</h4> <p class="curso_texto">Lorem ipsum dolor sit amet consectetur adipisicing elit. Consectetur debitis veritatis ut vero nemo perferendis sequi perspiciatis necessitatibus aut, consequuntur earum, non impedit consequatur possimus quisquam neque magnam soluta ratione.</p> <p class="curso_duracao">1 ano</p> </div> <div class="curso"> <div class="divdiv"> <div class="div"></div> <h3 class="curso_titulo">Infinity School</h3> </div> <h4 class="curso_subtitulo">Data Science</h4> <p class="curso_texto">Lorem ipsum dolor sit amet consectetur adipisicing elit. Consectetur debitis veritatis ut vero nemo perferendis sequi perspiciatis necessitatibus aut, consequuntur earum, non impedit consequatur possimus quisquam neque magnam soluta ratione.</p> <p class="curso_duracao">8 meses</p> </div> </div> </section> </body> </html>
#include "main.h" /** * get_bit - return the value of a bit at a given * index * @n: unsigned long int input * @index: index of the bit * Return: value of the bit */ int get_bit(unsigned long int n, unsigned int index) { unsigned int i; if (index >= 64) return (-1); return (((n >> index) & 1) ? 1 : 0); }
import React from 'react' import Drawer from '@mui/material/Drawer' import IconButton from '@mui/material/IconButton' import InboxIcon from '@mui/icons-material/MoveToInbox' import List from '@mui/material/List' import ListItem from '@mui/material/ListItem' import ListItemButton from '@mui/material/ListItemButton' import ListItemIcon from '@mui/material/ListItemIcon' import ListItemText from '@mui/material/ListItemText' import MailIcon from '@mui/icons-material/Mail' import MenuIcon from '@mui/icons-material/Menu' import { Link } from 'react-router-dom' const drawerWidth = 240 function ToggleSideBar (props) { const { window } = props const [mobileOpen, setMobileOpen] = React.useState(false) const handleDrawerToggle = () => { setMobileOpen(!mobileOpen) } const routeItems = [ { path: 'inicio' }, { path: 'incomes', showName: 'Ingresos' }, { path: 'expenditures', showName: 'gastos' }, { path: 'budget', showName: 'presupuesto' } ] const drawer = ( <div> <List> {routeItems.map((routeItem, index) => { const { path, showName } = routeItem return ( <Link to={path} key={index}> <ListItem disablePadding> <ListItemButton> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={showName ?? path} className='capitalize' /> </ListItemButton> </ListItem> </Link> ) })} </List> </div> ) const container = window !== undefined ? () => window().document.body : undefined return ( <> <IconButton color='inherit' aria-label='open drawer' edge='start' onClick={handleDrawerToggle} sx={{ mr: 2, display: { sm: 'none' } }} > <MenuIcon /> </IconButton> <Drawer container={container} variant='temporary' open={mobileOpen} onClose={handleDrawerToggle} ModalProps={{ keepMounted: true // Better open performance on mobile. }} sx={{ display: { xs: 'block', sm: 'none' }, '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth } }} > {drawer} </Drawer> </> ) } export default ToggleSideBar
import numpy as np import pandas as pd from statsmodels.tsa.vector_ar.var_model import VAR import matplotlib.pyplot as plt # Set a random seed for reproducibility np.random.seed(42) # Generate non-stationary data: random walks n_obs = 100 variable1 = np.random.normal(loc=0, scale=1, size=n_obs).cumsum() variable2 = np.random.normal(loc=0, scale=1, size=n_obs).cumsum() # Combine into a DataFrame df = pd.DataFrame({ 'Variable1': variable1, 'Variable2': variable2 }) # Plot the data to visualize non-stationarity plt.figure(figsize=(10, 5)) plt.plot(df['Variable1'], label='Variable 1') plt.plot(df['Variable2'], label='Variable 2') plt.title('Non-stationary Data Generated as Random Walks') plt.legend() plt.show() # Fit a VAR model model = VAR(df) results = model.fit(maxlags=1) # Output the results print(results.summary()) # Check for stationarity of the residuals residuals = results.resid fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(residuals) ax.set_title('Residuals from VAR Model') plt.show()
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(63201); script_version("1.9"); script_set_attribute(attribute:"plugin_modification_date", value:"2022/04/11"); script_name(english:"RWCards Component for Joomla! 'mosConfig_absolute_path' Parameter Remote File Include"); script_set_attribute(attribute:"synopsis", value: "The remote web server contains a PHP application that is affected by a remote file include vulnerability."); script_set_attribute(attribute:"description", value: "The version of the RWCards component for Joomla! running on the remote host is affected by a remote file include vulnerability due to improper sanitization of user-supplied input to the 'mosConfig_absolute_path' parameter before using it in the rwcards.advancedate.php script to include PHP code. An unauthenticated, remote attacker can exploit this issue to disclose arbitrary files or execute arbitrary PHP code on the remote host, subject to the privileges of the web server user ID."); # https://packetstormsecurity.com/files/view/94688/joomlarwcards-rfi.txt script_set_attribute(attribute:"see_also", value:"http://www.nessus.org/u?0edbe927"); script_set_attribute(attribute:"see_also", value:"https://www.weberr.de/"); script_set_attribute(attribute:"solution", value: "Unknown at this time."); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:P/I:P/A:P"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"); script_set_attribute(attribute:"exploited_by_nessus", value:"true"); script_set_attribute(attribute:"vuln_publication_date", value:"2010/10/12"); script_set_attribute(attribute:"plugin_publication_date", value:"2012/12/10"); script_set_attribute(attribute:"plugin_type", value:"remote"); script_set_attribute(attribute:"cpe", value:"cpe:/a:joomla:joomla\!"); script_set_attribute(attribute:"cpe", value:"cpe:/a:weberr:com_rwcards"); script_set_attribute(attribute:"thorough_tests", value:"true"); script_end_attributes(); script_category(ACT_ATTACK); script_family(english:"CGI abuses"); script_copyright(english:"This script is Copyright (C) 2012-2022 and is owned by Tenable, Inc. or an Affiliate thereof."); script_dependencies("joomla_detect.nasl"); script_require_keys("installed_sw/Joomla!", "www/PHP"); script_require_ports("Services/www", 80); exit(0); } include("audit.inc"); include("global_settings.inc"); include("misc_func.inc"); include("http.inc"); include("webapp_func.inc"); include("url_func.inc"); app = "Joomla!"; get_install_count(app_name:app, exit_if_zero:TRUE); port = get_http_port(default:80, php:TRUE); install = get_single_install( app_name : app, port : port ); dir = install['path']; install_url = build_url(port:port, qs:dir); # Verify component is installed plugin = "RWCards"; # Check KB first installed = get_kb_item("www/"+port+"/webapp_ext/"+plugin+" under "+dir); if (!installed) { checks = make_array(); regexes = make_list(); regexes[0] = make_list('.rwcardsfull', '.rwcards'); checks["/components/com_rwcards/css/rwcards.css"] = regexes; checks["/components/com_rwcards/css/rwcards.filloutform.css"] = regexes; # Ensure plugin is installed installed = check_webapp_ext( checks : checks, dir : dir, port : port, ext : plugin ); } if (!installed) audit(AUDIT_WEB_APP_EXT_NOT_INST, app, install_url, plugin + " component"); # Determine what to look for. os = get_kb_item("Host/OS"); if (os && report_paranoia < 2) { if ("Windows" >< os) files = make_list('windows/win.ini', 'winnt/win.ini'); else files = make_list('etc/passwd'); } else files = make_list('etc/passwd', 'windows/win.ini', 'winnt/win.ini'); file_pats = make_array(); file_pats['etc/passwd'] = "root:.*:0:[01]:"; file_pats['winnt/win.ini'] = "^\[[a-zA-Z]+\]|^; for 16-bit app support"; file_pats['windows/win.ini'] = "^\[[a-zA-Z]+\]|^; for 16-bit app support"; vuln = FALSE; error = FALSE; foreach file (files) { attack = mult_str(str:"../", nb:12) + file; url = "/components/com_rwcards/rwcards.advancedate.php?mosConfig_absolute_path=" + urlencode(str:attack) + '%00'; res = http_send_recv3( method : "GET", item : dir + url, port : port, exit_on_fail : TRUE ); if (egrep(pattern:file_pats[file], string:res[2])) { vuln = TRUE; contents = res[2]; break; } # we get an error because magic_quotes was enabled else if (file + "\0/includes/version.php" >< res[2]) { vuln = TRUE; error = TRUE; contents = strstr(res[2], file); break; } # we get an error claiming the file doesn't exist else if ( "main(" +file+ "): failed to open stream: No such file" >< res[2] || "include("+file+") [function.include]: failed to open stream: No such file" >< res[2] ) { vuln = TRUE; error = TRUE; contents = strstr(res[2], file); break; } # we get an error about open_basedir restriction. else if ("open_basedir restriction in effect. File(" + file >< res[2]) { vuln = TRUE; error = TRUE; contents = strstr(res[2], "open_basedir"); break; } } if (vuln) { if (error) { security_report_v4( port : port, severity : SECURITY_HOLE, generic : TRUE, request : make_list(install_url + url), output : contents, rep_extra : 'Note that Nessus was not able to directly exploit this issue;'+ '\nhowever, based on the error below, the install does appear to be'+ '\naffected.' ); exit(0); } security_report_v4( port : port, severity : SECURITY_HOLE, file : file, request : make_list(install_url + url), output : contents, attach_type : 'text/plain' ); exit(0); } else audit(AUDIT_WEB_APP_NOT_AFFECTED, app, install_url);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Formularze</h1> <hr> <br> <br> <br> <aside> <section> <head><b>Formuarz</b> <time datetime="12-31-2022"></time> 12-31-2022</head> <form action="" method="post"> <fieldset> <legend>Logowanie</legend> <p> <label for="">Wpisz imie <input type="text" name="name-wysyla-wartosc-na-serwer" id="username" placeholder="Wpisz nazwe usera" value="Imie usera"> </label> </p> <p> <label for="passwordId">Wpisz haslo koles</label> <input type="password" name="password" id="passwordId" placeholder="Wpisz haslo" required > </p> <p> <button type="submit">Zaloguj</button> <button type="reset">Wyczysc formularz</button> </p> </fieldset> </form> <hr> <h3>Rejestracja</h3> <form action="" method="post" enctype="multipart/form-data" > <fieldset> <legend>Rejestracja nowego usera</legend> <input type="hidden" name="hidden_value" id="hiddenId" value="ukryta wartosc przekazana do serwera"> <p> <label for="imieId">Wpisz imie</label> <input type="text" name="imieuser" id="imieID" placeholder="Twoje imie" value="Podaj imie" minlength="3" maxlength="10" required> </p> <p> <label for="passwordID2">Podaj haslo</label> <input type="password" name="password" id="passwordID2" required> </p> <p> <label for="confirmPass">Powtorz haslo</label> <input type="password" name="passwordConf" id="confirmPass" required> </p> <p> <label for="descId">Opis Usera</label><br> <textarea name="desc" id="descId" cols="30" rows="10"></textarea> </p> <p> <label for="avatarId">Wybierz avatar</label><br> <input type="file" name="avatar" id="avatarId" accept="image/jpg, image/png"> </p> <p> <b>Tylko jeden wybor</b><br> <input type="radio" name="color" id="redId" value="red"> <label for="redId">Czerwony</label> <input type="radio" name="color" id="greenId" value="green"> <label for="greenId">Green</label> <input type="radio" name="color" id="blueId" value="blue"> <label for="blueId">blue</label> </p> <p> <b>Wielokrotny wybor</b><br> <input type="checkbox" name="brand" id="redId" value="red"> <label for="redId">Czerwony</label> <input type="checkbox" name="brand" id="greenId" value="green"> <label for="greenId">Green</label> <input type="checkbox" name="brand" id="blueId" value="blue"> <label for="blueId">blue</label> </p> <p> <label for="dateId">Data</label> <input type="datetime-local" name="date" id="dateId"> </p> <p> <label for="colorId">Kolor</label> <input type="color" name="color" id="colorId"> </p> <p> <label for="telId">Nr tel</label> <input type="tel" name="tel" id="telId"> </p> <p> <label for="rangeId">Zasieg</label> <input type="range" name="range" id="rangeId" min="3" max="100" step="4"> </p> <p> <label for="urlId">Strona serwisu</label> <input type="url" name="url" id="urrlId"> </p> <label for="themeId">Template forum</label> <select name="theme" id="themeId"> <option value="white">bialy</option> <option value="black">black</option> </select> <p> <button type="submit">Rejestruj</button> <button type="reset">Czysc formularz</button> </p> </fieldset> </form> </section> </aside> </body> </html>
#include "include/wifi.h" /*Description: * Function that performs http GET request for given parameters * * @Input: * - [const char*] host: web host * - [const char*] path: web path * * @Output: * - [void] Prints response to terminal * */ void http_get(const char *host, const char *path) { int sockfd; struct sockaddr_in server_addr; struct hostent *server; // Create a socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("Error opening socket"); exit(EXIT_FAILURE); } // Get the server's IP address server = gethostbyname(host); if (server == NULL) { fprintf(stderr, "Error, no such host\n"); exit(EXIT_FAILURE); } // Initialize the server address structure bzero((char *)&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&server_addr.sin_addr.s_addr, server->h_length); server_addr.sin_port = htons(PORT); // Connect to the server if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("Error connecting to server"); exit(EXIT_FAILURE); } // Build the HTTP GET request char request[MAX_BUFFER_SIZE]; snprintf(request, sizeof(request), "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", path, host); // Send the request if (send(sockfd, request, strlen(request), 0) < 0) { perror("Error sending request"); exit(EXIT_FAILURE); } // Receive and print the response char response[MAX_BUFFER_SIZE]; ssize_t bytes_received; while ((bytes_received = recv(sockfd, response, sizeof(response) - 1, 0)) > 0) { response[bytes_received] = '\0'; printf("%s", response); } if (bytes_received < 0) { perror("Error receiving response"); exit(EXIT_FAILURE); } close(sockfd); } void http_put(const char *host, const char *path, const int port, const char *data, const char *authorization) { int sockfd; struct sockaddr_in server_addr; struct hostent *server; // Create a socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("Error opening socket"); exit(EXIT_FAILURE); } // Get the server's IP address // server = gethostbyname(host); // if (server == NULL) { // fprintf(stderr, "Error, no such host\n"); // exit(EXIT_FAILURE); // } // Initialize the server address structure bzero((char *)&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; // bcopy((char *)server->h_addr, (char *)&server_addr.sin_addr.s_addr, server->h_length); server_addr.sin_addr.s_addr = inet_addr(host); server_addr.sin_port = htons(port); // Connect to the server if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("Error connecting to server"); exit(EXIT_FAILURE); } // Build the HTTP PUT request with Authorization header char request[MAX_BUFFER_SIZE]; snprintf(request, sizeof(request), "PUT %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %zu\r\nContent-Type: application/json\r\nAuthorization: Bearer %s\r\n\r\n%s", path, host, strlen(data), authorization, data); printf("Request: %s\n", request); sleep(1); // Send the request if (send(sockfd, request, strlen(request), 0) < 0) { perror("Error sending request"); exit(EXIT_FAILURE); } // Receive and print the response char response[MAX_BUFFER_SIZE]; ssize_t bytes_received; while ((bytes_received = recv(sockfd, response, sizeof(response) - 1, 0)) > 0) { response[bytes_received] = '\0'; printf("%s", response); } if (bytes_received < 0) { perror("Error receiving response"); exit(EXIT_FAILURE); } close(sockfd); } /*Description: * Event handler for Wi-Fi events * * @Input: * - [void*] arg: ___ * - [esp_event_base_t] event_base: ___ * - [int32_t] event_id: id of the incoming event * - [void*] event_data: data of the incoming event * * @Output: * - [void] Only handles events * */ static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { ESP_LOGI(TAG, "Wifi started!"); esp_wifi_connect(); } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { if (s_retry_num < ESP_MAXIMUM_RETRY) { xEventGroupSetBits(s_wifi_event_group, WIFI_DISCONNECTED_BIT); wifi_connected = false; ESP_LOGI(TAG, "Reconnecting to wifi ..."); esp_wifi_connect(); s_retry_num++; } else { wifi_connected = false; xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); } } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); wifi_connected = true; ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data; ESP_LOGI(TAG, "Connected to ip: " IPSTR, IP2STR(&event->ip_info.ip)); } } /*Description: * Function to configure Wi-Fi module * * @Input: [void] * * @Output: [void] Configures Wi-Fi with set parameters * */ static void config_wifi() { s_wifi_event_group = xEventGroupCreate(); esp_netif_create_default_wifi_sta(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); esp_event_handler_instance_t instance_any_id; esp_event_handler_instance_t instance_got_ip; ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, &instance_any_id)); ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, &instance_got_ip)); } static void set_wifi_config(const char *ssid, const char *password) { wifi_sta_config_t wifi_config_sta = { .threshold.authmode = ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD, .sae_pwe_h2e = ESP_WIFI_SAE_MODE, .sae_h2e_identifier = EXAMPLE_H2E_IDENTIFIER, }; for (int i = 0; i < strlen(ssid); i++) { wifi_config_sta.ssid[i] = ssid[i]; } for (int i = 0; i < strlen(password); i++) { wifi_config_sta.password[i] = password[i]; } printf("SSID_len: %s\n", wifi_config_sta.ssid); printf("Password: %s\n", wifi_config_sta.password); wifi_config_t wifi_config = { .sta = wifi_config_sta }; ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config)); } /*Description: * Function to start Wi-Fi module * * @Input: [void] * * @Output: [void] Starts Wi-Fi * */ void start_wifi(void) { ESP_ERROR_CHECK(esp_wifi_start()); }
--- import { cn } from '@/lib/utils'; import type { SidebarNavItem } from '@/types'; import { Icon } from 'astro-icon/components'; type Props = { items: SidebarNavItem[]; }; const { items } = Astro.props; const { pathname } = Astro.url; --- { items.length ? ( <div class="w-full"> {items.map((item) => ( <div class={cn('pb-8')}> <h4 class="mb-1 flex w-full select-none flex-row items-center justify-between rounded-md px-2 py-1 text-[0.915rem] font-medium"> {item.title} <span class="opacity-0"> <Icon name="chevron-down" class="size-4" /> </span> </h4> {item.items?.length ? ( <div class="grid grid-flow-row auto-rows-max pl-0 text-sm"> {item.items.map((item) => !item.disabled && item.href ? ( <a href={item.href} data-path={pathname} class={cn('flex w-full items-center rounded-md p-2 hover:underline', { 'bg-muted': pathname === item.href, })} target={item.external ? '_blank' : ''} rel={item.external ? 'noreferrer' : ''} > {item.title} </a> ) : ( <span class="flex w-full cursor-not-allowed items-center rounded-md p-2 opacity-60"> {item.title} </span> ), )} </div> ) : null} </div> ))} </div> ) : null }
--- comments: false title: 九州大学 システム情報科学府 情報理工学専攻 2020年度 情報理論 tags: - Kyushu-University --- # 九州大学 システム情報科学府 情報理工学専攻 2020年度 情報理論 ## **Author** Yu ## **Description** ### 【問 1】 下図は, 定常 $2$ 重マルコフ情報源 $S$ の状態遷移図である. 下記の設問に答えよ. <figure style="text-align:center;"> <img src="https://raw.githubusercontent.com/Myyura/the_kai_project_assets/main/kakomonn/kyushu_university/ISEE/ist_2020_information_theory_p1.png" width="500" height="300" alt=""/> </figure> (1) 上図の状態遷移図を元に, このマルコフ情報源 $S$ の遷移確率行列 $A$ を求めよ. ただし, 状態 "$00$","$10$", "$01$" の順に, 行を記せ. (2) 時点 $0$ で状態 "00" にいたとして, 時点 $2$ で状態 "10" にいる確率はいくらか答えよ. (3) 上記のマルコフ情報源 $S$ の定常分布 $\vec{w} = (w_1,w_2,w_3)$ を求めよ. ただし, $w_i$ の添え字 $i = 1,2,3$ は状態 "$00$", "$10$", "$01$" にそれぞれ対応するものとする. (4) 定常 $2$ 重マルコフ情報源 $X_1,X_2,\dots$ のエントロピーレート $\lim_{n \rightarrow \infty} \frac{1}{n}H(X_1,X_2,\dots,X_n)$ が $H(X_3|X_1,X_2)$ に一致することを示せ. ただし, $H(X_3|X_1,X_2)$ は条件付きエントロピーである. (5) 上記のマルコフ情報源 $S$ に対するエントロピーレート $H(S)$ を求めよ. ### 【問 2】 $X,Y$ を $\{0,1\}$ に値をとる確率変数とする. パラメータ $\alpha,\beta,\gamma \in [0,1]$ に対し, $$ \begin{aligned} P(X = 0) = \alpha &,\quad P(X = 1) = 1 - \alpha,\\ P(Y = 0|X = 0) = \beta &,\quad P(Y = 1|X = 0) = 1 - \beta,\\ P(Y = 0|X = 1) = \gamma &,\quad P(Y = 1|X = 1) = 1 - \gamma, \end{aligned} $$ とする. $2$ 値エントロピー関数を $$ h(p) = \left \{ \begin{aligned} -p\log p - (1 - p)\log(1 - p) , \quad &\text{for} \quad 0 < p < 1, \\ 0,\qquad \qquad \qquad \qquad \qquad \qquad &\text{for} \quad p = 0,1 \end{aligned} \right. $$ とする. 以下の問いに答えよ. (1) 条件付きエントロピー $H(Y|X)$ を $2$ 値エントロピー関数を用いて表現せよ. (2) $\beta = 1 - \gamma$ とする. このとき, 相互情報量 $I(X;Y)$を最大化する$\alpha$ を求めよ. また $I(X;Y)$ の最大値を $2$ 値エントロピー関数と $\alpha,\beta$ を用いて表現せよ. (3) $\alpha,\beta$ をある値に固定する. ただし, $0 < \alpha < 1$ とする. 相互情報量 $I(X;Y)$ を最小化する $\gamma$ の値を $\alpha,\beta$ を用いて表せ. また, その最小値を示せ. (4) $\alpha,\beta$ をある値に固定する. ただし, $0 < \alpha < 1 ,\beta > \frac{1}{2}$ とする. 相互情報量 $I(X;Y)$ を最大化する $\gamma$ の値を求めよ. ## **Kai** ### 【問 1】 #### (1) $$ \begin{bmatrix} \frac{3}{4} & 0 & \frac{1}{4} \\ \frac{1}{2} & 0 & \frac{1}{2} \\ 0 & 1 & 0 \end{bmatrix} $$ #### (2) $$ A^2 = \begin{bmatrix} \frac{9}{16} & \frac{1}{4} & \frac{3}{16} \\ \frac{3}{8} & \frac{1}{2} & \frac{1}{8} \\ \frac{1}{2} & 0 & \frac{1}{2} \end{bmatrix} \Rightarrow P = \frac{1}{4} $$ #### (3) $$ \left\{ \begin{aligned} &w_1 + w_2 + w_3 = 1 \\ &\vec{w}A = \vec{w} \end{aligned} \right. \Rightarrow \vec{w} = (\frac{1}{2},\frac{1}{4},\frac{1}{4}) $$ #### (4) $$ \begin{aligned} \lim_{n \rightarrow \infty} \frac{1}{n}H(X _1,X_2,\dots,X_n) &= \lim_{n \rightarrow \infty} \frac{1}{n}[H(X_1) + H(X_2|X_1) + H(X_3|X_1,X_2) + \cdots + H(X_n|X_1,\dots,X_{n-1})] \\ &= \lim_{n \rightarrow \infty} \frac{1}{n}[H(X_1) + H(X_2|X_1) + H(X_3|X_1,X_2) + \cdots + H(X_n|X_{n-2},X_{n-1})] \\ &= \lim_{n \rightarrow \infty}\frac{1}{n}[H(X_3|X_1,X_2) + \cdots + H(X_n|X_{n-2},X_{n-1})] \\ &= \lim_{n \rightarrow \infty}\frac{n-2}{n}H(X_3|X_1,X_2)\\ &= H(X_3|X_1,X_2) \end{aligned} $$ #### (5) $$ H(S) = w_1\mathcal{H}(\frac{1}{4}) + w_2\mathcal{H}(\frac{1}{2}) + w_3\mathcal{H}(1) = \frac{5}{4} - \frac{3}{8}\log_2 3 $$ ### 【問 2】 #### (1) $$ H(Y|X) = \alpha h(\beta) + (1 - \alpha)h(\gamma) $$ #### (2) $$ \alpha = \frac{1}{2} $$ $$ \max_{\alpha}I(X;Y) = 1 - h(\beta) $$ #### (3) $$ \gamma = \beta $$ $$ \min_{\gamma}I(X;Y) = 0 $$ #### (4) $$ \begin{aligned} I(X;Y) &= H(Y) - H(Y|X) = h(\alpha\beta + (1 - \alpha)\gamma) - \alpha h(\beta) - (1 - \alpha)h(\gamma) \\ f(\gamma) &= h(\alpha\beta + (1 - \alpha)\gamma) - (1 - \alpha)h(\gamma)\text{の最大値問題を解くことになる} \end{aligned} $$ $$ \gamma = 0 $$
#include <stdlib.h> #include "Lista.h" typedef struct lista { int total; Aluno valores[MAX]; } Lista; Lista *criar() { Lista *l = (Lista *)malloc(sizeof(Lista)); if (l != NULL) l->total = 0; return l; } void limpar(Lista *l) { if (l != NULL) l->total = 0; } int inserirInicio(Lista *l, Aluno it) { int i; if (l == NULL) return 2; if (listaCheia(l) == 0) return 1; for (i = l->total; i > 0; i--) { l->valores[i] = l->valores[i - 1]; } l->valores[0] = it; l->total++; return 0; } int inserirFim(Lista *l, Aluno it) { if (l == NULL) return 2; if (l->total == MAX) return 1; if (l->total < MAX) { l->valores[l->total] = it; l->total++; return 0; } return 1; } int buscarItemChave(Lista *l, int chave, Aluno *retorno) { int i; if (l == NULL) return 2; if (listaVazia(l) == 0) return 1; for (i = 0; i < l->total; i++) { if (l->valores[i].mat == chave) { *retorno = l->valores[i]; return 0; } } return -1; } int listaVazia(Lista *l) { if (l == NULL) return 2; if (l->total == 0) return 0; else return 1; } int removerInicio(Lista *l) { int i; if (l == NULL) return 2; if (listaVazia(l) == 0) return 1; for (i = 0; i < l->total - 1; i++) { l->valores[i] = l->valores[i + 1]; } l->total--; return 0; } int removerFim(Lista *l) { if (l == NULL) return 2; if (listaVazia(l) == 0) return 1; l->total--; return 0; } int listaCheia(Lista *l) { if (l == NULL) return 2; if (l->total == MAX) return 0; else return 1; } void mostrar(Lista *l) { int i; if (l != NULL) { printf("["); for (i = 0; i < l->total; i++) { printf(" {%d, ", l->valores[i].mat); printf("%s, ", l->valores[i].nome); printf("%.2f} ", l->valores[i].n1); } printf("]\n"); } } // Exercício A int inserirPosicao(Lista *l, Aluno it, int pos) { if (l == NULL) return 2; if (pos < 0 || pos > l->total || l->total >= MAX) { return 3; } for (int i = l->total; i > pos; i--) { l->valores[i] = l->valores[i - 1]; } l->valores[pos] = it; l->total++; return 0; } int removerPosicao(Lista *l, int pos){ if (l == NULL) return 2; if (pos < 0 || pos >= MAX) { return 3; } l->total--; for (int i = pos; i < l->total; i++) { l->valores[i] = l->valores[i + 1]; } return 0; } int removerItem(Lista *l, Aluno it) { if (l == NULL) return 2; int pos = -1; for (int i = 0; i < l->total; i++) { if (l->valores[i].mat == it.mat) { pos = i; break; } } if (pos == -1) return 4; return removerPosicao(l, pos); } int buscarPosicao(Lista *l, int posicao, Aluno *it) { if (l == NULL) return 2; if (posicao < 0 || posicao >= l->total) { return 3; } *it = l->valores[posicao]; return 0; } //Exercicio B int ContemItem(Lista *l, Aluno it) { if (l == NULL) return 2; for (int i = 0; i < l->total; i++) { if (l->valores[i].mat == it.mat) { return 0; } } return 1; } Lista *Reversa(Lista *l) { if (l == NULL) return NULL; Lista *listaReversa = criar(); for (int i = l->total - 1; i >= 0; i--) { inserirFim(listaReversa, l->valores[i]); } return listaReversa; } int contaItem(Lista *l, Aluno it) { if (l == NULL) return -1; int contador = 0; for (int i = 0; i < l->total; i++) { if (l->valores[i].mat == it.mat) { contador++; } } return contador; } //Exercício D #define TAMANHO_INICIAL 10 Lista2 *cria2() { // Corrigido para "cria2" Lista2 *l = (Lista2 *)malloc(sizeof(Lista2)); if (l != NULL) { l->total = 0; l->capacidade = TAMANHO_INICIAL; l->valores = (Aluno *)malloc(TAMANHO_INICIAL * sizeof(Aluno)); if (l->valores == NULL) { free(l); return NULL; } } return l; } // Função para redimensionar a lista, dobrando a capacidade static int redimensionar(Lista2 *l) { int novaCapacidade = l->capacidade * 2; Aluno *novosValores = (Aluno *)realloc(l->valores, novaCapacidade * sizeof(Aluno)); if (novosValores != NULL) { l->valores = novosValores; l->capacidade = novaCapacidade; return 1; // Redimensionamento bem-sucedido } return 0; // Falha no redimensionamento } int inserirFim2(Lista2 *l, Aluno it) { if (l == NULL) return 2; if (l->total == l->capacidade) { // A lista está cheia, redimensione antes de inserir if (!redimensionar(l)) return 1; // Falha ao redimensionar } l->valores[l->total] = it; l->total++; return 0; } void mostrar2(Lista2 *l) { int i; if (l != NULL) { printf("["); for (i = 0; i < l->total; i++) { printf(" {%d, ", l->valores[i].mat); printf("%s, ", l->valores[i].nome); printf("%.2f} ", l->valores[i].n1); } printf("]\n"); } }
<template> <el-menu :default-active="selectedItem" class="nav-menu" active-text-color="#61ac85" @select="handleMenuSelect"> <div> <div class="nav-title nav-item">RevuSage</div> <el-menu-item index="1" class="nav-item"> <el-icon><House /></el-icon> &nbsp;&nbsp; <template #title>会&nbsp;&nbsp;议&nbsp;&nbsp;概&nbsp;&nbsp;览</template> </el-menu-item> <el-menu-item index="2" class="nav-item"> <el-icon><Monitor /></el-icon> &nbsp;&nbsp; <template #title>我&nbsp;&nbsp;的&nbsp;&nbsp;会&nbsp;&nbsp;议</template> </el-menu-item> <el-menu-item index="3" class="nav-item"> <el-icon><Message /></el-icon> &nbsp;&nbsp; <template #title>我&nbsp;&nbsp;的&nbsp;&nbsp;投&nbsp;&nbsp;稿</template> </el-menu-item> <el-menu-item index="4" class="nav-item"> <el-icon><User /></el-icon> &nbsp;&nbsp; <template #title>个&nbsp;&nbsp;人&nbsp;&nbsp;中&nbsp;&nbsp;心</template> </el-menu-item> </div> <div class="nav-bottom nav-item"> <div class="nav-bottom-left"> <ElDropdown trigger="click" style="height: 70px; line-height: 70px" @command="handleCommand"> <div class="nav-dropdown"> <el-avatar :icon="UserFilled" /> <!-- <el-icon style="margin-top: 20px;"><Avatar /></el-icon>&nbsp;&nbsp; <ElTooltip :content="username" style="font-size: 18px;" :disabled="username?.length <= 10"> <span>{{ username?.length > 10 ? username.substring(0, 10)+'...' : username }}</span> </ElTooltip> --> <el-icon style="margin-left: 10px"><arrow-down /></el-icon> </div> <template #dropdown> <ElDropdownMenu> <ElDropdownItem command="logout">注销用户</ElDropdownItem> <!-- <ElDropdownItem command="logoff" divided><span style="color: red">注销用户</span></ElDropdownItem> --> </ElDropdownMenu> </template> </ElDropdown> </div> <div class="nav-bottom-right" @click="handleBellSelect"> <el-icon v-if="selectedItem === ''"><BellFilled /></el-icon> <el-icon v-else><Bell /></el-icon> </div> </div> </el-menu> </template> <script setup lang="ts"> import { House, User, Message, Monitor, Avatar, Bell, BellFilled, ArrowDown, UserFilled } from '@element-plus/icons-vue' import { ElDropdown, ElDropdownItem, ElDropdownMenu, ElMessage, ElMessageBox } from 'element-plus' import { delToken, delUsername, getUsername } from '../../utils/auth' import router from '../../router' import { userStore } from '../../main' import { logOut } from '../../api/userApi' const state = reactive({ username: '', selectedItem: '1' }) const { username, selectedItem } = toRefs(state) onActivated(() => { username.value = getUsername() }) watchEffect(() => { const path = router.currentRoute.value.path if (path === '/') { const defaultActive = router.currentRoute.value.meta.defaultActive const activeQuery = router.currentRoute.value.query.active const pageName = activeQuery || defaultActive switch (pageName) { case 'overview': selectedItem.value = '1' break case 'conference': selectedItem.value = '2' break case 'paper': selectedItem.value = '3' break case 'profile': selectedItem.value = '4' break case 'notification': selectedItem.value = '' break default: selectedItem.value = '1' } } else if (path === '/paper-detail') { selectedItem.value = router.currentRoute.value.query.level === 'person' ? '3' : '2' } else if (path === '/conference-detail') { selectedItem.value = '2' } else if (path === '/conference-paper') { selectedItem.value = '2' } }) const emit = defineEmits(['UpdateActiveTab']) const handleBellSelect = () => { selectedItem.value = '' handleSelect(4) } const handleMenuSelect = (key: string, keyPath: string[]) => { selectedItem.value = key handleSelect(parseInt(key) - 1) } const handleSelect = (value: number) => { emit('UpdateActiveTab', value) } const handleCommand = (value: any) => { if (value === '') { ElMessageBox.confirm('确认退出登录?', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' }) .then(() => { delToken() delUsername() userStore.setUsername('') router.push({ path: '/login' }) }) .catch(() => {}) } else { ElMessageBox.confirm('确认注销该用户?', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' }) .then(() => { logOut().then((res: any) => { if (res.status === 200) { delToken() delUsername() userStore.setUsername('') ElMessage.success('注销成功') router.push({ path: '/login' }) } }) }) .catch(() => {}) } } </script> <style scoped> .nav-menu { height: 100%; width: 100%; display: flex; flex-direction: column; justify-content: space-between; border-radius: 20px; } .nav-item { width: 100%; text-align: center; font-size: 1.1rem; display: flex; justify-content: center; height: 70px; /* border-bottom: 1px solid var(--vt-c-divider-light-1); */ } .nav-title { font-family: 'KKSAKAI', sans-serif; font-size: 3rem; color: var(--color-text-light); background-color: var(--color-icon); margin-bottom: 10px; border-top-right-radius: 20px; /* border: none; */ } .nav-bottom { display: flex; font-size: 20px; line-height: 70px; justify-content: space-between; color: var(--color-text-light); background-color: var(--color-icon); border-bottom-right-radius: 20px; } .nav-bottom-left { margin-left: 20px; } .nav-dropdown { font-size: 17px; cursor: pointer; color: var(--color-text-light); } .nav-bottom-right { margin-right: 20px; } </style>
# SQL RIGHT JOIN KEYWORD La palabra clave `RIGHT JOIN` se utiliza para obtener todos los registros de la tabla de la derecha (segunda tabla declarada) y los registros coincidentes de la tabla de la izquierda (primer tabla declarada). ## Sintaxis ``` SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name; ``` Supongamos que queremos obtener una lista de todas las facturas junto con la información del cliente, incluso aquellas facturas que no tienen un cliente asociado. - Customers es la tabla de la izquierda. - Invoices es la tabla de la derecha. - Customers.CustomerID = Invoices.CustomerID establece la condición de unión basada en la clave primaria y foránea. ``` SELECT Customers.CustomerID, Customers.FirstName, Customers.LastName, Invoices.InvoiceID, Invoices.InvoiceDate FROM Customers RIGHT JOIN Invoices ON Customers.CustomerID = Invoices.CustomerID; ``` La consulta devuelve una lista de facturas con la información del cliente correspondiente, y si no hay un cliente asociado a una factura, los campos del cliente serán NULL. Se debe entender que `LEFT JOIN` y `RIGHT JOIN` funcionan de la misma manera y se puede lograr el mismo resultado cambiando el orden de las tablas.
import 'dart:io'; import 'package:camera/camera.dart'; import 'package:dotted_border/dotted_border.dart'; import 'package:fe_lab_clinicas_core/fe_lab_clinicas_core.dart'; import 'package:fe_lab_clinicas_self_service_cb/src/modules/self_service/documents/scan_confirm/documents_scan_confirm_controller.dart'; import 'package:flutter/material.dart'; import 'package:flutter_getit/flutter_getit.dart'; import 'package:signals_flutter/signals_flutter.dart'; import '../../widget/lab_clinicas_self_service_app_bar.dart'; class DocumentsScanConfirmPage extends StatelessWidget { DocumentsScanConfirmPage({super.key}); final controller = Injector.get<DocumentsScanConfirmController>(); @override Widget build(BuildContext context) { final sizeOf = MediaQuery.sizeOf(context); final foto = ModalRoute.of(context)!.settings.arguments as XFile; controller.pathRemoteStorage.listen(context, () { // Navigator.of(context).pop(); Navigator.of(context).pop(controller.pathRemoteStorage.value); }); return Scaffold( appBar: LabClinicasSelfServiceAppBar(), body: Align( alignment: Alignment.topCenter, child: SingleChildScrollView( child: Container( width: sizeOf.width * .85, margin: const EdgeInsets.only(top: 18), padding: const EdgeInsets.all(32), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: LabClinicasTheme.orangeColor), ), child: Column( children: [ Image.asset('assets/images/foto_confirm_icon.png'), const SizedBox( height: 24, ), const Text( 'CONFIRA SUA FOTO', style: LabClinicasTheme.subTitleSmallStyle, ), const SizedBox( height: 32, ), SizedBox( width: sizeOf.width * .5, child: ClipRRect( borderRadius: BorderRadius.circular(16), child: DottedBorder( dashPattern: const [1, 10, 1, 3], borderType: BorderType.RRect, strokeWidth: 4, color: LabClinicasTheme.orangeColor, strokeCap: StrokeCap.square, radius: const Radius.circular(16), child: Image.file(File(foto.path)), ), ), ), const SizedBox( height: 32, ), Row( children: [ Expanded( child: OutlinedButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text(textAlign: TextAlign.center, 'TIRAR OUTRA'), ), ), const SizedBox( width: 10, ), Expanded( child: ElevatedButton( onPressed: () async { final imageBytes = await foto.readAsBytes(); final fileName = foto.name; await controller.uploadImage(imageBytes, fileName); }, child: const Text('SALVAR'), ), ), ], ) ], ), ), ), ), ); } }
import {APP_BASE_HREF} from '@angular/common'; import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {AppModule} from 'app/app.module'; import {OpenReqCreateFormComponent} from './open-req-create-form.component'; import {OpenRequestModule} from '../open-request.module'; describe('Open Req Create Form Component', () => { let component: OpenReqCreateFormComponent; let fixture: ComponentFixture<OpenReqCreateFormComponent>; let compiled; beforeEach(async(() => { TestBed.configureTestingModule({ providers: [{ provide: APP_BASE_HREF, useValue: '/' }], imports: [AppModule, OpenRequestModule ] }).compileComponents(); fixture = TestBed.createComponent(OpenReqCreateFormComponent); component = fixture.componentInstance; compiled = fixture.debugElement.nativeElement; })); it('create request button should not be enabled if there is no client email', () => { component.searching = false; component.requestor.name = 'test name'; component.requestor.contacts = ['test']; component.requestor.emailId = ''; component.requestModel.pickupAddress.city = 'test city'; component.requestModel.dropAddress.city = 'test city'; expect(component.goForConfirm()).toBeFalsy(); }); it('create request button should be enabled if there is a client email', () => { component.searching = false; component.requestor.name = 'test name'; component.requestor.contacts = ['test']; component.requestor.emailId = '[email protected]'; component.requestModel.pickupAddress.city = 'test city'; component.requestModel.dropAddress.city = 'test city'; expect(component.goForConfirm()).toBeTruthy(); }); it('create request button should not be enabled if there is no pickupaddress', () => { component.searching = false; component.requestor.name = 'test name'; component.requestor.contacts = ['test']; component.requestor.emailId = '[email protected]'; component.requestModel.pickupAddress.city = ''; component.requestModel.dropAddress.city = 'test city'; expect(component.goForConfirm()).toBeFalsy(); }); it('create request button should be enabled if there is a pickupaddress', () => { component.searching = false; component.requestor.name = 'test name'; component.requestor.contacts = ['test']; component.requestor.emailId = '[email protected]'; component.requestModel.pickupAddress.city = 'test city'; component.requestModel.dropAddress.city = 'test city'; expect(component.goForConfirm()).toBeTruthy(); }); it('create request button should not be enabled if there is no requestor name', () => { component.searching = false; component.requestor.name = ''; component.requestor.contacts = ['test']; component.requestor.emailId = '[email protected]'; component.requestModel.pickupAddress.city = 'test city'; component.requestModel.dropAddress.city = 'test city'; expect(component.goForConfirm()).toBeFalsy(); }); it('create request button should not be enabled if there is a requestor name', () => { component.searching = false; component.requestor.name = 'test name'; component.requestor.contacts = ['test']; component.requestor.emailId = '[email protected]'; component.requestModel.pickupAddress.city = 'test city'; component.requestModel.dropAddress.city = 'test city'; expect(component.goForConfirm()).toBeTruthy(); }); it('create request button should not be enabled if there is no drop address', () => { component.searching = false; component.requestor.name = 'test name'; component.requestor.contacts = ['test']; component.requestor.emailId = '[email protected]'; component.requestModel.pickupAddress.city = 'test city'; component.requestModel.dropAddress.city = ''; expect(component.goForConfirm()).toBeFalsy(); }); it('create request button should be enabled if there is a drop address', () => { component.searching = false; component.requestor.name = 'test name'; component.requestor.contacts = ['test']; component.requestor.emailId = '[email protected]'; component.requestModel.pickupAddress.city = 'test city'; component.requestModel.dropAddress.city = 'test city'; expect(component.goForConfirm()).toBeTruthy(); }); });
package com.study.springboothyejin.aop; import com.study.springboothyejin.web.exception.CustomValidException; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.validation.BeanPropertyBindingResult; import java.util.HashMap; import java.util.Map; @Aspect @Component public class ValidationAop { @Pointcut("execution(* com.study.springboothyejin.web.controller.account.AccountApiController.*(..))") private void executionPointCut() {}; @Pointcut("@annotation(com.study.springboothyejin.aop.annotation.ValidAspect)") private void annotationPointCut() {}; @Around("executionPointCut()") public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Object[] args = proceedingJoinPoint.getArgs(); for(Object arg : args) { System.out.println(arg); } System.out.println("AOP 작동함"); BeanPropertyBindingResult bindingResult = null; for(Object arg : args) { if(arg.getClass() == BeanPropertyBindingResult.class){ bindingResult = (BeanPropertyBindingResult) arg; break; } } if(bindingResult != null){ if(bindingResult.hasErrors()) { Map<String, String> errorMap = new HashMap<String, String>(); bindingResult.getFieldErrors().forEach(error ->{ errorMap.put(error.getField(), error.getDefaultMessage()); }); throw new CustomValidException(errorMap); } } Object returnValue = proceedingJoinPoint.proceed(); return returnValue; } }
Newsgroups: comp.emulators.mac.executor From: [email protected] Subject: comp.emulators.mac.executor mini-FAQ, Please read before posting Thank you for reading this introduction to comp.emulators.mac.executor. Last modified: November 9th 1999 What is this newsgroup? What articles are appropriate here? comp.emulators.mac.executor (c.e.m.e.) was created for the discussion of Executor, a commercial Macintosh emulator for PCs. Discussions of Executor are welcome. Please read this mini-FAQ and the complete FAQ (see below) before posting. Both documents answer the questions that come to mind when you first hear about Executor, so by reading the FAQs you can avoid asking questions that most of the readers of this newsgroup are tired of answering. Reading FAQs before posting on usenet is considered good "netiquette" and will help make c.e.m.e. a useful discussion group and may avoid some of the "flame-wars" found on advocacy groups. Please do not post encoded binaries to c.e.m.e. Such posts are prohibited by c.e.m.e's charter (see below). Please respect the problems that such posts cause some of c.e.m.e's readership. Please do not post requests for Macintosh ROMs or System files here. Macintosh ROMs and System files are copyrighted by Apple Computer, Inc. Asking for a copy of them is asking someone to violate copyright laws. Even if it weren't, it's off-topic because Executor doesn't need Macintosh ROMs or Apple System files. C.e.m.e. is *not* an advocacy group, it's a support group for users of Executor. It isn't a support group for emulator users in general. If the discussion isn't about Executor, it's off-topic. Different people have different needs, so some people find Executor quite useful, others find it a novelty and some have no need for it at all. Please accept this and don't try to convince people that Executor is good or that Executor is bad in c.e.m.e. It's unlikely you'll change anybody's mind, and your time is better spent elsewhere. Similarly, some people like Macs, some people dislike them; please don't argue about operating systems in c.e.m.e. By ignoring off-topic posts, the off-topic poster will always get the last word in. *That's _OK_*. In any honest disagreement, proponents of each side will believe they are correct and the other person is mistaken. That leads to a desire to rebut any incorrect information that one sees, but this is Usenet. Incorrect information will always be plentiful. Even though it's counter-intuitive, you're more likely to see incorrect off-topic information disappear if you ignore it than if you automatically respond to it. Where is the complete FAQ? The latest version is always available via the World-Wide Web at <http://www.ardi.com/executor-faq.html/> You may also find it elsewhere, but beware. In cyberspace, outdated information can live an exceedingly long time. As such, it's especially useful for Executor users to have WWW access and to refer to the webbed FAQ, rather than looking for it elsewhere. If you don't have WWW access, you can get a copy mailed to you by sending email to [email protected] with "faq" or "FAQ" in the subject line (not the body) of the message, or by sending email to [email protected]. Both "[email protected]" and "[email protected]" are automated email servers which do not read the contents of the letter that is sent to them. What is Executor? Executor, a commercial product, is an emulator that allows non-Macintosh hardware to run many applications originally written for a Macintosh. It also lets your PC read and write Mac-formatted high-density floppies and Mac external hard drives, and read Mac CDs. Executor for Windows includes both Executor/DOS (E/D) and Executor/Win32 (E/W). E/D runs under DOS, Windows 3.x and OS/2. E/W runs under Windows 95, Windows 98 and NT. Executor for Linux includes the supported Executor/Linux/X and the unsupported Executor/Linux/SVGAlib and Executor/Linux/SDL. Where can I pick up the Executor demos? <http://www.ardi.com/> What limitations does Executor have? See the complete FAQ for more details. ARDI has rewritten the OS and Toolbox calls from scratch. This provides a tremendous speed improvement and allows Executor to be sold independently of Apple. This does cause some limitations, including limited serial port access, no AppleTalk, incomplete System 7 support, no INITs (which means no QuickTime and no ATM), no CDEVs and very little internationalization. Due to limitations in PC hardware, Executor can read and write 1.4 MB Mac formatted floppy disks, but can *not* read or write Mac formatted 800 KB floppy disks. Without custom hardware, PCs simply can't read the Mac 800 KB format. If you think you've seen software that allows this, you're mistaken. It's possible to read 800 KB formatted floppies that are in a different format, but not 800 KB floppies that are in the Mac 800 KB format. Executor prints directly to PostScript printers. If you don't have a PostScript printer, Executor can print to a Postscript file for which you will need a PostScript filter in order to print. Who makes Executor? <http://www.ardi.com/> ARDI Suite 4-101 1650 University Blvd., NE Albuquerque, NM 87102 +1 505 766 9115 Phone +1 505 766 5153 FAX [email protected] What is the c.e.m.e. charter? CHARTER: comp.emulators.mac.executor Comp.emulators.mac.executor is for general discussion of ARDI's Executor software Macintosh emulator. Executor users and potential users are encouraged to discuss Executor bugs and workarounds and to share tips for getting Executor to work properly with specific hardware and/or software. ARDI will post announcements of new versions, and provide other help when possible. Criticism, advice, and mutual user assistance are all expected and encouraged. Advertisements and off-topic postings are forbidden, as is the posting of encoded binaries or any information on obtaining pirated software. END CHARTER. Thank you for reading this. With your cooperation, we can keep a high signal-to-noise ratio on c.e.m.e.
package jatx.mybooks import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.Settings import android.util.Log import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import jatx.mybooks.util.Backup.loadLauncher import jatx.mybooks.util.Backup.saveLauncher import jatx.mybooks.util.Backup.tryToLoadBackup import jatx.mybooks.util.onLoadPermissionGranted import jatx.mybooks.util.onSavePermissionGranted class MainActivity : AppCompatActivity() { init { saveLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { map -> if (map.all { it.value }) { onSavePermissionGranted() } } loadLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { map -> if (map.all { it.value }) { onLoadPermissionGranted() } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) requestForManageExternalStorage() initBookList() } private fun initBookList() { Log.e("MainActivity", "onAppStart") if (Build.VERSION.SDK_INT < 33) { tryToLoadBackup() } else { onLoadPermissionGranted() } } private fun requestForManageExternalStorage() { if (Build.VERSION.SDK_INT >= 30) { if (!Environment.isExternalStorageManager()) { val intent = Intent() intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION val uri = Uri.fromParts("package", this.packageName, null) intent.data = uri startActivity(intent) } } } }
import { BadRequestException, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Creator } from './creator.entity'; import { In, Repository } from 'typeorm'; import { LimitArg, SortBy } from '../../utils/ArgsTypes'; import { CreatorDto } from './creator.dto'; import { GraphQLResolveInfo } from 'graphql'; import { PrismaService } from 'src/prisma.service'; import { Prisma } from '.prisma/client'; import { isEmpty } from 'class-validator'; import { getPrismaSelectString } from 'src/utils/GetPrismaSelectString'; @Injectable() export class CreatorService { constructor( @InjectRepository(Creator) private readonly creatorRepository: Repository<Creator>, private readonly prisma: PrismaService, ) {} async getAll( info: GraphQLResolveInfo, sort = SortBy.LAST_CREATED, limit = LimitArg.getAllCreators.default, skip: number, ): Promise<Creator[]> { if (limit > LimitArg.getAllCreators.max) { throw new Error( `Your "limit" argument exceeds our maxim (${LimitArg.getAllCreators.max})`, ); } const select = getPrismaSelectString(info); const orderBy: Prisma.Enumerable<Prisma.creatorOrderByWithRelationInput> = {}; switch (sort) { case SortBy.LAST_CREATED: orderBy.created = 'desc'; break; case SortBy.NAME: orderBy.name = 'asc'; break; case SortBy.LAST_UPDATED: orderBy.lastUpdated = 'desc'; break; default: orderBy.name = 'asc'; } return this.prisma.creator.findMany({ take: limit, skip, orderBy, ...select, }); } async create(creatorDto: CreatorDto) { if (creatorDto.name.trim().length == 0) { throw new BadRequestException(creatorDto.name, 'The name must not be empty'); } const creator = new Creator(); creator.name = creatorDto.name; creator.profilePicture = creatorDto.profilePicture; creator.bannerPicture = creatorDto.bannerPicture; return this.creatorRepository.save(creator); } async findById(id: string, info?: GraphQLResolveInfo): Promise<Creator> { const select = getPrismaSelectString(info); const creator = await this.prisma.creator.findFirst({ where: { id }, ...select, }); return creator; } async searchByName( name: string, info: GraphQLResolveInfo, sort = SortBy.NAME, limit: number, skip: number, ): Promise<Creator[]> { if (isEmpty(name)) throw new BadRequestException('Empty "name" argument'); if (limit > LimitArg.getAllCreators.max) { throw new Error( `Your "limit" argument exceeds our maxim (${LimitArg.getAllCreators.max})`, ); } const select = getPrismaSelectString(info); const orderBy: Prisma.Enumerable<Prisma.creatorOrderByWithRelationInput> = {}; switch (sort) { case SortBy.LAST_CREATED: orderBy.created = 'desc'; break; case SortBy.NAME: orderBy.name = 'asc'; break; case SortBy.LAST_UPDATED: orderBy.lastUpdated = 'desc'; break; default: orderBy.name = 'asc'; } const result = await this.prisma.creator.findMany({ where: { name: { contains: name, }, }, skip, take: limit, orderBy, ...select, }); return result; } // Differs from findByIds by checking the number of creators requested. async getByIds(ids: string[], info: GraphQLResolveInfo, sort?: SortBy): Promise<Creator[]> { const select = getPrismaSelectString(info); if (ids.length > LimitArg.getAllCreators.max) { throw new Error( `The number of creators you are requesting exceeds our maxim (${LimitArg.getAllCreators.max})`, ); } const orderBy: Prisma.Enumerable<Prisma.creatorOrderByWithRelationInput> = {}; switch (sort) { case SortBy.LAST_CREATED: orderBy.created = 'desc'; break; case SortBy.NAME: orderBy.name = 'asc'; break; case SortBy.LAST_UPDATED: orderBy.lastUpdated = 'desc'; break; } const result = await this.prisma.creator.findMany({ where: { id: { in: ids, }, }, orderBy, ...select, }); return result; } // This is used by the dataloader and should not be changed. async findByIds(ids: readonly Creator['id'][]) { return this.creatorRepository.find({ where: { id: In(ids as Creator['id'][]) }, cache: true, }); } }
<div class="body-container"> <mat-card class="login-card"> <mat-card-header class="card-header"> <div class="row"> <div class="col-md-6 mb-5"> <a routerLink="/professor/create-account" mat-flat-button class="uni-btn-primary"> <mat-icon aria-hidden="false" svgIcon="teacher" aria-label="add circle outline icon"></mat-icon> S'inscrire </a> </div> <div class="col-md-6"> <a routerLink="/student/create-account" mat-flat-button class="uni-btn-primary"> <mat-icon svgIcon="student" aria-hidden="false" aria-label="add circle outline icon"></mat-icon> S'inscrire </a> </div> <div class="row text-center"> <mat-card-title><img src="../../assets//images/school.png" alt="" width="150px"></mat-card-title> </div> </div> </mat-card-header> <form [formGroup]="loginForm" class="form" (ngSubmit)="onLogin()" > <mat-card-content> <mat-form-field class="input-full-width"> <mat-label>Email</mat-label> <input matInput formControlName="email" type="email" name="email" > <mat-error *ngIf="loginForm.controls['email'].hasError('required')"> Champ obligatoire, entrez un email valide ! </mat-error> </mat-form-field> <mat-form-field class="input-full-width"> <mat-label>Mot de passe</mat-label> <input matInput formControlName="password" type="password" name="password" > <mat-error *ngIf="loginForm.controls['password'].hasError('required')"> Champ obligatoire ! </mat-error> </mat-form-field> </mat-card-content> <section class="example-section"> <mat-radio-group [formControl] = "loginForm.controls['statut']" name="statut"> <mat-radio-button class="radio-margin" value="professor"> <mat-icon svgIcon="teacher" aria-hidden="false"></mat-icon> </mat-radio-button> <mat-radio-button class="radio-margin" value="student"> <mat-icon svgIcon="student" aria-hidden="false"></mat-icon> </mat-radio-button> </mat-radio-group> </section> <mat-card-actions class="text-end"> <button mat-fab class="btn-fab"> <mat-icon aria-hidden="false" svgIcon="login" aria-label="login icon"></mat-icon> </button> </mat-card-actions> </form> </mat-card> </div>
import * as React from "react"; import { getApp, getApps, initializeApp } from 'firebase/app'; import { getAuth, indexedDBLocalPersistence, setPersistence, signInAnonymously, signInWithEmailAndPassword, User } from 'firebase/auth'; import * as EventEmitter from "events"; declare const port: { addListener(subject: string, callback: (...content: any[]) => any, options?: { once?: boolean }): void removeListener(subject: string): void; removeListener(subject: string, callback: (...content: any[]) => any): void; postMessage(subject: string, ...content: any[]): void; }; type Apis = { isRenderer: boolean, controlWindow(method: string): void; useWindowState(): { isFullscreen: boolean; isMaximize: boolean; isMinimize: boolean; }; useCurrentUser(): User | null; getUserInfo(): Promise<UserInfo>; signIn(email: string, password: string): Promise<void>; signOut(): Promise<void>; search(searchString: string): Promise<any[]>; getHomepageContent(): Promise<BookSet[]>; getBookGroupInfo(BookGroupID: string, IsSerial: string): Promise<BookGroupInfo>; getVolInfo(BookID: string): Promise<BookVolInfo>; getBookPages(BookID: string, IsFree: boolean, callback: (pages: Page[], progress: number) => any): Promise<Page[]>; openExternal(href: string): void; alert(message: string): Promise<void>; alert(title: string, message: string): Promise<void>; }; const ApisContext: React.Context<Apis> = React.createContext<Apis>(null); ApisContext.displayName = 'Apis'; const modal = new EventEmitter; const ModalContext: React.Context<EventEmitter> = React.createContext<EventEmitter>(modal); ModalContext.displayName = 'Modal'; function getApis(): Apis { const app = getApps().length ? getApp() : initializeApp({ apiKey: "AIzaSyAJbYmo7KyhM_7CDXjjFXnp8bdRTNgbUIE", authDomain: "tongli-book.firebaseapp.com", databaseURL: "https://tongli-book.firebaseio.com", projectId: "tongli-book", storageBucket: "tongli-book.appspot.com", messagingSenderId: "1066510659255", appId: 'tongli-book' }); const auth = getAuth(app); const windowState = { isFullscreen: false, isMaximize: false, isMinimize: false }; return { isRenderer: (window.process as any)?.type === 'renderer', controlWindow(method) { return port.postMessage('window-control', method); }, useWindowState() { const [state, setState] = React.useState(windowState); React.useEffect(function () { port.addListener('window-state', function (state) { setState(state); Object.assign(windowState, state); }); }, []); return state; }, useCurrentUser() { const [user, setUser] = React.useState<User>(auth.currentUser); React.useEffect(function () { auth.onAuthStateChanged(function (user) { setUser(user); console.log(user) }); }, []); return user; }, getUserInfo() { const user = auth.currentUser; return new Promise(function (resolve, reject) { if (!user) return reject(); return user.getIdToken(true).then(function (token) { function listener(result: any) { port.removeListener('user-info', listener); resolve(result); } port.postMessage('user-info', token); return port.addListener('user-info', listener); }).catch(function (reason) { return reject(reason); }); }); }, signIn(email, password) { return new Promise(function (resolve, reject) { return signInWithEmailAndPassword(auth, email, password).then(function () { return setPersistence(auth, indexedDBLocalPersistence); }).then(function () { return resolve(); }).catch(function () { return reject(); }); }); }, signOut() { return auth.signOut(); }, search(searchString) { return new Promise(function (resolve) { function listener(result: any) { port.removeListener('search', listener); resolve(result); } port.postMessage('search', searchString); return port.addListener('search', listener); }); }, getHomepageContent() { return new Promise(function (resolve) { function listener(result: any) { port.removeListener('homepage', listener); resolve(result); } port.postMessage('homepage'); return port.addListener('homepage', listener); }); }, getBookGroupInfo(BookGroupID, IsSerial) { return new Promise(function (resolve) { function listener(result: any) { port.removeListener('book-group-info', listener); resolve(result); } port.postMessage('book-group-info', { BookGroupID, IsSerial }); return port.addListener('book-group-info', listener); }); }, getVolInfo(BookID) { return new Promise(function (resolve) { function listener(result: any) { port.removeListener('book-vol-info', listener); resolve(result); } port.postMessage('book-vol-info', BookID); return port.addListener('book-vol-info', listener); }); }, getBookPages(BookID, IsFree, callback) { return new Promise(function (resolve, reject) { const user = auth.currentUser?.isAnonymous ?? true ? signInAnonymously(auth).then(() => auth.currentUser) : Promise.resolve(auth.currentUser); return user.then(user => user.getIdToken(true)).then(function (token) { if (auth.currentUser?.isAnonymous) auth.signOut(); const pages: Page[] = []; function listener(result: Page[] | {}, progress: number, end: boolean) { if (result === null) { resolve(pages); port.removeListener(`book-pages:${BookID}`, listener); } else if (result instanceof Array) { result.forEach(function (page) { pages[page.PageNumber - 1] = page; }); callback(pages, progress); if (end) { resolve(pages); port.removeListener(`book-pages:${BookID}`, listener); }; } else { reject(result); port.removeListener(`book-pages:${BookID}`, listener); } } port.postMessage('book-pages', { BookID, IsFree, token }); return port.addListener(`book-pages:${BookID}`, listener); }); }); }, openExternal(href) { return port.postMessage('open-external', href); }, alert(...args: string[]): Promise<void> { return new Promise(function (resolve) { function listener() { modal.removeListener('modal-close', listener); resolve(void 0); } modal.emit('modal-show', ...args); return modal.addListener('modal-close', listener); }); } } } export const ApisProvider: React.FunctionComponent<React.PropsWithChildren> = function ApisProvider(props) { const apis = getApis(); return ( <ModalContext.Provider value={modal}> <ApisContext.Provider value={apis}> {props.children} </ApisContext.Provider> </ModalContext.Provider> ); }; export function useApis(): Apis { return React.useContext(ApisContext); } export function useModal(): EventEmitter { return React.useContext(ModalContext); }
class Solution { func strStr(_ haystack: String, _ needle: String) -> Int { guard haystack.count >= needle.count else { return -1 } var lower = haystack.startIndex var upper = haystack.index( haystack.startIndex, offsetBy: needle.count - 1 ) while upper < haystack.endIndex { if haystack[lower...upper] == needle { return haystack.distance(from: haystack.startIndex, to: lower) } lower = haystack.index(after: lower) upper = haystack.index(after: upper) } return -1 } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Mini chat</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous" /> </head> <body class="container"> <h1 class="mt-5">Mini chat</h1> <hr /> <form id="myForm"> <div class="row"> <div class="col-8"> <input type="text" id="msgBox" placeholder="Mensaje" class="form-control" /> </div> <div class="col-4"> <button class="btn btn-primary">Enviar</button> </div> </div> </form> <div class="row"> <div class="col"> <ul id="messages" class="mt-2"></ul> </div> </div> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous" referrerpolicy="no-referrer" ></script> <script> const socket = io("http://localhost:8080/"); const form = document.querySelector("#myForm"); const messages = document.querySelector("#messages"); const msgBox = document.querySelector("#msgBox"); form.addEventListener("submit", (e) => { e.preventDefault(); const msg = msgBox.value; socket.emit("msg", { msg, }); msgBox.value = ""; }); socket.on("reply", (data) => { messages.innerHTML += `<li>${data.msg}</li>`; }); </script> </html>
import { createApp } from 'vue' import { Quasar, Notify, Dialog } from 'quasar' import { createPinia } from 'pinia' import '@quasar/extras/roboto-font-latin-ext/roboto-font-latin-ext.css' import '@quasar/extras/material-icons/material-icons.css' import '@quasar/extras/mdi-v6/mdi-v6.css' // import '@quasar/extras/material-icons-outlined/material-icons-outlined.css' // import '@quasar/extras/material-icons-round/material-icons-round.css' // import '@quasar/extras/material-icons-sharp/material-icons-sharp.css' // A few examples for animations from Animate.css: // import @quasar/extras/animate/fadeIn.css // import @quasar/extras/animate/fadeOut.css import './index.css' import 'quasar/src/css/index.sass' import App from './App.vue' import router from './router' import { store, key } from './store' import { __baseURL } from './constant' import axios from 'axios' import { auth } from '@/firebase/firebaseConfig' axios.defaults.baseURL = __baseURL const unsubscribe = auth.onAuthStateChanged(async user => { unsubscribe() if (user) { const token = await user.getIdToken() axios.defaults.headers.common['Authorization'] = 'Bearer ' + token } else { if (window.location.pathname === '/') router.push('/welcome') } }) const myApp = createApp(App) myApp.use(Quasar, { plugins: { Notify, Dialog } }) myApp.use(createPinia()) myApp.use(router) myApp.use(store, key) myApp.mount('#app')
#ifndef SCISL_COMMON_H #define SCISL_COMMON_H #ifndef SCISL_INT_PRECISION #define SCISL_INT_PRECISION int #endif #ifndef SCISL_FLOAT_PRECISION #define SCISL_FLOAT_PRECISION float #endif #include <string> #define SCISL_CAST_INT(var) (*(SCISL_INT_PRECISION*)(var)) #define SCISL_CAST_FLOAT(var) (*(SCISL_FLOAT_PRECISION*)(var)) #define SCISL_CAST_STRING(var) (*(std::string*)(var)) namespace scisl { enum class type : unsigned char { integer, floating, string, error }; constexpr const char* typeToStr(type t) { switch (t) { case scisl::type::integer: return "Integer"; case scisl::type::floating: return "Float"; case scisl::type::string: return "String"; default: return "Error"; } } //these are vals, used during runtime struct value { type type; void* val; value() : type(type::error), val(nullptr) {} value(value& o) = default; value(value&& moved) noexcept; value& operator=(value& o); value& operator=(value&& moved) noexcept; value& operator=(void* val); value& operator=(SCISL_INT_PRECISION val); value& operator=(SCISL_FLOAT_PRECISION val); value& operator=(std::string val); value& operator+=(value& other); value& operator-=(value& other); value& operator*=(value& other); value& operator/=(value& other); value& operator%=(value& other); value& operator|=(value& other); value& operator&=(value& other); value& operator^=(value& other); value& operator>>=(value& other); value& operator<<=(value& other); bool operator<(value& other); bool operator>(value& other); bool operator==(value& other); bool operator==(SCISL_INT_PRECISION other); bool operator&&(value& other); bool operator||(value& other); ~value(); }; value createTemporary(type tipe); value createTemporary(type tipe, SCISL_INT_PRECISION val); value createTemporary(type tipe, SCISL_FLOAT_PRECISION val); value createTemporary(type tipe, std::string val); } #endif
package sem.dataaccess; import sem.models.Car; import java.sql.*; import java.util.ArrayList; import java.util.List; public class DataAccess { public List<Car> GetCars() { List<Car> cars = new ArrayList<>(); try { Class.forName("org.postgresql.Driver"); String hostname = System.getenv("DB_HOSTNAME"); String username = System.getenv("DB_USER"); String password = System.getenv("DB_PASSWORD"); String url = String.format("jdbc:postgresql://%s:5432/%s", hostname, username); Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); String sql = "SELECT Id, Make, Model FROM public.cars"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Integer id = rs.getInt("Id"); String make = rs.getString("Make"); String model = rs.getString("Model"); Car car = new Car(id, make, model); cars.add(car); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return cars; } public void AddCar(Car car) { try { Class.forName("org.postgresql.Driver"); String hostname = System.getenv("DB_HOSTNAME"); String username = System.getenv("DB_USER"); String password = System.getenv("DB_PASSWORD"); String url = String.format("jdbc:postgresql://%s:5432/%s", hostname, username); Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); try { var prestmt = conn.prepareStatement("INSERT INTO cars (Make, Model) VALUES (?,?)"); prestmt.setString(1, car.getMake()); prestmt.setString(2, car.getModel()); prestmt.execute(); } catch (Exception ex) { System.out.println(ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } } } catch (Exception ex) { System.out.println(ex.getMessage()); } return; } }
import { Injectable, inject } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Product, ProductData } from '../interfaces/product'; @Injectable({ providedIn: 'root' }) export class ProductService { private httpClient = inject(HttpClient); private productsURL = new URL('https://dummyjson.com/products'); private headerOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; all(): Observable<ProductData> { return this.httpClient.get<ProductData>(this.productsURL.href, this.headerOptions); } byId(id: number): Observable<Product> { return this.httpClient.get<Product>(this.productsURL.href + `/${id}`, this.headerOptions); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('variaciones', function (Blueprint $table) { $table->id(); $table->string('orden'); $table->foreignId('producto_id')->constrained('productos')->onDelete('cascade'); $table->string('color'); $table->string('medida'); $table->string('material'); $table->string('tipo'); $table->string('imagen')->nullable(); $table->string('imagen2')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('variaciones'); } };
import React, { useContext } from 'react' import Spinner from './Spinner' import { AppContext } from '../context/AppContext' const Blogs = () => { // Consume const { posts, loading } = useContext(AppContext); return ( <div className='w-11/12 h-full max-w-[630px] py-8 flex flex-col justify-center items-center gap-y-7 mt-12 mb-10'> { loading ? (<Spinner />) : ( posts.length === 0 ? (<div> <p>No post found</p> </div>) : (posts.map((post) => ( <div key={post.id}> <p className='font-bold text-lg'>{post.title}</p> <p> By <span className='italic text-[14px]'>{post.author}</span> on <a href="" className=' text-sm underline font-bold'>{post.category}</a> </p> <p className='text-[14px] mb-4'>Posted on {post.date}</p> <p>{post.content}</p> <div className='flex gap-3'> {post.tags.map((tag, index) => { return <a href='' key={index} className='text-blue-700 underline font-semibold text-[12px] mt-2'>{`#${tag}`} </a> })} </div> </div> ))) ) } </div> ) } export default Blogs
import express from 'express'; import Todo from '../models/todo.js'; import User from '../models/user.js'; const router = express.Router(); // Get all records of Todo Collection router.get("/getAllTodoList", async (req, res) => { const getAllRecords = await Todo.find() res.send(getAllRecords) }) //create Todo router.post("/create-todo", async (req, res) => { //console.log("req.body---", req.body) const addTodo = new Todo({ title: req.body.title, content: req.body.content, }) await addTodo.save() res.send(addTodo) }) //Get individual Record of Todo router.get("/getTodoList/:id", async (req, res) => { try { const getTodo = await Todo.findOne({ _id: req.params.id }) res.send(getTodo) }catch { res.status(404) res.send({ error: "Record doesn't exist!" }) } }) //update todo router.patch("/updateTodo/:id", async (req, res) => { try { const todo = await Todo.findOne({ _id: req.params.id }) if (req.body.title) { todo.title = req.body.title } if (req.body.content) { todo.content = req.body.content } await todo.save() res.send(todo) } catch { res.status(404) res.send({ error: "Todo doesn't exist!" }) } }) //delete todo router.delete("/deleteTodo/:id", async (req, res) => { try { await Todo.deleteOne({ _id: req.params.id }) res.status(204).send() } catch { res.status(404) res.send({ error: "Todo doesn't exist!" }) } }) //create user router.post("/create-user", async (req, res) => { console.log("req.body----", req.body) const addUser = new User({ name: req.body.name, address: req.body.address, }) await addUser.save() res.send(addUser) }) export default router
package com.pramudiaputr.githubapp.ui.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.pramudiaputr.githubapp.model.ListUserResponse import com.pramudiaputr.githubapp.model.SearchResponse import com.pramudiaputr.githubapp.network.ApiConfig import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainViewModel : ViewModel() { private var _listUser = MutableLiveData<List<ListUserResponse>>() var listUser: LiveData<List<ListUserResponse>> = _listUser private val _isLoading = MutableLiveData<Boolean>() val isLoading: LiveData<Boolean> = _isLoading private val _searchCount = MutableLiveData<Int>() val searchCount: LiveData<Int> = _searchCount init { getListUser() } private fun getListUser() { _isLoading.value = true val client = ApiConfig.getApiServices().getUserList() client.enqueue(object : Callback<List<ListUserResponse>> { override fun onResponse( call: Call<List<ListUserResponse>>, response: Response<List<ListUserResponse>> ) { _isLoading.value = false if (response.isSuccessful) { _listUser.value = response.body() } else { Log.e(TAG, "onFailure: ${response.message()}") } } override fun onFailure(call: Call<List<ListUserResponse>>, t: Throwable) { _isLoading.value = false Log.e(TAG, "onFailure connect: ${t.message}") } }) } fun searchUser(username: String) { _isLoading.value = true val client = ApiConfig.getApiServices().searchUser(username) client.enqueue(object : Callback<SearchResponse> { override fun onResponse( call: Call<SearchResponse>, response: Response<SearchResponse> ) { _isLoading.value = false if (response.isSuccessful) { _listUser.value = response.body()?.items _searchCount.value = response.body()?.totalCount } } override fun onFailure(call: Call<SearchResponse>, t: Throwable) { _isLoading.value = false Log.e(TAG, "onFailure: ${t.message}") } }) } companion object { private val TAG = MainViewModel::class.java.simpleName } }
/* Copyright 2017. All rights reserved. Computer Vision Group, Visual Computing Institute RWTH Aachen University, Germany This file is part of the rwth_mot framework. Authors: Aljosa Osep (osep -at- vision.rwth-aachen.de) rwth_mot framework is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. rwth_mot framework is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with rwth_mot framework; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef GOT_OBJECT_PROPOSAL_H #define GOT_OBJECT_PROPOSAL_H #include "shared_types.h" #include <vector> #include <Eigen/Dense> #include <Eigen/StdVector> // PCL #include <pcl/common/common_headers.h> #include <pcl/point_types.h> namespace GOT { namespace segmentation { /** * @brief This class represents one object proposal. * Object proposal is 3D region, mostly defined by set of 3d points. * These 3d points are stored here as * (linear) indices, corresponding to 'cells' of (organized) pcl::PointCloud. * Thus, indices relate the region to both, 2d image plane and a set of 3d points. * 2D image indices can be obtained using GOT::utils::geometry::ConvertIndex2Coordinates(...) * * For convenience, we also store 2d and 3d bounding box, 3d pos. (in local coord. frame of point cloud) * and id of the proposal. */ class ObjectProposal { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef std::vector<ObjectProposal, Eigen::aligned_allocator<ObjectProposal> > Vector; public: void init(const std::vector<int> &groundplane_indices, const std::vector<int> &pointcloud_indices, const Eigen::Vector4d &bounding_box_2d, const Eigen::VectorXd &bounding_box_3d, double score, int image_width, int image_height); // Setters / getters Eigen::Vector4d pos3d() const; double score() const; const Eigen::Vector4d &bounding_box_2d() const; const Eigen::VectorXd &bounding_box_3d() const; const std::vector<int> &pointcloud_indices() const; const std::vector<int> &ground_plane_indices() const; const SUN::shared_types::CompressedMask &compressed_mask() const; const std::vector<std::pair<float, float> > &scale_pairs() const; const Eigen::Matrix3d &pose_covariance_matrix() const; const int category() const; const int second_category() const; const std::vector<float> &posterior() const; // Agnostic const std::vector<float> &second_posterior() const; // Specific void set_bounding_box_2d(const Eigen::Vector4d &bbox2d); void set_bounding_box_3d(const Eigen::VectorXd &bbox3d); void set_pos3d(const Eigen::Vector4d &pos3d); void set_score(double new_score); void set_pointcloud_indices(const std::vector<int> &indices, int image_width, int image_height); void set_pointcloud_indices(const std::string &mask_rle, int image_width, int image_height); void set_groundplane_indices(const std::vector<int> &indices); void set_pose_covariance_matrix(const Eigen::Matrix3d &pose_cov_mat); void set_category(int category_index); void set_second_category(int category_index); void set_posterior(const std::vector<float> &p); // Agnostic void set_second_posterior(const std::vector<float> &p); // Specific void add_scale_pair(const std::pair<float, float> &scale_pair); void add_scale_pairs(const std::vector<std::pair<float, float> > &scale_pairs); void set_segm_id(int id); int segm_id() const; void free(); private: std::vector<int> groundplane_indices_; Eigen::Vector4d pos3d_; double score_; int category_; // Agnostic int second_category_; // Specific Eigen::Vector4d bounding_box_2d_; // 2D bounding box: [min_x min_y width height] Eigen::VectorXd bounding_box_3d_; // 3D bounding box: [centroid_x centroid_y centroid_z width height length q.w q.x q.y q.z] Eigen::Matrix3d pose_covariance_matrix_; // Scales info std::vector<std::pair<float, float> > scale_pairs_; //std::vector<std::pair<int, int>> convex_hull_; std::vector<int> cached_indices_; SUN::shared_types::CompressedMask compressed_mask_; // NEW std::vector<float> posterior_; // Agnostic std::vector<float> second_posterior_; // Specific int segm_id_; }; } } #endif
import { ArticleFadeIn, RowProps } from '@past3lle/components' import { MediaWidths, setBackgroundOrDefault, setBackgroundWithDPI, setFlickerAnimation, upToLarge, upToMedium, upToSmall } from '@past3lle/theme' import { GenericImageSrcSet } from '@past3lle/types' import styled from 'styled-components' import { CursiveHeader, MonospaceText } from '../../Common/Text' const DEFAULT_SIDE_PANEL_PROPS = { background: 'lightgrey', paddingMobile: '4rem 0', borderRadius: '0px', filter: 'none', flexDir: 'column' as RowProps['flexDirection'], flexWrap: 'nowrap' as RowProps['flexWrap'], padding: '4rem', transition: 'none', useMediaQueries: true, width: '40%', zIndex: 88 } export type SidePanelCssProps = Partial<typeof DEFAULT_SIDE_PANEL_PROPS> & { bgWithDpiOptions?: { bgSet: GenericImageSrcSet<MediaWidths> color?: string } showFlickerAnimation?: boolean } export const StyledSidePanel = styled(ArticleFadeIn)<SidePanelCssProps>` position: fixed; display: flex; flex-flow: ${({ flexWrap = DEFAULT_SIDE_PANEL_PROPS.flexWrap, flexDir = DEFAULT_SIDE_PANEL_PROPS.flexDir }) => `${flexDir} ${flexWrap}`}; z-index: ${({ zIndex = DEFAULT_SIDE_PANEL_PROPS.zIndex }) => zIndex}; background: ${({ background = DEFAULT_SIDE_PANEL_PROPS.background }) => background}; padding: ${({ padding = DEFAULT_SIDE_PANEL_PROPS.padding }) => padding}; width: ${({ width = DEFAULT_SIDE_PANEL_PROPS.width }) => width}; border-radius: ${({ borderRadius = DEFAULT_SIDE_PANEL_PROPS.borderRadius }) => borderRadius}; top: 0; right: 0; bottom: 0; height: 100%; filter: ${({ filter }) => filter}; transition: ${({ transition }) => transition}; > div#bg-tag { position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: -1; opacity: 0.4; ${({ showFlickerAnimation }) => showFlickerAnimation && setFlickerAnimation({ state: true, duration: 4, count: 2 })} ${({ theme, bgWithDpiOptions }) => bgWithDpiOptions ? setBackgroundWithDPI(theme, bgWithDpiOptions.bgSet, { preset: 'header', modeColours: [bgWithDpiOptions?.color || '#fff', '#fff'], backgroundAttributes: ['center / cover no-repeat', 'center 5px / cover no-repeat'], backgroundBlendMode: 'difference', lqIkUrlOptions: { dpi: '1x', transforms: [null, 'pr-true,q-2,w-50,h-700'] } }) : setBackgroundOrDefault( theme, { bgValue: theme.assetsMap.logos.company.full, defaultValue: 'lightgrey' }, { backgroundColor: 'lightgrey', backgroundAttributes: ['bottom/contain no-repeat'] } )} } ${CursiveHeader} { font-size: 5rem; } ${({ useMediaQueries = DEFAULT_SIDE_PANEL_PROPS.useMediaQueries }) => upToLarge` width: 50%; ${ useMediaQueries && ` ${CursiveHeader} { font-size: 4vw; } ` } `} ${upToMedium` width: 65%; `} ${({ useMediaQueries = DEFAULT_SIDE_PANEL_PROPS.useMediaQueries, paddingMobile = DEFAULT_SIDE_PANEL_PROPS.paddingMobile }) => upToSmall` width: 100%; padding: ${paddingMobile}; ${ useMediaQueries && ` ${CursiveHeader} { font-size: 4.2rem; } ` } `} ${MonospaceText} { font-size: 2rem; font-style: italic; text-align: left; } `
import { OpenAI } from "langchain/llms/openai"; import { createSqlAgent, SqlToolkit } from "langchain/agents/toolkits/sql"; import { SqlDatabase } from "langchain/sql_db"; import { DataSource } from "typeorm"; import * as dotenv from "dotenv"; import { SQL_PREFIX, SQL_SUFFIX } from "./prompt"; dotenv.config(); export const run = async (prompt: string) => { const datasource = new DataSource({ type: "postgres", host: process.env.DB_HOST, port: Number(process.env.DB_PORT), username: process.env.DB_USERNAME, password: process.env.DB_PASSWORD, database: process.env.DB_DATABASE, }); const db = await SqlDatabase.fromDataSourceParams({ appDataSource: datasource, }); const model = new OpenAI({ openAIApiKey: process.env.OPENAI_API_KEY, temperature: 0, }); const toolkit = new SqlToolkit(db, model); const executor = createSqlAgent(model, toolkit, { topK: 10, prefix: SQL_PREFIX, suffix: SQL_SUFFIX, }); try { const result = await executor.call({ input: prompt }); console.log(`RESPONSE: ${result.output}`); // console.log(`Intermediate steps ${JSON.stringify(result, null, 2)}`); result.intermediateSteps.forEach((step: any) => { console.log(step.action.toolInput); }); } catch (e) { console.log(e); } await datasource.destroy(); console.log("Closed connection with database."); };
package com.system.api.filter; import com.system.api.common.R; import com.system.api.util.JwtUtils; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; /** * @author zhangyongkai * @date 2024/2/20-14:34 */ @Component public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsService userDetailsService; private static final ObjectMapper mapper = new ObjectMapper(); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwtFromRequest(request); if (jwt != null && jwtUtils.validateToken(jwt)) { String username = jwtUtils.getUsernameFromJWT(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json"); response.getWriter().write(mapper.writeValueAsString(R.fail("失败"))); response.getWriter().flush(); } } catch (Exception ex) { // 如果认证失败,确保Spring知道认证状态 SecurityContextHolder.clearContext(); } filterChain.doFilter(request, response); } // Utility method to extract JWT from the Authorization header private String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } }
<!doctype html> <html lang="pl"> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="{{ $description ?? 'Fundacja Głos Młodych'}}"/> <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> <title> @isset($title) {{ $title }} @endisset </title> {{-- <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> --}} <link rel="icon" type="image/x-icon" href="/images/cropped-logo-32x32.webp"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js" defer></script> <script src="https://kit.fontawesome.com/d96bec4722.js" crossorigin="anonymous"></script> <script src="{{ asset('assets/vendor/ckeditor5/build/ckeditor.js') }}" type="text/javascript"></script> <script src="https://cdn.tailwindcss.com"></script> {{-- @vite('resources/css/app.css') --}} <style> html { scroll-behavior: smooth; } .clamp { display: -webkit-box; -webkit-box-orient: vertical; overflow: hidden; } .clamp.one-line { -webkit-line-clamp: 1; } </style> <body style="font-family: Open Sans, sans-serif"> <div class="px-2 lg:px-9"> <header class="max-w-full bg-white cursor-pointer"> <div class="flex justify-center items-center"> <a href="/"><img class="h-42" src="{{ asset('images/cropped-logo_fgm-2-1.png') }}" alt="Logo Fundacji"></a> </div> </header> <x-nav.mobile /> <nav class="hidden sticky top-0 z-50 md:block bg-black text-white min-h-14 lg:h-14"> <ul class="flex flex-row flex-wrap items-center align-middle justify-center text-sm text-nowrap py-auto h-full"> <x-nav.list-item route="/" name="STRONA GŁÓWNA" /> <li x-data="{ open: false }" @mouseover="open = true" @mouseout="open = false" class="z-50 box-border text-sm cursor-pointer transform duration-300 flex items-center h-full {{ request()->is('o-fundacji', 'statut-fundacji', 'zarzad-fundacji', 'cele-i-zasady-dzialania', 'dzialalnosc-gospodarcza', 'sprawozdania') ? '' : 'hover:bg-teal-300' }}"> <a href="/o-fundacji" class="block py-2 w-full h-full"> <p class="py-2 px-2">O FUNDACJI <i class="fa-solid fa-chevron-down fa-sm"></i></p> </a> <!-- Dropdown menu --> <x-dropdown> <x-nav.dropdown-item route="/statut-fundacji">STATUT FUNDACJI</x-nav.dropdown-item> <x-nav.dropdown-item route="/zarzad-fundacji">ZARZĄD FUNDACJI</x-nav.dropdown-item> <x-nav.dropdown-item route="/cele-i-zasady-dzialania">CELE I ZASADY DZIAŁANIA</x-nav.dropdown-item> <x-nav.dropdown-item route="/dzialalnosc-gospodarcza">DZIAŁALNOŚĆ GOSPODARCZA</x-nav.dropdown-item> <x-nav.dropdown-item route="/sprawozdania">SPRAWOZDANIA</x-nav.dropdown-item> </x-dropdown> </li> {{-- <li x-data="{ open: false }" @mouseover="open = true" @mouseout="open = false" class="z-50 box-border text-sm cursor-pointer transform duration-300 flex items-center h-full hover:bg-teal-300"> <a href="/#" class="block py-2 w-full h-full"> <p class="py-2 px-2">PRACOWNICY FUNDACJI <i class="fa-solid fa-chevron-down fa-sm"></i></p> </a> <x-dropdown> <li> <a href="#" class="block px-4 py-2 transform duration-200 hover:bg-teal-300"> <p class="py-2">SPECJALIŚCI FUNDACJI</p> </a> </li> <li> <a href="#" class="block px-4 py-2 transform duration-200 hover:bg-teal-300"> <p class="py-2">REDAKCJA PORTALU GLOSWSCHODU</p> </a> </li> </x-dropdown> </li> --}} {{-- <x-nav.list-item route="/pracownicy" name="PRACOWNICY FUNDACJI"/> --}} <x-nav.list-item route="/praktyki" name="PRAKTYKI" /> <x-nav.list-item route="/projekty" name="PROJEKTY" /> <x-nav.list-item route="/aktualnosci" name="AKTUALNOŚCI" /> <x-nav.list-item route="/galeria" name="GALERIA" /> <x-nav.list-item route="/kontakt" name="KONTAKT" /> <x-nav.list-item route="/opinie" name="OPINIE" /> </ul> </nav> {{ $slot }} <div class="h-128"> <footer class="h-auto my-5 bottom-0"> <div class="bg-cover bg-center h-full" style="background-image: url({{ asset('images/tlo1234.png') }});"> <div class="grid grid-cols-2 gap-4 text-white text-sm pb-4"> <div class="flex flex-wrap justify-center gap-4 italic mt-6"> <h2>Oświadczenie</h2> <h4 class="text-center">Niniejszym, w imieniu własnym oraz Fundacji na Rzecz Promocji i Rozwoju „ Głos Młodych” deklarujemy, że Fundacja przyjmuje i stosuje zasady równego traktowania. Prowadzi działalność wolną od dyskryminacji, w szczególności ze względu na takie cechy jak płeć, rasa (kolor skóry), pochodzenie etniczne, narodowość bądź wyznania religijne.</h4> <h5 class="ml-auto mr-24">Zarząd</h5> </div> <div class="flex-1 flex-wrap justify-self-center gap-4 italic relative"> <div> <img class="max-h-28 mx-auto" src="{{ asset('images/cropped-logo_fgm-2-1.png') }}" alt="Logo Fundacji"> </div> <div class="absolute w-full top-24"> <h2 class="text-center text-xs"><strong>Wsparcie</strong></h2> <h4 class="text-center text-xs"> Fundacja na Rzecz Promocji i Rozwoju „Głos Młodych” <br> Konto: Bank Pekao SA. Poznań ul. Masztalerska 8a <br> Nr Konta: <strong>92 1240 1763 1111 0010 7475 8053</strong> </h4> </div> </div> </div> </div> <div class="text-center text-gray-400 italic mt-12"> <a href="/" class="hover:text-blue-400">Copyright © <time>{{ date('Y') }}</time> Fundacja na rzecz promocji i rozwoju – Głos Młodych, Adrian Reszczyński and Dominik Głowacki<br> Witryna stworzona za pomocą Laravel</a> </div> <div class="flex flex-nowrap justify-center space-x-2.5 mt-11"> <a class="relative" href="https://www.facebook.com/Fundacja.Glos.Mlodych"> <img class="pointer-events-none relative z-10" src="{{ asset('images/Facebook.png') }}" alt="Nasz profil na facebook"> <div class="absolute top-0 left-0 bg-blue-600 rounded-sm h-full w-full transform duration-300 hover:rotate-90 hover:bg-cyan-400"> </div> </a> <a class="relative" href="https://twitter.com/Portal_e_magnes"> <img class="pointer-events-none relative z-10" src="{{ asset('images/Twitter.png') }}" alt="Twitter"> <div class="absolute top-0 left-0 bg-blue-600 rounded-sm h-full w-full transform duration-300 hover:rotate-90 hover:bg-cyan-400"> </div> </a> <a class="relative" href="mailto:[email protected]"> <img class="pointer-events-none relative z-10" src="{{ asset('images/Mail.png') }}" alt="Napisz do nas"> <div class="absolute top-0 left-0 bg-blue-600 rounded-sm h-full w-full transform duration-300 hover:rotate-90 hover:bg-cyan-400"> </div> </a> <a class="relative" href="/o-fundacji"> <img class="pointer-events-none relative z-10" src="{{ asset('images/AboutMe.png') }}" alt="AboutMe"> <div class="absolute top-0 left-0 bg-blue-600 rounded-sm h-full w-full transform duration-300 hover:rotate-90 hover:bg-cyan-400"> </div> </a> </div> </footer> </div> </div> </body> </html>
/* // // // //arquivo destinado apenas a estudo e refazer o curso do decola em flutter (ao termino sera excluido) //https://m3.material.io/develop/flutter // // import 'package:flutter/material.dart'; //import = importM + tab // void main(){ // int valor = 0; // runApp(MyApp(title: 'Ap ola mundo', valor: valor) // /* // MaterialApp( // home:Scaffold( //andaime -> appBar e body // appBar:AppBar ( // title:Text('ap ola mundo',style: TextStyle(fontSize: 40,color: Colors.redAccent.shade700),), // titulo // ), // body: //corpo // Center( // child:Text ('olá mundo', style: TextStyle(fontSize: 40, color: Colors.greenAccent.shade700)), // ), // ), // ), // */ // ); // valor++; // } // //estrutura basica do Flutter // class MyApp extends StatelessWidget { //statelassW + tab (statelassW é para uma tela estatica) // //são widgets que não mudao o estado da interface do usuario, // //mantendo a caracteristica do inicio ao fim da aplicação // //tendo apenas um objeto um widget // // final String title; //parametro para titulo // final int valor; // const MyApp({Key? key, this.title = '', this.valor = 0}): super(key:key); // atenção nessa parte //parametro setado // @override // Widget build(BuildContext context) { // variaveis de contexto // return MaterialApp( // home:Scaffold( //andaime -> appBar e body // appBar:AppBar ( // title:Text(this.title,style: TextStyle(fontSize: 40,color: Colors.redAccent.shade700),), // titulo // ), // body: //corpo // Center( // child:Text ('olá mundo o valor é = ' + this.valor.toString(), style: TextStyle(fontSize: 40, color: Colors.greenAccent.shade700)), // ), // ), // ); // } // } void main(){ runApp(MyApp(nome: 'Pedro')); } class MyApp extends StatefulWidget {//Ja o stateful Widget, eles mudam o // estado da interface durante a aplicação // //neste caso vai ter dois objetos final String nome; //<------------- nome aqui const MyApp({Key? key, this.nome = ''}): super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int salario = 5000; void aumentaSlaraio(int valor){ setState(() { this.salario = this.salario +valor; }); } void diminuiSlaraio(int valor){ setState(() { this.salario = this.salario +valor; }); } @override Widget build(BuildContext context) { return Center(// aqui pode ser Container ou Material neste caso é Center para Centralizar o Texto child: GestureDetector(//vai detectar intereções na tela onTap: (){ aumentaSlaraio(2000); // setState((){//para atualizar na tela // salario = salario +100; // }); }, child: Text( //antes do "Text" apertar Ctrl + . para abrir um menu (Wrap whith widget) // vai adicionar uma estrutura de Widget 'alguma coisa ${widget.nome} é $salario',textDirection: TextDirection.ltr,), ), // para referenciar o nome precisa puxar o Widget // ja o salario por estar dentro da mesma classe pode ser puxado sem o widget //tambem foi dado o TextDirection para direcionar o texto ); } } */ // import 'package:flutter/material.dart'; // // primarySwatch: Colors.blue, é basicamente o tema do App // void main(){ // runApp(MyApp()); // } // class MyApp extends StatefulWidget { // const MyApp({Key? key}): super(key: key); // @override // State<MyApp> createState() => _MyAppState(); // } // class _MyAppState extends State<MyApp> { // @override // Widget build(BuildContext context) { // return MaterialApp( // home: Scaffold( // appBar: AppBar( // title: Text('Titulo App'), // ), // body: Center( // child:Column( //Colunm é tudo na coluna // mainAxisAlignment: MainAxisAlignment.spaceAround, // // Row( //Row é tudo na mesma linha // // mainAxisAlignment: MainAxisAlignment.spaceAround, //alinhamento do Row // children: [ // Center( // child:Text( // 'Texto 1', // style: TextStyle( // fontSize: 25), // ), // ), // Center( // child:Text( // 'Texto 2', // style: TextStyle( // fontSize: 25), // ), // ), // Center( // child:Text( // 'Texto 3', // style: TextStyle( // fontSize: 25), // ), // ), // ] // )), // ), // ); // } // } // import 'package:flutter/material.dart'; // void main(){ // runApp(Myapp()); // } // class Myapp extends StatelessWidget { // const Myapp({Key? key}): super(key: key); // @override // Widget build(BuildContext context) { // return Container( // child: Center( // child: Text( // 'texto', // textDirection: TextDirection.ltr, // style: TextStyle( // fontSize: 50, // fontWeight: FontWeight.normal, // color: Colors.yellowAccent.shade700, // ), // ), // ), // ); // // } // // } // import 'package:flutter/material.dart'; // void main() { // runApp(MyApp()); // } // class MyApp extends StatefulWidget { // const MyApp({Key? key}) : super(key: key); // @override // State<MyApp> createState() => _MyAppState(); // } // class _MyAppState extends State<MyApp> { // List<String> listaProdutos = []; // @override // void initState() { // super.initState(); // for (int i = 1; i <= 100; i++) { // listaProdutos.add('P $i'); // } // } // @override // Widget build(BuildContext context) { // return MaterialApp( // home: Scaffold( // appBar: AppBar( // title: Text('List View'), // ), // body: ListView.builder( // reverse: false, //deixar a lista invertida caso true // itemCount: listaProdutos.length, // itemBuilder: (context, indice) { // return ListTile( // title: Text('${listaProdutos[indice]}'), // ); // }, // ), // ), // ); // } // } ///Text fild /// /// // import 'package:flutter/material.dart'; // enum Genero{ // Masculino, // Feminino, // Outro // } // void main() { // runApp(MyApp()); // } // class MyApp extends StatefulWidget { // const MyApp({Key? key}) : super(key: key); // @override // State<MyApp> createState() => _MyAppState(); // } // class _MyAppState extends State<MyApp> { // String email = ''; // String senha = ''; // bool termos = false; // Genero genero = Genero.Masculino; // @override // Widget build(BuildContext context) { // return MaterialApp( // home: Scaffold( // appBar: AppBar( // title: Text('Página de cadastro'), // ), // body: Padding( // padding: const EdgeInsets.all(40.0), // antes do Column foi dado um CTRL + . para criar a padding // child: Column( // mainAxisAlignment: MainAxisAlignment.spaceAround, // crossAxisAlignment: CrossAxisAlignment.stretch, // estica o Botão para a tela inteira // children: [ // Text( // 'Insira seus dados', // style: TextStyle(fontSize: 20), // ), // // TextField(), // aqui para escrever na tela // // Text('Email'), // TextField( // decoration: InputDecoration( // labelText: 'E-mail' // a escrita email fica dentro // ), // onChanged: (text) { // if (text.contains('@')) { // email = text; // armazenar o email // } // }, // ), // // Text('Senha'), // TextField( // obscureText: true, // formulário de senha não mostra a senha // decoration: InputDecoration( // labelText: 'Senha', // ), // onChanged: (text) { // senha = text; // armazenar a senha // }, // ), // // Radio(value: genero, // // groupValue: genero, // // onChanged: (Genero generoSelecionado){ // // setState((){ // // genero = generoSelecionado; // // }); // // }, // // ), // Row( // children: [ // Checkbox( // value: termos, // checkbox // onChanged: (checked) { // setState(() { // termos = checked ?? false; // atualizar termos // }); // }, // ), // Text('Concordo'), // ], // ), // // Text('esqueceu a senha ?'), // ElevatedButton( // onPressed: () { // if (termos && email.isNotEmpty && senha.isNotEmpty) { // // lógica para o botão Entrar // print('Email: $email, Senha: $senha'); // } else { // // lógica de validação // print('Preencha todos os campos e aceite os termos.'); // } // }, // child: Text('Entrar'), // ), // ], // ), // ), // ), // ); // } // } /// /// // import 'package:flutter/material.dart'; // void main(){ // runApp(MyApp()); // } // class Argumentos{ //transição de dados entre telas // final int id; // final String nome; // Argumentos(this.id,this.nome); // } // class MyApp extends StatelessWidget { // const MyApp({Key? key}):super(key: key); // static const routeName = '/tela2'; //transição de dados entre telas // @override // Widget build(BuildContext context) { // final argumentos = ModalRoute.of(context)!.settings.arguments as Argumentos; //transição de dados entre telas // return MaterialApp( // home:Tela1(), // routes:{ // '/tela1' : (context) => Tela1(), //rotas nomiadas, sempre utilizar // //Tela2.routeName:(context) => Tela2(), //transição de dados entre telas // '/tela2' : (context) => Tela2() // } // ); // } // } // class Tela1 extends StatelessWidget { // const Tela1({Key? key}): super(key: key); // @override // Widget build(BuildContext context) { // return Container( // child: MaterialApp( // home: Scaffold( // appBar:AppBar( // title:Text('Tela1'), // backgroundColor: Colors.greenAccent.shade700 // ), // body:Center( // child: ElevatedButton( // child: Text('ir tela2'), // onPressed: (){ // Navigator.pushNamed(context, '/tela2'); // }, // /* // onPressed: () { Navigator.push(context, ////aqui navega entre telas utilizando o push // MaterialPageRoute( // builder: (context){return Tela2(); // }, // )); // }, // */ // ), // ), // ), // ), // ); // } // } // class Tela2 extends StatelessWidget { // const Tela2({Key? key}): super(key: key); // @override // Widget build(BuildContext context) { // return Container( // child: MaterialApp( // home: Scaffold( // appBar:AppBar( // title:Text('Tela2'), // backgroundColor: Colors.redAccent.shade700, // ), // body:Center( // child: ElevatedButton( // child: Text('retornar a tela1'), // onPressed: (){ // Navigator.pushNamed(context, '/tela1'); // }, // //onPressed: () { Navigator.pop(context);} ////aqui navega entre telas utilizando o pop // ), // ), // ), // ), // ); // } // } //trabalhando com async import 'dart:async'; import 'package:flutter/material.dart'; void main(){ /* Future<void> quatro = Future.delayed( Duration(seconds: 3)); quatro.then((value) =>print(4)); */ print(1); print(2); print(3); } Future<void> quatro() async{ Future.delayed(Duration(seconds: 10),() => print(4)); } //https://pub.dev/ // assistir com calma sobre o Radio //!!!!! //aula | | | // V V V //Fluter Lista de Produtos
const swaggerDocument = { "openapi": "3.0.0", "info": { "title": "Digital Certificate Indexer API", "version": "1.0.0", "description": "API for indexing digital certificate data using Pinecone and Langchain." }, "paths": { "/certificates-free": { "post": { "summary": "Index a new digital certificate", "description": "Adds a new digital certificate to the Pinecone index.", "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "recipientName": { "type": "string" }, "recipientEmail": { "type": "string" }, "courseName": { "type": "string" }, "courseDescription": { "type": "string" }, "issueDate": { "type": "string" }, "pdfUrl": { "type": "string" }, "pngUrl": { "type": "string" } }, "required": ["recipientName", "recipientEmail", "courseName", "issueDate", "pdfUrl", "pngUrl"] } } } }, "responses": { "200": { "description": "Successful Operation" }, "400": { "description": "Invalid input" } } } }, "/query-certificates-free": { "get": { "summary": "Query a digital certificate", "description": "Query a digital certificate in the Pinecone index.", "parameters": [ { "in": "query", "name": "text", "required": false, "schema": { "type": "string" }, "description": "Text content of the digital certificate to be indexed." } ], "requestBody": { }, "responses": { "200": { "description": "Successful Operation" }, "400": { "description": "Invalid input" } } } } } } export default swaggerDocument;
<?php namespace Transave\ScolaBookstore\Actions\Auth; use Carbon\Carbon; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Notification; use Transave\ScolaBookstore\Http\Models\User; use Transave\ScolaBookstore\Helpers\ResponseHelper; use Transave\ScolaBookstore\Helpers\ValidationHelper; use Transave\ScolaBookstore\Http\Notifications\WelcomeNotification; class Register { use ValidationHelper, ResponseHelper; private array $request; private array $validatedInput; private User $user; public function __construct(array $request) { $this->request = $request; } public function execute() { try{ return $this ->validateRequest() ->setUserPassword() ->setVerificationToken() ->setUserType() ->createUser() ->sendNotification() ->sendSuccess($this->user, 'account created successfully'); }catch (\Exception $exception){ return $this->sendServerError($exception); } } private function setUserPassword(): self { $this->validatedInput['password'] = bcrypt($this->validatedInput['password']); return $this; } private function createUser(): self { $this->user = User::query()->create($this->validatedInput); return $this; } private function setUserType(): self { if (isset($this->validatedInput['role']) && in_array($this->validatedInput['role'], ['superAdmin', 'admin', 'publisher', 'user'])) { $this->validatedInput['role'] = $this->validatedInput['role']; } else { $this->validatedInput['role'] = 'user'; } return $this; } private function setVerificationToken(): self { $this->validatedInput['verification_token'] = rand(100000, 999999); $this->validatedInput['email_verified_at'] = Carbon::now(); return $this; } private function sendNotification() { try { Notification::route('mail', $this->user->email) ->notify(new WelcomeNotification([ "token" => $this->validatedInput['verification_token'], "user" => $this->user ])); } catch (\Exception $exception) { } return $this; } public function validateRequest(): self { $data = $this->validate($this->request, [ 'first_name' => ['required', 'string', 'max:255'], 'last_name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'unique:users'], 'role' => ['string', 'in:superAdmin,admin,publisher,user'], 'password' => ['required', 'string'], ]); $this->validatedInput = Arr::only($data, ['first_name', 'last_name', 'email', 'role', 'password']); return $this; } }
package com.lms.worldoflol.common import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibilityScope import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.lms.worldoflol.R import com.lms.worldoflol.ui.theme.textStyle16 import com.lms.worldoflol.ui.theme.textStyle24 import com.lms.worldoflol.utils.backgroundWithBorder @Composable fun NoInternetConnectionScreen(onRefresh: () -> Unit) { Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight() .background(Color(0xFF242731)) .padding(horizontal = 40.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(text = "Whoops!", style = textStyle24(color = 0xFFF6C97F, fontWeight = 700)) Spacer(modifier = Modifier.height(25.dp)) Text( text = "Slow or no internet connection", style = textStyle16( color = 0x80EEE2CC, textAlign = TextAlign.Center ) ) Text( text = "Please check your internet settings.", style = textStyle16( color = 0x80EEE2CC, textAlign = TextAlign.Center ) ) Spacer(modifier = Modifier.height(40.dp)) Image( modifier = Modifier .size(width = 170.dp, height = 146.dp) .aspectRatio(1f), contentScale = ContentScale.FillBounds, painter = painterResource(id = R.drawable.ic_error), contentDescription = "", ) Spacer(modifier = Modifier.height(50.dp)) RefreshButton { onRefresh() } } } @Composable private fun RefreshButton(onClick: () -> Unit = { }) { Box( modifier = Modifier .height(55.dp) .width(140.dp) .backgroundWithBorder( backgroundColors = arrayListOf(0x660E141B, 0x99242731), borderGradientColors = 0x66CA9D4B ) .clickable { onClick() }, contentAlignment = Alignment.Center ) { Text( text = "Refresh", style = textStyle16(color = 0xB3EEE2CC) ) } } @Preview @Composable fun ErrorScreenPreview() { NoInternetConnectionScreen {} }
import copy import itertools import typing import ConfigSpace import numpy as np import pandas as pd import scipy.stats import sklearn.ensemble import sklearn.linear_model import sklearn.preprocessing class AbstractSelector: def fit( self, X: pd.DataFrame, y: pd.DataFrame, minima: typing.Dict[int, typing.Dict[str, float]], maxima: typing.Dict[int, typing.Dict[str, float]], ) -> None: raise NotImplementedError() def predict(self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame] = None) -> pd.DataFrame: prediction = self._predict(X, y) for col, series in prediction.iteritems(): assert series.dtype == float, (col, series) np.testing.assert_array_almost_equal( prediction.sum(axis='columns').to_numpy(), np.ones(X.shape[0]), err_msg=prediction.to_csv(), ) return prediction def _predict(self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame]) -> pd.DataFrame: raise NotImplementedError() class RandomSelector(AbstractSelector): def __init__(self, random_state): self.random_state = random_state def fit( self, X: pd.DataFrame, y: pd.DataFrame, minima: typing.Dict[int, typing.Dict[str, float]], maxima: typing.Dict[int, typing.Dict[str, float]], ) -> None: self.strategies_ = y.columns def _predict(self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame]) -> pd.DataFrame: if y is not None: raise ValueError("y must not be provided") rval = { task_id: { strategy: 1 if idx == strategy_idx else 0 for strategy_idx, strategy in enumerate(self.strategies_) } for task_id, idx in zip( X.index, self.random_state.randint(0, len(self.strategies_), size=X.shape[0]) ) } rval = pd.DataFrame(rval).transpose().astype(float) rval = rval[self.strategies_] rval = rval.fillna(0) return rval class SingleBest(AbstractSelector): def __init__(self, loss_function, random_state): self.loss_function = loss_function self.random_state = random_state def _get_prediction(self, X: pd.DataFrame, selection: np.ndarray) -> pd.DataFrame: rval = { task_id: { strategy: value for strategy, value in zip(self.strategies_, selection) } for task_id in X.index } rval = pd.DataFrame(rval).transpose().astype(float) rval = rval[self.strategies_] rval = rval.fillna(0) return rval def fit( self, X: pd.DataFrame, y: pd.DataFrame, minima: typing.Dict[int, typing.Dict[str, float]], maxima: typing.Dict[int, typing.Dict[str, float]], ) -> None: self.strategies_ = y.columns regrets = [ self.loss_function( y, self._get_prediction(X, np.eye(len(self.strategies_), dtype=float)[i]), nan_strategy='ones' ) for i, strategy in enumerate(self.strategies_) ] rank = scipy.stats.rankdata(regrets) self.selection_ = (len(self.strategies_) - rank) / (len(self.strategies_) - 1) self.selection_ = np.array(self.selection_) / np.sum(self.selection_) def _predict(self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame]) -> pd.DataFrame: if y is not None: raise ValueError("y must not be provided") return self._get_prediction(X, self.selection_) def __getstate__(self) -> typing.Dict[str, typing.Any]: rval = { 'random_state': self.random_state, 'loss_function': None, } for attr in ('strategies_', 'selection_'): if hasattr(self, attr): rval[attr] = getattr(self, attr) return rval class OracleSelector(AbstractSelector): def __init__(self, random_state): self.random_state = random_state def fit( self, X: pd.DataFrame, y: pd.DataFrame, minima: typing.Dict[int, typing.Dict[str, float]], maxima: typing.Dict[int, typing.Dict[str, float]], ) -> None: self.strategies_ = y.columns def _predict(self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame]) -> pd.DataFrame: rval = { task_id: { strategy: value for strategy, value in zip( self.strategies_, (len(y_row) - scipy.stats.rankdata(y_row)) / (len(y_row) - 1) ) } for task_id, y_row in y.iterrows() } rval = pd.DataFrame(rval).astype(float) rval = rval / rval.sum() rval = rval.transpose() rval = rval[self.strategies_] rval = rval.fillna(0) return rval class OneVSOneSelector(AbstractSelector): def __init__(self, configuration, random_state, tie_break_order): self.configuration = configuration.get_dictionary() self.single_strategy_idx = None self.rng = random_state self.tie_break_order = tie_break_order self.models = None self.target_indices = None self.selectors_ = None self.weights_ = {} self.strategies_ = None def fit( self, X: pd.DataFrame, y: pd.DataFrame, minima: typing.Dict[int, typing.Dict[str, float]], maxima: typing.Dict[int, typing.Dict[str, float]], ) -> None: self.maxima = copy.deepcopy(maxima) target_indices = np.array(list(range(y.shape[1]))) models = dict() weights = dict() self.strategies_ = copy.deepcopy(y.columns.to_list()) y_pd = y.copy() y = y.to_numpy() for i in range(len(target_indices)): models[i] = dict() weights[i] = dict() for j in range(i + 1, len(target_indices)): if self.configuration['normalization'] in ('all', 'binary', 'y', 'all1', 'binary1'): minimum2 = np.ones(len(X)) * np.inf maximum2 = np.zeros(len(X)) if self.configuration['normalization'] in ('all', 'all1'): for idx, task_id in enumerate(X.index): for method_id in range(len(target_indices)): minimum2[idx] = np.nanmin(( minimum2[idx], minima[task_id][self.strategies_[method_id]] )) maximum2[idx] = np.nanmax(( maximum2[idx], maxima[task_id][self.strategies_[method_id]] )) if self.configuration['normalization'] == 'all1': maximum2 = np.ones_like(maximum2) elif self.configuration['normalization'] in ('binary', 'binary1'): for idx, task_id in enumerate(X.index): for method_id in (i, j): minimum2[idx] = np.nanmin(( minimum2[idx], minima[task_id][self.strategies_[method_id]] )) maximum2[idx] = np.nanmax(( maximum2[idx], maxima[task_id][self.strategies_[method_id]] )) if self.configuration['normalization'] == 'binary1': maximum2 = np.ones_like(maximum2) elif self.configuration['normalization'] == 'y': for idx, task_id in enumerate(X.index): minimum2[idx] = np.nanmin((minimum2[idx], y_pd.loc[task_id].min())) maximum2[idx] = np.nanmax((maximum2[idx], y_pd.loc[task_id].max())) else: raise ValueError(self.configuration['normalization']) y_i_j = y[:, i] < y[:, j] mask = np.isfinite(y[:, i]) & np.isfinite(y[:, j]) X_ = X.to_numpy()[mask] y_i_j = y_i_j[mask] minimum = minimum2[mask] maximum = maximum2[mask] diff = maximum - minimum diff[diff == 0] = 1 normalized_y_i = (y[:, i][mask].copy() - minimum) / diff normalized_y_j = (y[:, j][mask].copy() - minimum) / diff weights_i_j = np.abs(normalized_y_i - normalized_y_j) elif self.configuration['normalization'] == 'rank': y_i_j = y[:, i] < y[:, j] mask = np.isfinite(y[:, i]) & np.isfinite(y[:, j]) X_ = X.to_numpy()[mask] y_i_j = y_i_j[mask] ranks = scipy.stats.rankdata(y[mask], axis=1) weights_i_j = np.abs(ranks[:, i] - ranks[:, j]) elif self.configuration['normalization'] == 'None': y_i_j = y[:, i] < y[:, j] mask = np.isfinite(y[:, i]) & np.isfinite(y[:, j]) X_ = X.to_numpy()[mask] y_i_j = y_i_j[mask] weights_i_j = np.ones_like(y_i_j).astype(int) else: raise ValueError(self.configuration['normalization']) if len(y_i_j) == 0: models[i][j] = None weights[i][j] = None continue if np.all([target == y_i_j[0] for target in y_i_j]): n_zeros = int(np.ceil(len(y_i_j) / 2)) n_ones = int(np.floor(len(y_i_j) / 2)) import sklearn.dummy base_model = sklearn.dummy.DummyClassifier(strategy='constant', constant=y_i_j[0]) base_model.fit( X_, np.array(([[0]] * n_zeros) + ([[1]] * n_ones)).flatten(), sample_weight=weights_i_j, ) else: if self.configuration.get('max_depth') == 0: import sklearn.dummy loss_i = np.sum((y_i_j == 0) * weights_i_j) loss_j = np.sum((y_i_j == 1) * weights_i_j) # regret_i = np.mean(normalized_y_i) # regret_j = np.mean(normalized_y_j) # if ((loss_i < loss_j) != (regret_i < regret_j)) or ((loss_i > loss_j) != (regret_i > regret_j)): # print( # self.strategies_[i], self.strategies_[j], # loss_i, loss_j, loss_i < loss_j, regret_i < regret_j, # loss_i > loss_j, regret_i > regret_j # ) base_model = sklearn.dummy.DummyClassifier( strategy='constant', constant=1 if loss_i < loss_j else 0, ) base_model.fit( X_, np.ones_like(y_i_j) * int(loss_i < loss_j), sample_weight=weights_i_j, ) else: base_model = self.fit_pairwise_model( X_, y_i_j, weights_i_j, self.rng, self.configuration, ) models[i][j] = base_model weights[i][j] = weights_i_j self.models = models self.weights_ = weights self.target_indices = target_indices def _predict(self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame]) -> pd.DataFrame: if y is not None: raise ValueError("y must not be provided") raw_predictions = dict() raw_probas = dict() for i in range(len(self.target_indices)): for j in range(i + 1, len(self.target_indices)): if self.models[i][j] is not None: raw_predictions[(i, j)] = self.models[i][j].predict(X) raw_probas[(i, j)] = self.models[i][j].predict_proba(X) if len(raw_predictions) == 0: predictions = pd.DataFrame(0, index=X.index, columns=self.strategies_).astype(float) predictions.iloc[:, self.single_strategy_idx] = 1.0 return predictions predictions = {} for x_idx in range(X.shape[0]): wins = np.zeros(self.target_indices.shape) for i in range(len(self.target_indices)): for j in range(i + 1, len(self.target_indices)): if (i, j) in raw_predictions: if self.configuration['prediction'] == 'soft': if raw_probas[(i, j)].shape[1] == 1: proba = raw_probas[(i, j)][x_idx][0] else: proba = raw_probas[(i, j)][x_idx][1] wins[i] += proba wins[j] += 1 - proba elif self.configuration['prediction'] == 'hard': prediction = raw_predictions[(i, j)][x_idx] if prediction == 1: wins[i] += 1 else: wins[j] += 1 else: raise ValueError(self.configuration['prediction']) n_prev = np.inf # Tie breaking while True: most_wins = np.max(wins) most_wins_mask = most_wins == wins if n_prev == np.sum(most_wins_mask): n_prev = np.sum(most_wins_mask) hit = False for method in self.tie_break_order: if method not in self.strategies_: continue method_idx = self.strategies_.index(method) if most_wins_mask[method_idx]: wins[method_idx] += 1 hit = True break if not hit: wins[int(self.rng.choice(np.argwhere(most_wins_mask).flatten()))] += 1 elif np.sum(most_wins_mask) > 1: n_prev = np.sum(most_wins_mask) where = np.argwhere(most_wins_mask).flatten() for i, j in itertools.combinations(where, 2): if (i, j) in raw_predictions: prediction = raw_predictions[(i, j)][x_idx] if prediction == 1: wins[i] += 1 else: wins[j] += 1 else: method_i = self.strategies_[i] method_j = self.strategies_[j] if self.tie_break_order.index(method_i) < self.tie_break_order.index(method_j): wins[i] += 1 else: wins[j] += 1 else: break wins = wins / np.sum(wins) predictions[X.index[x_idx]] = wins rval = { task_id: { strategy: predictions[task_id][strategy_idx] for strategy_idx, strategy in enumerate(self.strategies_) } for task_id in X.index } rval = pd.DataFrame(rval).transpose().astype(float) rval = rval[self.strategies_] rval = rval.fillna(0.0) return rval def fit_pairwise_model(self, X, y, weights, rng, configuration): raise NotImplementedError() @staticmethod def get_configuration_space(n_features): raise NotImplementedError() class OVORF(OneVSOneSelector): def __init__(self, n_estimators, **kwargs): super().__init__(**kwargs) self.n_estimators = n_estimators def fit_pairwise_model(self, X, y, weights, rng, configuration): base_model = sklearn.ensemble.RandomForestClassifier( random_state=rng, n_estimators=self.n_estimators, bootstrap=True if configuration['bootstrap'] == 'True' else False, min_samples_split=configuration['min_samples_split'], min_samples_leaf=configuration['min_samples_leaf'], max_features=int(configuration['max_features']), max_depth=configuration['max_depth'], ) base_model.fit(X, y, sample_weight=weights) return base_model @staticmethod def get_configuration_space(n_features) -> ConfigSpace.ConfigurationSpace: cs = ConfigSpace.ConfigurationSpace() cs.add_hyperparameter( ConfigSpace.UniformIntegerHyperparameter('min_samples_split', 3, 20, log=True, default_value=5) ) # The lower bound is 2 to avoid drastic overfitting cs.add_hyperparameter( ConfigSpace.UniformIntegerHyperparameter('min_samples_leaf', 2, 20, log=True, default_value=5) ) cs.add_hyperparameter( ConfigSpace.UniformIntegerHyperparameter('max_depth', 0, 20, default_value=0) ) cs.add_hyperparameter( ConfigSpace.UniformIntegerHyperparameter('max_features', 1, n_features) ) cs.add_hyperparameter( ConfigSpace.CategoricalHyperparameter('bootstrap', ["True", "False"]) ) cs.add_hyperparameter( ConfigSpace.CategoricalHyperparameter( 'normalization', ["all", "all1", "binary", "binary1", "y", "rank", "None"], ) ) cs.add_hyperparameter( ConfigSpace.CategoricalHyperparameter('prediction', ['hard', 'soft']) ) return cs class FallbackWrapper(AbstractSelector): def __init__(self, selector, default_strategies: typing.List[str]): self.selector = selector self.default_strategies = default_strategies def fit( self, X: pd.DataFrame, y: pd.DataFrame, minima: typing.Dict[int, typing.Dict[str, float]], maxima: typing.Dict[int, typing.Dict[str, float]], ) -> None: self.X_ = X self.strategies_ = y.columns self.rval_ = np.array([ (len(self.strategies_) - self.default_strategies.index(strategy) - 1) / (len(self.strategies_) - 1) for strategy in self.strategies_ ]) self.rval_ = self.rval_ / np.sum(self.rval_) self.selector.fit(X, y, minima, maxima) def _predict(self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame]) -> pd.DataFrame: if y is not None: prediction = self.selector.predict(X, y) else: prediction = self.selector.predict(X) for task_id, x in X.iterrows(): counter = 0 te = x.copy() assert len(te) == self.X_.shape[1] for _, tr in self.X_.iterrows(): tr = tr.to_numpy() if all([tr[i] >= te[i] for i in range(self.X_.shape[1])]): counter += 1 if counter == 0: prediction.loc[task_id] = pd.Series({ strategy: value for strategy, value in zip(self.strategies_, self.rval_) }) return prediction def prune_ovo_selector(selector, mask): for i in range(len(mask)): for j in range(len(mask)): if not mask[i] or not mask[j]: if isinstance(selector, FallbackWrapper): selector.selector.models[i][j] = None selector.selector.weights_[i][j] = None else: selector.models[i][j] = None selector.weights_[i][j] = None if np.sum(mask) == 1: if isinstance(selector, FallbackWrapper): selector.selector.single_strategy_idx = np.argmax(mask) print('Single strategy idx', selector.selector.single_strategy_idx) else: selector.single_strategy_idx = np.argmax(mask) print('Single strategy idx', selector.single_strategy_idx) return selector
import { InvalidParamError } from '../../errors' import { EmailValidation } from './email-validation' import { EmailValidator } from '../../protocols/email-validator' const makeEmailValidator = (): EmailValidator => { // tslint:disable-next-line: max-classes-per-file class EmailValidatorStub implements EmailValidator { isValid (email: string): boolean { return true } } return new EmailValidatorStub() } interface SutTypes { sut: EmailValidation emailValidatorStub: EmailValidator } const makeSut = (): SutTypes => { const emailValidatorStub = makeEmailValidator() const sut = new EmailValidation(emailValidatorStub, 'email') return { emailValidatorStub, sut } } describe('EmailValidation suite', () => { test('should return as error if email validator returns false', () => { const { sut, emailValidatorStub } = makeSut() jest.spyOn(emailValidatorStub, 'isValid').mockReturnValueOnce(false) const error = sut.validate({ email: '[email protected]' }) expect(error).toEqual(new InvalidParamError('email')) }) test('should call email validator with correct email',async () => { const { sut, emailValidatorStub } = makeSut() const isValidSpy = jest.spyOn(emailValidatorStub, 'isValid') sut.validate({ email: '[email protected]' }) expect(isValidSpy).toHaveBeenCalledWith('[email protected]') }) test('should throw if email validator throws',async () => { // const addAccountStub = makeAddAccount() const { sut, emailValidatorStub } = makeSut() jest.spyOn(emailValidatorStub, 'isValid').mockImplementationOnce(() => { throw new Error() }) expect(sut.validate).toThrow() }) })
<?php namespace Database\Seeders; use Carbon\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class PretensionSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $pretensiones = [ ['pre_id' => '01', 'pre_nombre' => 'AFP - Pagos'], ['pre_id' => '02', 'pre_nombre' => 'Aplicación de la Ley 31542'], ['pre_id' => '03', 'pre_nombre' => 'Beneficios sociales'], ['pre_id' => '04', 'pre_nombre' => 'Bonificación por 25 y 30 años'], ['pre_id' => '05', 'pre_nombre' => 'CAFAE'], ['pre_id' => '06', 'pre_nombre' => 'FONAVI – 10%'], ['pre_id' => '07', 'pre_nombre' => 'Homologación'], ['pre_id' => '08', 'pre_nombre' => 'Impugnación de sanción administrativa'], ['pre_id' => '09', 'pre_nombre' => 'Impugnación de sanción docente'], ['pre_id' => '10', 'pre_nombre' => 'Inclusión a planillas'], ['pre_id' => '11', 'pre_nombre' => 'Indemnización'], ['pre_id' => '12', 'pre_nombre' => 'Inaplicación de Ley 31364'], ['pre_id' => '13', 'pre_nombre' => 'O.D.S.D'], ['pre_id' => '14', 'pre_nombre' => 'Quinquenios'], ['pre_id' => '15', 'pre_nombre' => 'Racionamiento'], ['pre_id' => '16', 'pre_nombre' => 'Reconocimiento de ascenso docente'], ['pre_id' => '17', 'pre_nombre' => 'Refrigerio y Movilidad'], ['pre_id' => '18', 'pre_nombre' => 'Reposición y otros'], ['pre_id' => '19', 'pre_nombre' => 'Subsidio por luto y fallecimiento'], ['pre_id' => '20', 'pre_nombre' => 'Otros'], ]; $currentTimestamp = Carbon::now(); foreach($pretensiones as &$pretension){ // $pretension['pre_nombre'] = mb_strtoupper($pretension['pre_nombre']); $pretension['created_at'] = $currentTimestamp; $pretension['updated_at'] = $currentTimestamp; } DB::table('claims')->insert($pretensiones); } }
/* * Copyright 2002-2019 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.resource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Unit tests for {@link FixedVersionStrategy}. * * @author Brian Clozel * @author Rossen Stoyanchev */ public class FixedVersionStrategyTests { private static final String VERSION = "1df341f"; private static final String PATH = "js/foo.js"; private FixedVersionStrategy strategy; @BeforeEach public void setup() { this.strategy = new FixedVersionStrategy(VERSION); } @Test public void emptyPrefixVersion() { assertThatIllegalArgumentException().isThrownBy(() -> new FixedVersionStrategy(" ")); } @Test public void extractVersion() { assertThat(this.strategy.extractVersion(VERSION + "/" + PATH)).isEqualTo(VERSION); assertThat(this.strategy.extractVersion(PATH)).isNull(); } @Test public void removeVersion() { assertThat(this.strategy.removeVersion(VERSION + "/" + PATH, VERSION)).isEqualTo(("/" + PATH)); } @Test public void addVersion() { assertThat(this.strategy.addVersion("/" + PATH, VERSION)).isEqualTo((VERSION + "/" + PATH)); } @Test // SPR-13727 public void addVersionRelativePath() { String relativePath = "../" + PATH; assertThat(this.strategy.addVersion(relativePath, VERSION)).isEqualTo(relativePath); } }
import React from 'react' import styles from './button.module.scss' import FilterListIcon from '@mui/icons-material/FilterList' import AddIcon from '@mui/icons-material/Add' import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight' import { Close } from '@mui/icons-material' type Props = { text: string type: 'logout' | 'kanban' | 'primary' | 'secondary' | 'cancel' icon?: 'filter' | 'add' | 'close' | 'right' size: 'small' | 'medium' | 'large' invert?: boolean disabled?: boolean action: () => void } const Button: React.FC<Props> = ({ text, type, icon, size, invert, disabled, action }: Props) => { return ( <button className={`${styles.button} ${styles[type]} ${styles[size]} ${invert && styles.right}`} disabled={disabled} onClick={() => { action() }}> { icon === 'filter' && ( <FilterListIcon /> ) } { icon === 'add' && ( <AddIcon /> ) } { icon === 'close' && ( <Close /> ) } { icon === 'right' && ( <KeyboardArrowRightIcon /> ) } <span>{text}</span> </button> ) } export default Button
#!/usr/bin/python3 """ A function that returns an object (Python data structure) represented by a JSON string """ def from_json_string(my_str): """ Deserialize a JSON-formatted string and return the corresponding Python data structure. :param my_str: A JSON-formatted string. :return: A Python data structure representing the deserialized object. """ import json return json.loads(my_str)
/* * * Copyright 2021-2023 Software Radio Systems Limited * * This file is part of srsRAN. * * srsRAN is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * srsRAN is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * A copy of the GNU Affero General Public License can be found in * the LICENSE file in the top-level directory of this distribution * and at http://www.gnu.org/licenses/. * */ /// \file /// \brief PUSCH demodulator interface. #pragma once #include "srsran/adt/optional.h" #include "srsran/phy/upper/channel_estimation.h" #include "srsran/phy/upper/dmrs_mapping.h" #include "srsran/phy/upper/log_likelihood_ratio.h" #include "srsran/phy/upper/rb_allocation.h" #include "srsran/ran/modulation_scheme.h" namespace srsran { class pusch_codeword_buffer; class pusch_demodulator_notifier; class resource_grid_reader; /// \brief PUSCH demodulator interface. /// /// The demodulation of a PUSCH consists of: /// - extracting allocated REs from the resource grid, /// - equalizing of the extracted RE, /// - soft-demodulation of the complex data, and /// - descrambling. class pusch_demodulator { public: /// Parameters defining the demodulation procedure of a PUSCH transmission. struct configuration { /// Radio Network Temporary Identifier, see parameter \f$n_{RNTI}\f$ in TS38.211 Section 6.3.1.1. uint16_t rnti; /// Allocation RB list: the entries set to true are used for transmission. bounded_bitset<MAX_RB> rb_mask; /// Modulation scheme used for transmission. modulation_scheme modulation; /// Time domain allocation within a slot: start symbol index {0, ..., 12}. unsigned start_symbol_index; /// Time domain allocation within a slot: number of symbols {1, ..., 14}. unsigned nof_symbols; /// OFDM symbols containing DM-RS: boolean mask. std::array<bool, MAX_NSYMB_PER_SLOT> dmrs_symb_pos; /// DM-RS configuration type. dmrs_type dmrs_config_type; /// Number of DM-RS CDM groups without data. unsigned nof_cdm_groups_without_data; /// Scrambling identifier, see parameter \f$n_{ID}\f$ in TS38.211 Section 6.3.1.1. Range is {0, ..., 1023}. unsigned n_id; /// Number of transmit layers. unsigned nof_tx_layers; /// Receive antenna port indices the PUSCH transmission is mapped to. static_vector<uint8_t, MAX_PORTS> rx_ports; }; /// Default destructor. virtual ~pusch_demodulator() = default; /// \brief Demodulates a PUSCH transmission. /// /// Computes log-likelihood ratios from channel samples by reversing all the operations described in TS38.211 Section /// 6.3.1. /// /// \remarks /// - The size of \c data determines the codeword size in soft bits. /// - The total number of LLR must be consistent with the number of RE allocated to the transmission. /// /// \param[out] codeword_buffer Codeword buffer. /// \param[in] notifier Demodulation statistics notifier. /// \param[in] grid Resource grid for the current slot. /// \param[in] estimates Channel estimates for the REs allocated to the PUSCH transmission. /// \param[in] config Configuration parameters. virtual void demodulate(pusch_codeword_buffer& codeword_buffer, pusch_demodulator_notifier& notifier, const resource_grid_reader& grid, const channel_estimate& estimates, const configuration& config) = 0; }; } // namespace srsran
import { createPortal } from 'react-dom'; import styled from 'styled-components'; import { ExitButton } from '../button/button'; import { FaXmark } from 'react-icons/fa6'; const StyledModal = styled.div` position: fixed; height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; top: 0; background-color: rgba(0, 0, 0, 0.5); `; const ModalContent = styled.div` position: relative; top: -15%; display: flex; flex-direction: column; padding: 1.5rem; background-color: var(--color-slate-100); border: 1px solid var(--color-indigo-300); border-radius: 8px; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; `; const ButtonContainer = styled.div` display: flex; justify-content: end; `; interface ModalProps { children: React.ReactNode; closeModal: () => void; } export default function Modal({ children, closeModal }: ModalProps) { return createPortal( <StyledModal> <ModalContent> <ButtonContainer> <ExitButton onClick={closeModal}> <FaXmark /> </ExitButton> </ButtonContainer> <div>{children}</div> </ModalContent> </StyledModal>, document.body ); }
import React from "react"; import Nazim from '../img/sahil.jpg' import ProgressBar from "@ramonak/react-progress-bar"; import { useSpring, animated } from "react-spring"; import resume from '../img/Sahilresume.pdf' function About() { const calc = (x, y) => [ -(y - window.innerHeight / 2) / 20, (x - window.innerWidth / 2) / 20, 1.1, ]; const trans = (x, y, s) => `perspective(600px) rotateX(${x}deg) rotateY(${y}deg) scale(${s})`; const [props, set] = useSpring(() => ({ xys: [0, 0, 1], config: { mass: 5, tension: 300, friction: 60 }, })); const skills = [ {name:"HTML",val:"90"}, {name:"CSS",val:"80"}, {name:"Bootstrap",val:"92"}, {name:"Material UI",val:"85"}, {name:"Tailwind",val:"90"}, {name:"JavaScript",val:"80"}, {name:"React",val:"80"}, {name:"NodeJs",val:"70"}, {name:"ExpressJS",val:"70"}, {name:"MongoDB",val:"80"}, {name:"MySql",val:"70"}, // {name:"React Native",val:"70"}, ] return ( <section id="about" className="about"> <div className="container" data-aos="fade-up"> <div className="section-title"> <h2>About</h2> </div> <div className="row"> <animated.div className="col-lg-4" onMouseMove={({ clientX: x, clientY: y }) => set({ xys: calc(x, y) }) } onMouseLeave={() => set({ xys: [0, 0, 1] })} style={{ transform: props.xys.to(trans) }} > <img src={Nazim} className="img-fluid borderNew" alt="not found" /> </animated.div> <div className="col-lg-8 pt-4 pt-lg-0 content"> <h3>Full Stack Web Developer &amp; Freelancer</h3> <p className="fst-italic"> Enthusiastic and innovative MERN Stack Developer aiming to leverage extensive skillsin MongoDB, Express.js, React, and Node.jsto build dynamic and responsive web applications. Committed to writing clean, efficient code and solving complex problems, with a focus on optimizing user experience and integrating the latest web technologies. Seeking to contribute to a forward-thinking team where I can continue to develop my technical abilities, collaborate on challenging projects, and make a tangible impact in the field of web development :Skills- React.js Next.js Node.js Express.js Mongodb MySql JavaScript Material UI, Bootstrap, Tailwind.css Html Css </p> <div className="row"> <div className="col-lg-6"> <h5 style={{ color: "#728394" }}>Contact Contact Details</h5> <ul> <li> <i className="bi bi-chevron-right"></i> <strong>Email:</strong> <a href="mailto:[email protected]" style={{ textDecoration: "none" }} > [email protected] </a> </li> <li> <i className="bi bi-chevron-right"></i> <strong>Website:</strong>{" "} <a href="https://heynazim.netlify.app" style={{ textDecoration: "none" }} > https://heysahil.netlify.app </a> </li> <li> <i className="bi bi-chevron-right"></i> <strong>Phone:</strong>{" "} <a href="tel:+917880811002" style={{ textDecoration: "none" }} > +91 9205700614 </a> </li> <li> <i className="bi bi-chevron-right"></i> <strong>City:</strong> <span>Ghaziabad</span> </li> </ul> </div> <div className="col-lg-6 d-flex align-items-center"> <a href={resume} className="button-58" download> <span className="text"> <i className="fa-solid fa-download"></i> Download Resume </span> </a> </div> </div> </div> </div> <div id="skills" className="skills section-bg my-5"> <div className="container"> <div className="section-title"> <h2>Skills</h2> <p>I love working on new and exciting technologies emerging nowadays.I have good work experience as a MERN Stack Developer in startup(s) and UI/UX Designer where I was core member of the development team and done quite some contribution to open source as well</p> </div> <div className="row skills-content"> {skills.map((item)=>{ return <div className="col-lg-6"key={item.name}> <div className="progress" > <span className="skill">{item.name} <i className="val">{item.val}%</i></span> <div className="progress-bar-wrap" style={{borderRadius:"5px"}}> <ProgressBar completed={item.val} height="10px" isLabelVisible={false} transitionDuration="3s" animateOnRender={true} /> </div> </div> </div> })} </div> </div> </div> </div> </section> ); } export default About;
// Requiring our models and passport as we've configured it const db = require("../models"); const passport = require("../config/passport"); module.exports = function (app) { // Using the passport.authenticate middleware with our local strategy. // If the user has valid login credentials, send them to the members page. // Otherwise the user will be sent an error app.post("/api/login", passport.authenticate("local"), (req, res) => { // Sending back a password, even a hashed password, isn't a good idea res.json({ email: req.user.email, id: req.user.id }); }); // Route for signing up a user. The user's password is automatically hashed and stored securely thanks to // how we configured our Sequelize User Model. If the user is created successfully, proceed to log the user in, // otherwise send back an error app.post("/api/signup", (req, res) => { db.User.create({ email: req.body.email, password: req.body.password }) .then(() => { res.redirect(307, "/api/login"); }) .catch(err => { console.log(err) res.status(401).json("Email already in use."); }); }); // Route for logging user out app.get("/logout", (req, res) => { req.logout(); res.redirect("/"); }); // Route for getting some data about our user to be used client side app.get("/api/user_data", (req, res) => { if (!req.user) { // The user is not logged in, send back an empty object res.json({}); } else { // Otherwise send back the user's email and id // Sending back a password, even a hashed password, isn't a good idea res.json({ email: req.user.email, id: req.user.id }); } }); app.get("/api/story/:id", (req, res) => { // console.log(req.params.id) db.MainStory.findOne({ where: { id: req.params.id } }).then(function (dbMainStory) { res.json(dbMainStory) }) }) //sends the data from the main story seed to frontend app.get("/api/story", (req, res) => { db.MainStory.findAll({}).then(data => { res.json(data) }) }) app.post("/api/createCharacter", (req, res) => { db.Character.create({}).then((data) => { res.status(200).json(data) }) .catch(err => { res.status(401).json(err); }); }); //sends character data to front end based on user id app.get("/api/character", (req, res) => { db.Character.findAll({ include: [db.User], where: { id: req.user.id } }).then(data => { res.json(data) }) }); //updates the user's name in database when character is created app.put("/api/charname", (req, res) => { db.Character.update({ name: req.body.name }, { where: { id: req.user.id } }); }) //Increments the character exp on the table app.put("/api/charexp", (req, res) => { // console.log(req.body.exp) db.Character.increment({ exp: (req.body.exp) }, { where: { id: req.user.id } }) }) app.put("/api/clearexp", (req, res) => { // console.log(req.body.exp) db.Character.update({ exp: (req.body.exp) }, { where: { id: req.user.id } }) }) //updates the character items on the character table app.put("/api/charitem", (req, res) => { console.log(req.body.exp) db.Character.create({ item: (req.body.item) }, { where: { id: req.user.id } }, ) }) }
/// @file /// @brief /// The @ref DesignPatternExamples_csharp.ILogger "ILogger" interface /// as used on all loggers in the @ref bridge_pattern "Bridge pattern". using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternExamples_csharp { /// <summary> /// Represents an implementation of a logger object as call from the Logger class. /// </summary> internal interface ILogger { /// <summary> /// Log trace messages to the configured output. /// </summary> /// <param name="msg">The message to log.</param> void LogTrace(string msg); /// <summary> /// Log informational messages to the configured output. /// </summary> /// <param name="msg">The message to log.</param> void LogInfo(string msg); /// <summary> /// Log error messages to the configured output. /// </summary> /// <param name="msg">The message to log.</param> void LogError(string msg); } }
// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering // Solutions of Sandia, LLC (NTESS). Under the terms of Contract // DE-NA0003525 with NTESS, the U.S. Government retains certain rights // in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of NTESS nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #ifndef STK_SEARCH_PLANE_HPP #define STK_SEARCH_PLANE_HPP #include <cmath> #include <Kokkos_ArithTraits.hpp> #include <stk_search/Point.hpp> namespace stk { namespace search { template <typename T> class Plane { public: typedef T value_type; typedef Point<value_type> point_type; static const int Dim = 3; static KOKKOS_FUNCTION constexpr value_type max() { return Kokkos::Details::ArithTraits<T>::max() ;} KOKKOS_FUNCTION point_type cross(const point_type& a, const point_type& b) const{ return point_type(a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]); } KOKKOS_FUNCTION void normalize(point_type& a) const{ const value_type vec_len = Kokkos::Details::ArithTraits<T>::sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); const value_type denom = vec_len == 0.0 ? 1.0 : vec_len; const value_type vec_len_inv = 1.0 / denom; a[0] *= vec_len_inv; a[1] *= vec_len_inv; a[2] *= vec_len_inv; } KOKKOS_FUNCTION value_type dot(const point_type& a, const point_type& b) const { return (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]); } KOKKOS_FUNCTION value_type SignedDistance(const point_type& P) const { return dot(normal, P) - constant; } KOKKOS_FUNCTION int WhichSide(const point_type& P) const { value_type Distance = SignedDistance(P); if (Distance < 0.0) { return -1; } else if (Distance > 0.0) { return 1; } else { // Distance == 0.0 return 0; } } KOKKOS_FUNCTION Plane() : normal(max()), constant(max()) { } KOKKOS_FUNCTION Plane( const point_type normal_, const value_type constant_) : normal(normal_), constant(constant_) { } KOKKOS_FUNCTION Plane( const point_type pointOnPlane, const point_type normal_) : normal(normal_), constant() { constant = dot(normal, pointOnPlane); } KOKKOS_FUNCTION Plane( const point_type P0, const point_type P1, const point_type P2) : normal(), constant() { point_type Edge1 = P1 - P0; point_type Edge2 = P2 - P0; normal = cross(Edge1, Edge2); normalize(normal); constant = dot(normal, P0); } KOKKOS_FUNCTION bool operator==(Plane<value_type> const& b) const { return normal == b.normal && constant == b.constant; } KOKKOS_FUNCTION bool operator!=(Plane<value_type> const& b) const { return !(*this == b); } KOKKOS_DEFAULTED_FUNCTION ~Plane() = default; private: point_type normal; value_type constant; }; }} //namespace stk::search #endif //STK_SEARCH_Plane_HPP
import React, { useRef } from "react"; import "./Compose.css"; import { useDispatch, useSelector } from "react-redux"; import { sendMail, updateSentbox } from "../Redux/EmailSlice"; const Compose = () => { const dispatch = useDispatch(); const userID = useSelector((state) => { return state.login.user; }); const sendTo = useRef(); const msg = useRef(); const formSubmitHandler = async (event) => { event.preventDefault(); const mailData = { mailFrom: userID, mailTo: sendTo.current.value, mailBody: msg.current.value, readStatus: false, }; await dispatch(sendMail(mailData)); await dispatch(updateSentbox(mailData)); alert("Email Sent Successfully"); }; return ( <div> <form onSubmit={formSubmitHandler}> <label htmlFor="user" className="to"> To : {" "} </label> <input type="email" ref={sendTo} className="compose-input" placeholder="[email protected]" required /> <label htmlFor="user" className="to"> Subject : {" "} </label> <input type="text" className="compose-input" placeholder="Subject (Optional)" /> <textarea placeholder="Write your email here.." className="mailBody" name="body" id="body" ref={msg} required ></textarea> <div> <button type="button">Cancel</button> <button type="submit">Send</button> </div> </form> </div> ); }; export default Compose;
import 'package:flutter/material.dart'; import 'package:peliculas_app_flutter/providers/movies_provider.dart'; import 'package:peliculas_app_flutter/widgets/movie_search_delegate.dart'; import 'package:peliculas_app_flutter/widgets/widgets.dart'; import 'package:provider/provider.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final moviesProvider = context.watch<MovieProvider>(); //final moviesProvider = Provider.of<MovieProvider>(context, listen: true); return Scaffold( appBar: AppBar( title: const Text('Peliculas en cines'), elevation: 0, actions: [ IconButton( onPressed: () => showSearch(context: context, delegate: MovieSearchDelegate()), icon: const Icon(Icons.search), ) ], ), body: SingleChildScrollView( child: Column( children: [ CardSwiper(movies: moviesProvider.onDisplayMovies), const SizedBox(height: 20), MovieSlider( moviesPopulars: moviesProvider.onDisplayPopularity, title: 'Movie Popularity', onNextPage: () => moviesProvider.getOnDisplayPopularity(), ), ], ), ), ); } }
/* * This is a manifest file that'll be compiled into application.css, * which will include all the files listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, * vendor/assets/stylesheets, or vendor/assets/stylesheets of plugins, if any, * can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear * at the top of the compiled file, but it's generally better to create a new * file per style scope. * *= require_self *= require bootstrap3-editable/bootstrap-editable *= require rails_bootstrap_forms *= require_tree . */ @import "bootstrap-sprockets" @import "bootstrap" @import "font-awesome-sprockets" @import "font-awesome" /* A mixin & a class selector to beautify the debug info. */ $gray-medium-light: #eaeaea @mixin box_sizing -moz-box-sizing: border-box -webkit-box-sizing: border-box box-sizing: border-box body padding-right: 25px padding-left: 25px margin-right: auto margin-lef: auto .debug_dump clear: both float: left width: 100% margin-top: 45px @include box_sizing #banner img float: left /* header */ #logo float: left margin-right: 10px font-size: 1.7em color: #fff text-transform: uppercase letter-spacing: -1px padding-top: 9px font-weight: bold &:hover color: #fff text-decoration: none /* footer */ footer margin-top: 45px padding-top: 5px border-top: 1px solid $gray-medium-light color: $gray-light a color: $gray &:hover color: $gray-darker large float: left ul float: right list-style: none li float: left margin-left: 15px
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import { StakingBase } from "../bases/StakingBase.t.sol"; import "forge-std/Test.sol"; contract DelegatingTests is StakingBase { // Test that a staked token is delegated to self by default. function testDelegating__DelegateToSelfByDefault() public { address owner = mockStakeSingle(PUNK_ID); assert(staking.getDelegate(owner) == owner); } // Test that delegating to other staked user works. function testDelegating__GetDelegateAddress() public { address owner = mockStakeSingle(PUNK_ID); address delegate = mockStakeSingle(MONSTER_ID); vm.prank(owner); staking.delegate(delegate); assert(staking.getDelegate(owner) == delegate); } // Test that delegating to a non-staked user works. function testDelegating__DelegateToNonStakedUser() public { address owner = mockStakeSingle(PUNK_ID); address delegate = makeAddr("unstakedDelegate"); vm.prank(owner); staking.delegate(delegate); assert(staking.getDelegate(owner) == delegate); } // Test that you cannot delegate to your current delegate. function testDelegating__RevertsIfDelegatingToCurrentDelegate() public { address owner = mockStakeSingle(PUNK_ID); address delegate = makeAddr("unstakedDelegate"); vm.prank(owner); staking.delegate(delegate); vm.expectRevert(InvalidDelegation.selector); staking.delegate(delegate); } // Test that you cannot delegate if you haven't staked. function testDelegating__RevertsIfAddressHasNotStaked() public { address owner = frankenpunks.ownerOf(PUNK_ID); address delegate = makeAddr("unstakedDelegate"); vm.prank(owner); vm.expectRevert(InvalidDelegation.selector); staking.delegate(delegate); } }
// // NativeAppModule.swift // NativeModules // // Created by Dhruv Parmar on 12/06/22. // import Foundation @objc(NativeAppModule) class NativeAppModule : NSObject { //When you want to execute swift code then call this function @objc func simpleFunction(){ //Add your swift code here NSLog("%@", "Calling simple function"); } //When you want to execute swift code with parameters then call this function @objc func functionWithParam(_ param:String){ //Execure your swift code by passing parameters from react native code } //When you want to execute swift code and wait for some result then call this function @objc func functionWithCallback(_ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock){ //Execute swift code and return result below to react native resolve("Any value that needs to be return of any data type"); } //When you want to execute swift code with parameters and wait for some result then call this function @objc func functionWithCallbackParams(_ param1:String, param2:String, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock){ print("Calling functionWithCallback"); do { if (String(param2) == param1) { resolve("true"); } else { resolve("false"); } }catch let error { //If you want to throw an error reject("errorCode", error.localizedDescription, error); //If you want to return custom message resolve("Custom error message"); }; } //When you want to execute swift code with parameters and wait for some result then call this function @objc func validateBasicFields(_ param1:String, param2:String, resolver resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock){ print("Calling functionWithCallback"); do { if (!param1.isEmpty && !param2.isEmpty) { resolve("My name is \(param1) and email id is \(param2)"); } else { resolve("Enter Fields (name & email)"); } }catch let error { //If you want to throw an error reject("errorCode", error.localizedDescription, error); //If you want to return custom message resolve("Custom error message"); }; } //add this to avoid warning in react native @objc static func requiresMainQueueSetup() -> Bool { return true } }
// @ZBS { // *MODULE_NAME Simple Hash // *MASTER_FILE 1 // +DESCRIPTION { // A simple, fast, and decoupled hash table using string keys. // } // *PORTABILITY win32 unix // *REQUIRED_FILES zhashtable.cpp zhashtable.h zhashtyped.h zendian.cpp zendian.h // *VERSION 2.0 // +HISTORY { // 1.2 KLD fixed a bug on setting a key that had previously been deleted // 1.3 ZBS changed memcmp to strncmp to fix a bug that made set read potenitally outside of bounds (causing Bounds Checker to complain) // 1.4 ZBS changed hash function to code borrowed from Bob Jenkins // 1.5 ZBS changed name to standard convention // 2.0 ZBS reworked nomenclature to allow for clear binary or string storage and also added concept of buffer type // 2.1 ZBS added typing flags to improve the get and put characteristics // } // +TODO { // } // *SELF_TEST yes console ZHASHTABLE_SELF_TEST // *PUBLISH yes // } // OPERATING SYSTEM specific includes: #ifdef WIN32 #include "windows.h" // The following line is copied out of windows.h to avoid the header dependency // If there is a problem, comment it out and uncomment the include above. // This function is only used for the debugging function "debugDump()" // and could easily be removed entirely. //extern "C" { //__declspec(dllimport) void __stdcall OutputDebugStringA( const char *lpOutputString ); //} //#define OutputDebugString OutputDebugStringA #endif // STDLIB includes: #include "string.h" #include "stdio.h" #include "stdlib.h" #include "stdarg.h" #include "assert.h" #include "limits.h" #include "ctype.h" // for isprint() -- see zHashTableUnpack() // MODULE includes: #include "zhashtable.h" // Endian // ZBS Dec 2008 made redundant copies of these endian calls in zhashtable // so that hashtable can compile alone int zHashTableMachineIsBigEndian() { short word = 0x4321; if((*(char *)& word) != 0x21 ) { return 1; } return 0; } void zHashTableByteSwap( unsigned char * b, int size ) { int i = 0; int j = size-1; unsigned char c; while( i < j ) { c = b[i]; b[i] = b[j]; b[j] = c; i++, j--; } } #define BYTESWAP(x) zHashTableByteSwap((unsigned char *) &x,sizeof(x)) // macro for atomic types size_t zHashTableFreadEndian( void *buffer, size_t elemSize, size_t numElem, FILE *f, int _byteSwap ) { size_t elemsRead = fread( buffer, elemSize, numElem, f ); if( !_byteSwap || elemSize==1 ) { return elemsRead; } unsigned char *b = (unsigned char *)buffer; for( size_t i=0; i<numElem; i++, b += elemSize ) { zHashTableByteSwap( b, elemSize ); } return elemsRead; } // ZHashTable // This hash function generator taken from: // http://burtleburtle.net/bob/hash/doobs.html // By Bob Jenkins, 1996. bob_jenkins -AT- burtleburtle.net. // It is a MAJOR improvement over my previous simple-minded implementations unsigned int ZHashTable::hashBurtle( char *k, int keyLen ) { #define mix(a,b,c) \ { \ a -= b; a -= c; a ^= (c>>13); \ b -= c; b -= a; b ^= (a<<8); \ c -= a; c -= b; c ^= (b>>13); \ a -= b; a -= c; a ^= (c>>12); \ b -= c; b -= a; b ^= (a<<16); \ c -= a; c -= b; c ^= (b>>5); \ a -= b; a -= c; a ^= (c>>3); \ b -= c; b -= a; b ^= (a<<10); \ c -= a; c -= b; c ^= (b>>15); \ } unsigned int a,b,c,len; len = (unsigned int)keyLen; a = b = 0x9e3779b9; c = 0; while( len >= 12 ) { a += (k[0] +((unsigned int)k[1]<<8) +((unsigned int)k[2]<<16) +((unsigned int)k[3]<<24)); b += (k[4] +((unsigned int)k[5]<<8) +((unsigned int)k[6]<<16) +((unsigned int)k[7]<<24)); c += (k[8] +((unsigned int)k[9]<<8) +((unsigned int)k[10]<<16)+((unsigned int)k[11]<<24)); mix(a,b,c); k += 12; len -= 12; } // handle the last 11 bytes c += keyLen; switch(len) { case 11: c+=((unsigned int)k[10]<<24); case 10: c+=((unsigned int)k[9]<<16); case 9 : c+=((unsigned int)k[8]<<8); // the first byte of c is reserved for the length case 8 : b+=((unsigned int)k[7]<<24); case 7 : b+=((unsigned int)k[6]<<16); case 6 : b+=((unsigned int)k[5]<<8); case 5 : b+=k[4]; case 4 : a+=((unsigned int)k[3]<<24); case 3 : a+=((unsigned int)k[2]<<16); case 2 : a+=((unsigned int)k[1]<<8); case 1 : a+=k[0]; // case 0: nothing left to add } mix(a,b,c); return c; } typedef unsigned long long U64; static U64 hashfn_tab[256] = {0,}; void ZHashTable::nrHashInit() { if( hashfn_tab[0] == 0 ) { U64 h; h = 0x544B2FBACAAF1684LL; for( int j=0; j<256; j++ ) { for( int i=0; i<31; i++ ) { h = (h >> 7) ^ h; h = (h << 11) ^ h; h = (h >> 10) ^ h; } hashfn_tab[j] = h; } } } U64 ZHashTable::nrHash( char *key, int keyLen ) { int j; char *k = (char *)key; U64 h = 0xBB40E64DA205B064LL; j = 0; while( keyLen ? j++ < keyLen : *k ) { h = ( h * 7664345821815920749LL ) ^ hashfn_tab[ (unsigned char)(*k) ]; k++; } return h; } unsigned int ZHashTable::hash( char *k, int keyLen ) { unsigned int ret; if( useNRHash ) { ret = ( nrHash( k, keyLen ) >> 32 ) & 0xFFFFFFFF; } else { ret = hashBurtle( k, keyLen ); } return ret; } int ZHashTable::internalSet( ZHashRecord **_hashTable, int _hashTableSize, char *key, int keyLen, ZHashRecord *_recPtr ) { // The _recPtr might be nul if we are deleting which is why key and keyLen are passed in separately // However, in the case that this isn't a delete, this fucntion expects that _recPtr already has the // key, keyLen, valLen and val all setup hasAnyChanged = 1; int index = hash( key, keyLen ) % _hashTableSize; int total = _hashTableSize; int totalDeleted = 0; int foundKey = 0; ZHashRecord *recPtr; int dstIndex = -1; while( total-- ) { recPtr = _hashTable[index]; if( recPtr ) { if( recPtr->flags & zhDELETED ) { // Found a deleted key. Use this space unless the key is found. // NOTE: This will end up using farthest deleted key from the // head of the chain first. dstIndex = index; totalDeleted++; } else if( keyLen==recPtr->keyLen && !memcmp(key, recPtr->key, keyLen) ) { // Found already existing key. Use this slot. foundKey = 1; dstIndex = index; break; } else { collisions++; } } else { // Found an empty slot, marking the end of this chain. // Use this slot unless we found a deleted slot above. if( dstIndex == -1 ) { dstIndex = index; } break; } index = (index+1) % _hashTableSize; } assert( total + totalDeleted ); // There should always be some room left since we keep // the list at 50% free all the time to avoid collisions // Here, destIndex contains the index of the found record. The found record value can // be either NULL, a pointer to a deleted entry, or a pointer to the found entry. ZHashRecord *delRec = _hashTable[dstIndex]; if( _recPtr == NULL ) { // We are deleting the key, it is only marked as deleted it is not actually freed // until the value is replaced. This sucks because the val might be huge // and we don't need it around anymore. So we do a check here to see if it is // worth reallocating the hash record. if( foundKey ) { // Only can deleted it if it already exists if( delRec->type == zhPFR ) { void **ptr = (void **)&delRec->key[delRec->keyLen]; assert( *ptr ); free( *ptr ); *ptr = 0; } if( delRec->valLen > 64 ) { // Probably worth it to reallocate ZHashRecord *r = (ZHashRecord *)malloc( sizeof(ZHashRecord) + keyLen ); memcpy( r, recPtr, sizeof(ZHashRecord) + keyLen ); r->valLen = 0; if( ! fastModePtr ) { free( delRec ); } _hashTable[dstIndex] = r; delRec = r; } delRec->flags = zhDELETED; delRec->type = 0; return 1; } return 0; } else { // We are either adding a new key or setting the value of an old key. // Either way, if the destination record has a value, it must be deleted // before the new value is set. if( delRec ) { if( delRec->type == zhPFR ) { void **ptr = (void **)&delRec->key[delRec->keyLen]; assert( *ptr ); free( *ptr ); *ptr = 0; } if( ! fastModePtr ) { free( delRec ); } } _recPtr->flags |= zhCHANGED; _hashTable[dstIndex] = _recPtr; } return !foundKey; } ZHashTable::ZHashTable( int _initialSize, int _fastModeAllocate, int _useNRHash ) { nrHashInit(); last = 0; lastLen = 0; initialSize = _initialSize; hashTable = 0; fastModeAllocate = _fastModeAllocate; fastModeBuffer = 0; useNRHash = _useNRHash; clear(); } ZHashTable::ZHashTable( const ZHashTable &copy ) { last = 0; lastLen = 0; initialSize = 64; hashTable = 0; clear(); copyFrom( (ZHashTable &)copy ); } ZHashTable::~ZHashTable() { clearLast(); if( hashTable ) { if( ! fastModePtr ) { for( int i=0; i<hashTableSize; i++ ) { ZHashRecord *p = hashTable[i]; if( p ) { free( p ); } } } free( hashTable ); } } void ZHashTable::dump( int toStdout ) { for( int i=0; i<size(); i++ ) { if( getKey(i) ) { char buf[512] = {0,}; char keybuf[256] = {0,}; // If the key is binary we convert it to hex int binary = 0; for( int j=0; j<hashTable[i]->keyLen-1; j++ ) { if( hashTable[i]->key[j] < ' ' || hashTable[i]->key[j] > 126 ) { binary = 1; break; } } if( binary ) { char *b = keybuf; for( int j=0; j<hashTable[i]->keyLen && b < keybuf; j++ ) { sprintf( b, "%02X", hashTable[i]->key[j] ); b += 2; *b++ = ' '; } } else { strncpy( keybuf, hashTable[i]->key, 255 ); } int type = hashTable[i]->type; char typeCode[] = { ' ', 'b', 's', 'i', 'u', 'l', 'f', 'd', 'p', 'o' }; sprintf( buf, "%s = (%c)%s\n", keybuf, typeCode[type], getValS(i) ); if( toStdout ) { printf( "%s", buf ); } else { #ifdef WIN32 OutputDebugString( buf ); #else printf( "%s", buf ); #endif } } } } char *ZHashTable::dumpToString() { int len = 0; char *string = 0; for( int pass=0; pass<2; pass++ ) { for( int i=0; i<size(); i++ ) { if( getKey(i) ) { char buf[512] = {0,}; char keybuf[256] = {0,}; // If the key is binary we convert it to hex int binary = 0; for( int j=0; j<hashTable[i]->keyLen-1; j++ ) { if( hashTable[i]->key[j] < ' ' || hashTable[i]->key[j] > 126 ) { binary = 1; break; } } if( binary ) { char *b = keybuf; for( int j=0; j<hashTable[i]->keyLen && b < keybuf; j++ ) { sprintf( b, "%02X", hashTable[i]->key[j] ); b += 2; *b++ = ' '; } } else { strncpy( keybuf, hashTable[i]->key, 255 ); } int type = hashTable[i]->type; char typeCode[] = { 'b', 's', 'i', 'u', 'l', 'f', 'd', 'p', 'o' }; sprintf( buf, "%s = (%c)%s\n", keybuf, typeCode[type], getValS(i) ); if( pass==0 ) { len += strlen( buf ); } else { strcat( string, buf ); } } } if( pass==0 ) { string = new char[len+1]; *string = 0; } } return string; } void ZHashTable::clearLast() { if( last ) { free( last ); last = 0; lastLen = 0; } } void ZHashTable::init( int _initSize ) { last = 0; lastLen = 0; clear( _initSize, 1 ); } void ZHashTable::clear( int _initSize, int freeFirst ) { if( hashTable && freeFirst ) { for( int i=0; i<hashTableSize; i++ ) { if( hashTable[i] ) { if( hashTable[i]->type == zhPFR ) { free( *(void **)&hashTable[i]->key[hashTable[i]->keyLen] ); } if( !fastModeAllocate ) { free( hashTable[i] ); } } } free( hashTable ); } if( _initSize > 0 ) { initialSize = _initSize; } hashTableSize = initialSize; numRecords = 0; hashTable = 0; hasAnyChanged = 0; collisions = 0; resizeCount = 0; if( fastModeBuffer ) { free( fastModeBuffer ); fastModeBuffer = 0; } fastModePtr = 0; fastModeResizes = 0; if( initialSize ) { hashTable = (ZHashRecord **)malloc( sizeof(ZHashRecord *) * hashTableSize ); memset( hashTable, 0, sizeof(ZHashRecord *) * hashTableSize ); } } void ZHashTable::copyFrom( ZHashTable &table ) { for( int i=0; i<table.size(); i++ ) { ZHashRecord *p = table.hashTable[i]; if( p ) { if( !(p->flags & zhDELETED) ) { bputB( p->key, p->keyLen, &p->key[p->keyLen], p->valLen, p->type, p->flags ); } } } } char **ZHashTable::getKeys( int &count ) { char **ptrs = (char **)malloc( sizeof(char*) * numRecords ); int cnt = 0; for( int i=0; i<hashTableSize; i++ ) { if( hashTable[i] ) { assert( cnt < numRecords ); ptrs[cnt++] = strdup( hashTable[i]->key ); } } assert( cnt == numRecords ); count = cnt; return ptrs; } // CONVERT //------------------------------------------------------------------------------------------ void ZHashTable::convert( int srcType, char *src, int srcLen, int dstType, char **dst, int *dstLen ) { char *endPtr = 0; //assert( last == 0 ); // I'm not sure who added this. It is perfectly legal for last != 0 as this function // doesn't even reference it. switch( dstType ) { case zhS32: { *dst = (char *)malloc( sizeof(int) ); *dstLen = sizeof(int); break; } case zhU32: { *dst = (char *)malloc( sizeof(int) ); *dstLen = sizeof(int); break; } case zhS64: { *dst = (char *)malloc( sizeof(S64) ); *dstLen = sizeof(S64); break; } case zhFLT: { *dst = (char *)malloc( sizeof(float) ); *dstLen = sizeof(float); break; } case zhDBL: { *dst = (char *)malloc( sizeof(double) ); *dstLen = sizeof(double); break; } case zhPTR: { *dst = (char *)malloc( sizeof(char*) ); *dstLen = sizeof(char*); break; } case zhPFR: { *dst = (char *)malloc( sizeof(char*) ); *dstLen = sizeof(char*); break; } } switch( srcType ) { case zhBIN: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( srcLen ); *dstLen = srcLen; memcpy( *dst, src, srcLen ); break; } case zhSTR: { *dst = (char *)malloc( srcLen ); *dstLen = srcLen; memcpy( *dst, src, srcLen ); break; } case zhS32: { assert( srcLen == sizeof(int) ); *(signed int *)dst = *(signed int *)src; break; } case zhU32: { assert( srcLen == sizeof(int) ); *(unsigned int *)dst = *(unsigned int *)src; break; } case zhS64: { assert( srcLen == sizeof(S64) ); *(S64 *)dst = *(S64 *)src; break; } case zhFLT: { assert( srcLen == sizeof(float) ); *(float *)dst = *(float *)src; break; } case zhDBL: { assert( srcLen == sizeof(double) ); *(double *)dst = *(double *)src; break; } case zhPTR: { assert( srcLen == sizeof(char*) ); *(char* *)dst = *(char* *)src; break; } case zhPFR: { assert( srcLen == sizeof(char*) ); *(char* *)dst = *(char* *)src; break; } } break; } case zhSTR: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( srcLen+1 ); *dstLen = srcLen+1; memcpy( *dst, src, srcLen+1 ); break; } case zhSTR: { *dst = (char *)malloc( srcLen+1 ); *dstLen = srcLen+1; memcpy( *dst, src, srcLen+1 ); break; } case zhS32: { int ret; if( srcLen > 2 && src[0] == '0' && src[1] == 'x' ) { ret = strtoul( src, &endPtr, 0 ); } else { ret = (int)strtod( src, &endPtr ); } if( endPtr-src < srcLen && *endPtr=='.' ) { ret = (int)strtod( src, &endPtr ); } if( endPtr-src >= srcLen ) { *((int *)*dst) = ret; } else { *((int *)*dst) = 0; } break; } case zhU32: { int ret; if( srcLen > 2 && src[0] == '0' && src[1] == 'x' ) { ret = strtoul( src, &endPtr, 0 ); } else { ret = (unsigned int)strtod( src, &endPtr ); } if( endPtr-src >= srcLen ) { *((unsigned int *)*dst) = ret; } else { *((unsigned int *)*dst) = 0; } break; } case zhS64: { S64 ret = (S64)strtod( src, &endPtr ); if( endPtr-src >= srcLen ) { *((S64 *)*dst) = ret; } else { *((S64 *)*dst) = 0; } break; } case zhFLT: { float ret = (float)strtod( src, &endPtr ); if( endPtr-src >= srcLen ) { *((float *)*dst) = ret; } else { *((float *)*dst) = 0; } break; } case zhDBL: { double ret = (double)strtod( src, &endPtr ); if( endPtr-src >= srcLen ) { *((double *)*dst) = ret; } else { *((double *)*dst) = 0; } break; } case zhPTR: { char* ret = (char*)strtoul( src, &endPtr, 0 ); if( endPtr-src >= srcLen ) { *((char* *)*dst) = ret; } else { *((char* *)*dst) = 0; } break; } case zhPFR: { char* ret = (char*)strtoul( src, &endPtr, 0 ); if( endPtr-src >= srcLen ) { *((char* *)*dst) = ret; } else { *((char* *)*dst) = 0; } break; } } break; } case zhS32: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( sizeof(int) ); *dstLen = sizeof(int); memcpy( *dst, src, sizeof(int) ); break; } case zhSTR: { char buf[128]; sprintf( buf, "%d", *(int *)src ); int len = strlen( buf ) + 1; *dst = (char *)malloc( len ); *dstLen = len; memcpy( *dst, buf, *dstLen ); break; } case zhS32: { *(int *)*dst = *(int *)src; break; } case zhU32: { *(unsigned int *)*dst = *(unsigned int *)src; break; } case zhS64: { *(S64 *)*dst = (S64)*(int *)src; break; } case zhFLT: { *(float *)*dst = (float)*(int *)src; break; } case zhDBL: { *(double *)*dst = (double)*(int *)src; break; } case zhPTR: { *(char* *)*dst = (char *)*(int *)src; break; } case zhPFR: { *(char* *)*dst = (char *)*(int *)src; break; } } break; } case zhU32: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( sizeof(unsigned int) ); *dstLen = sizeof(unsigned int); memcpy( *dst, src, sizeof(unsigned int) ); break; } case zhSTR: { char buf[128]; sprintf( buf, "%u", *(unsigned int *)src ); int len = strlen( buf ) + 1; *dst = (char *)malloc( len ); *dstLen = len; memcpy( *dst, buf, *dstLen ); break; } case zhS32: { *(int *)*dst = *(int *)src; break; } case zhU32: { *(unsigned int *)*dst = (unsigned int)*(unsigned int *)src; break; } case zhS64: { *(S64 *)*dst = (S64)*(unsigned int *)src; break; } case zhFLT: { *(float *)*dst = (float)*(unsigned int *)src; break; } case zhDBL: { *(double *)*dst = (double)*(unsigned int *)src; break; } case zhPTR: { *(char* *)*dst = (char*)*(unsigned int *)src; break; } case zhPFR: { *(char* *)*dst = (char*)*(unsigned int *)src; break; } } break; } case zhS64: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( sizeof(S64) ); *dstLen = sizeof(S64); memcpy( *dst, src, sizeof(S64) ); break; } case zhSTR: { char buf[128]; sprintf( buf, "%I64d", *(S64*)src ); int len = strlen( buf ) + 1; *dst = (char *)malloc( len ); *dstLen = len; memcpy( *dst, buf, *dstLen ); break; } case zhS32: { *(int *)*dst = (int)*(S64 *)src; break; } case zhU32: { *(unsigned int *)*dst = (unsigned int)*(S64 *)src; break; } case zhS64: { *(S64 *)*dst = (S64)*(S64 *)src; break; } case zhFLT: { *(float *)*dst = (float)*(S64 *)src; break; } case zhDBL: { *(double *)*dst = (double)*(S64 *)src; break; } case zhPTR: { assert( 0 ); //*(char* *)*dst = (char*)*(S64 *)src; break; } case zhPFR: { assert( 0 ); //*(char* *)*dst = (char*)*(S64 *)src; break; } } break; } case zhFLT: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( sizeof(float) ); *dstLen = sizeof(float); memcpy( *dst, src, sizeof(float) ); break; } case zhSTR: { char buf[128]; sprintf( buf, "%f", *(float*)src ); int len = strlen( buf ) + 1; *dst = (char *)malloc( len ); *dstLen = len; memcpy( *dst, buf, *dstLen ); break; } case zhS32: { *(int *)*dst = (int)*(float *)src; break; } case zhU32: { *(unsigned int *)*dst = (unsigned int)*(float *)src; break; } case zhS64: { *(S64 *)*dst = (S64)*(float *)src; break; } case zhFLT: { *(float *)*dst = (float)*(float *)src; break; } case zhDBL: { *(double *)*dst = (double)*(float *)src; break; } case zhPTR: { assert( 0 ); break; } case zhPFR: { assert( 0 ); break; } } break; } case zhDBL: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( sizeof(double) ); *dstLen = sizeof(double); memcpy( *dst, src, sizeof(double) ); break; } case zhSTR: { char buf[128]; sprintf( buf, "%lf", *(double*)src ); int len = strlen( buf ) + 1; *dst = (char *)malloc( len ); *dstLen = len; memcpy( *dst, buf, *dstLen ); break; } case zhS32: { *(int *)*dst = (int)*(double *)src; break; } case zhU32: { *(unsigned int *)*dst = (unsigned int)*(double *)src; break; } case zhS64: { *(S64 *)*dst = (S64)*(double *)src; break; } case zhFLT: { *(float *)*dst = (float)*(double *)src; break; } case zhDBL: { *(double *)*dst = (double)*(double *)src; break; } case zhPTR: { assert( 0 ); break; } case zhPFR: { assert( 0 ); break; } } break; } case zhPTR: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( sizeof(char*) ); *dstLen = sizeof(char*); memcpy( *dst, src, sizeof(char*) ); break; } case zhSTR: { char buf[128]; sprintf( buf, "0x%X", *(char**)src ); int len = strlen( buf ) + 1; *dst = (char *)malloc( len ); *dstLen = len; memcpy( *dst, buf, *dstLen ); break; } case zhS32: { #if defined(__LP64__) || defined(_Wp64) assert( 0 && "64bit ptr illegal typecast (zhashtable)" ); #else *(int *)*dst = (int)*(char* *)src; #endif break; } case zhU32: { #if defined(__LP64__) || defined(_Wp64) assert( 0 && "64bit ptr illegal typecast (zhashtable)"); #else *(unsigned int *)*dst = (unsigned int)*(char* *)src; #endif break; } case zhS64: { assert(0); //*(S64 *)*dst = (S64)*(char* *)src; break; } case zhFLT: { assert( 0 ); break; } case zhDBL: { assert( 0 ); break; } case zhPTR: { *(char* *)*dst = (char*)*(char* *)src; break; } case zhPFR: { *(char* *)*dst = (char*)*(char* *)src; break; } } break; } case zhPFR: { switch( dstType ) { case zhBIN: { *dst = (char *)malloc( sizeof(char*) ); *dstLen = sizeof(char*); memcpy( *dst, src, sizeof(char*) ); break; } case zhSTR: { char buf[128]; sprintf( buf, "0x%X", *(char**)src ); int len = strlen( buf ) + 1; *dst = (char *)malloc( len ); *dstLen = len; memcpy( *dst, buf, *dstLen ); break; } case zhS32: { #if defined(__LP64__) || defined(_Wp64) assert( 0 && "64bit ptr illegal typecast (zhashtable)" ); #else *(int *)*dst = (int)*(char* *)src; #endif break; } case zhU32: { #if defined(__LP64__) || defined(_Wp64) assert( 0 && "64bit ptr illegal typecast (zhashtable)" ); #else *(unsigned int *)*dst = (unsigned int)*(char* *)src; #endif break; } case zhS64: { assert(0); //*(S64 *)*dst = (S64)*(char* *)src; break; } case zhFLT: { assert( 0 ); break; } case zhDBL: { assert( 0 ); break; } case zhPTR: { *(char* *)*dst = (char*)*(char* *)src; break; } case zhPFR: { *(char* *)*dst = (char*)*(char* *)src; break; } } break; } } } // GET //------------------------------------------------------------------------------------------ ZHashRecord *ZHashTable::lookup( char *key, int keyLen ) { if( keyLen == -1 ) keyLen = strlen( key ) + 1; int hashRec = hash(key,keyLen) % hashTableSize; int total = hashTableSize; while( total-- ) { ZHashRecord *recPtr = hashTable[hashRec]; if( recPtr ) { if( !(recPtr->flags & zhDELETED) ) { // Non-deleted element, compare if( !memcmp(key, recPtr->key, keyLen) ) { return hashTable[hashRec]; } } } else { // Empty record found before match, terminate search return 0; } hashRec = (hashRec+1) % hashTableSize; } return 0; } int ZHashTable::has( char *key, int keyLen ) { char *a = bgetb( key, keyLen ); return a ? 1 : 0; } int ZHashTable::getType ( char *key, int keyLen ) { int srcType = 0; int srcLen = 0; bgetb (key, -1, &srcLen, &srcType); return srcType; } char *ZHashTable::getS( char *key, char *onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, -1, &srcLen, &srcType ); if( src ) { if( srcType != zhSTR ) { convert( srcType, src, srcLen, zhSTR, &last, &lastLen ); return (char *)last; } else { return src; } } return onEmpty; } int ZHashTable::getI( char *key, int onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, -1, &srcLen, &srcType ); if( src ) { if( srcType != zhS32 ) { convert( srcType, src, srcLen, zhS32, &last, &lastLen ); return *(int *)last; } else { return *(int *)src; } } return onEmpty; } unsigned int ZHashTable::getU( char *key, unsigned int onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, -1, &srcLen, &srcType ); if( src ) { if( srcType != zhU32 ) { convert( srcType, src, srcLen, zhU32, &last, &lastLen ); return *(unsigned int *)last; } else { return *(unsigned int *)src; } } return onEmpty; } S64 ZHashTable::getL( char *key, S64 onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, -1, &srcLen, &srcType ); if( src ) { if( srcType != zhS64 ) { convert( srcType, src, srcLen, zhS64, &last, &lastLen ); return *(S64 *)last; } else { return *(S64 *)src; } } return onEmpty; } float ZHashTable::getF( char *key, float onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, -1, &srcLen, &srcType ); if( src ) { if( srcType != zhFLT ) { convert( srcType, src, srcLen, zhFLT, &last, &lastLen ); return *(float *)last; } else { return *(float *)src; } } return onEmpty; } double ZHashTable::getD( char *key, double onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, -1, &srcLen, &srcType ); if( src ) { if( srcType != zhDBL ) { convert( srcType, src, srcLen, zhDBL, &last, &lastLen ); return *(double *)last; } else { return *(double *)src; } } return onEmpty; } void *ZHashTable::getp( char *key, void *onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, -1, &valLen, &type ); if( s ) { assert( type == zhPTR || type == zhPFR ); assert( valLen == sizeof(void *) ); return *(void **)s; } return onEmpty; } char *ZHashTable::getb( char *key, void *onEmpty ) { // this gets you the address of the value in the hash (tfb 11feb2009) int type = 0; int valLen = 0; char *s = bgetb( key, -1, &valLen, &type ); if( s ) { return s; } return (char*)onEmpty; } int ZHashTable::geti( char *key, int onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, -1, &valLen, &type ); if( s ) { assert( type == zhS32 ); assert( valLen == sizeof(int) ); return *(int *)s; } return onEmpty; } unsigned int ZHashTable::getu( char *key, unsigned int onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, -1, &valLen, &type ); if( s ) { assert( type == zhU32 ); assert( valLen == sizeof(unsigned int) ); return *(unsigned int *)s; } return onEmpty; } S64 ZHashTable::getl( char *key, S64 onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, -1, &valLen, &type ); if( s ) { assert( type == zhS64 ); assert( valLen == sizeof(S64) ); return *(S64 *)s; } return onEmpty; } float ZHashTable::getf( char *key, float onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, -1, &valLen, &type ); if( s ) { assert( type == zhFLT ); assert( valLen == sizeof(float) ); return *(float *)s; } return onEmpty; } double ZHashTable::getd( char *key, double onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, -1, &valLen, &type ); if( s ) { assert( type == zhDBL ); assert( valLen == sizeof(double) ); return *(double *)s; } return onEmpty; } char *ZHashTable::bgetS( void *key, int keyLen, char *onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, keyLen, &srcLen, &srcType ); if( src ) { if( srcType != zhSTR ) { convert( srcType, src, srcLen, zhSTR, &last, &lastLen ); return (char*)last; } else { return (char*)src; } } return onEmpty; } int ZHashTable::bgetI( void *key, int keyLen, int onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, keyLen, &srcLen, &srcType ); if( src ) { if( srcType != zhS32 ) { convert( srcType, src, srcLen, zhS32, &last, &lastLen ); return *(int *)last; } else { return *(int*)src; } } return onEmpty; } unsigned int ZHashTable::bgetU( void *key, int keyLen, unsigned int onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, keyLen, &srcLen, &srcType ); if( src ) { if( srcType != zhU32 ) { convert( srcType, src, srcLen, zhU32, &last, &lastLen ); return *(unsigned int *)last; } else { return *(unsigned int *)src; } } return onEmpty; } S64 ZHashTable::bgetL( void *key, int keyLen, S64 onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, keyLen, &srcLen, &srcType ); if( src ) { if( srcType != zhS64 ) { convert( srcType, src, srcLen, zhS64, &last, &lastLen ); return *(S64 *)last; } else { return *(S64 *)src; } } return onEmpty; } float ZHashTable::bgetF( void *key, int keyLen, float onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, keyLen, &srcLen, &srcType ); if( src ) { if( srcType != zhFLT ) { convert( srcType, src, srcLen, zhFLT, &last, &lastLen ); return *(float *)last; } else { return *(float *)src; } } return onEmpty; } double ZHashTable::bgetD( void *key, int keyLen, double onEmpty ) { clearLast(); int srcType = 0; int srcLen = 0; char *src = bgetb( key, keyLen, &srcLen, &srcType ); if( src ) { if( srcType != zhDBL ) { convert( srcType, src, srcLen, zhDBL, &last, &lastLen ); return *(double *)last; } else { return *(double *)src; } } return onEmpty; } char *ZHashTable::bgetb( void *key, int keyLen, int *valLen, int *type, int touch ) { if( !key ) { if( valLen ) *valLen = 0; return 0; } if( keyLen==-1 ) keyLen = strlen( (char*)key ) + 1; int hashRec = hash((char*)key,keyLen) % hashTableSize; int total = hashTableSize; while( total-- ) { ZHashRecord *recPtr = hashTable[hashRec]; if( recPtr ) { if( !(recPtr->flags & zhDELETED) ) { // Non-deleted element, compare if( !memcmp(key, recPtr->key, keyLen) ) { // Found it if( touch ) { recPtr->flags |= zhCHANGED; hasAnyChanged = 1; } if( type ) { *type = recPtr->type; } if( valLen ) { *valLen = recPtr->valLen; if( recPtr->type == zhSTR ) { // Strings are one less than they say because we don't want to count the nul (*valLen)--; } } return &recPtr->key[recPtr->keyLen]; } } } else { // Empty record found before match, terminate search break; } hashRec = (hashRec+1) % hashTableSize; } if( valLen ) *valLen = 0; return 0; } void *ZHashTable::bgetp( void *key, int keyLen, void *onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, keyLen, &valLen, &type ); if( s ) { assert( type == zhPTR || type == zhPFR ); assert( valLen == sizeof(void *) ); return *(void **)s; } return onEmpty; } int ZHashTable::bgeti( void *key, int keyLen, int onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, keyLen, &valLen, &type ); if( s ) { assert( type == zhS32 ); assert( valLen == sizeof(int) ); return *(int *)s; } return onEmpty; } unsigned int ZHashTable::bgetu( void *key, int keyLen, unsigned int onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, keyLen, &valLen, &type ); if( s ) { assert( type == zhU32 ); assert( valLen == sizeof(unsigned int) ); return *(unsigned int *)s; } return onEmpty; } S64 ZHashTable::bgetl( void *key, int keyLen, S64 onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, keyLen, &valLen, &type ); if( s ) { assert( type == zhS64 ); assert( valLen == sizeof(S64) ); return *(S64 *)s; } return onEmpty; } float ZHashTable::bgetf( void *key, int keyLen, float onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, keyLen, &valLen, &type ); if( s ) { assert( type == zhFLT ); assert( valLen == sizeof(float) ); return *(float *)s; } return onEmpty; } double ZHashTable::bgetd( void *key, int keyLen, double onEmpty ) { int type = 0; int valLen = 0; char *s = bgetb( key, keyLen, &valLen, &type ); if( s ) { assert( type == zhDBL ); assert( valLen == sizeof(double) ); return *(double *)s; } return onEmpty; } char *ZHashTable::getKey( int i, int *keyLen ) { if( keyLen ) *keyLen = 0; if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( keyLen ) *keyLen = p->keyLen; return p->key; } } return 0; } void *ZHashTable::getValb( int i, int *valLen ) { if( valLen ) *valLen = 0; if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( valLen ) *valLen = p->valLen; return &p->key[p->keyLen]; } } return 0; } int ZHashTable::getFlags( int i ) { if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) return p->flags; } return 0; } int ZHashTable::getType( int i ) { if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) return p->type; } return 0; } char *ZHashTable::getValS( int i ) { clearLast(); if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( p->type != zhSTR ) { convert( p->type, &p->key[p->keyLen], p->valLen, zhSTR, &last, &lastLen ); return last; } else { return &p->key[p->keyLen]; } } } return 0; } int ZHashTable::getValI( int i ) { clearLast(); if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( p->type != zhS32 ) { convert( p->type, &p->key[p->keyLen], p->valLen, zhS32, &last, &lastLen ); return *(int *)last; } else { return *(int *)&p->key[p->keyLen]; } } } return 0; } unsigned int ZHashTable::getValU( int i ) { clearLast(); if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( p->type != zhU32 ) { convert( p->type, &p->key[p->keyLen], p->valLen, zhU32, &last, &lastLen ); return *(unsigned int *)last; } else { return *(unsigned int *)&p->key[p->keyLen]; } } } return 0; } S64 ZHashTable::getValL( int i ) { clearLast(); if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( p->type != zhS64 ) { convert( p->type, &p->key[p->keyLen], p->valLen, zhS64, &last, &lastLen ); return *(S64 *)last; } else { return *(S64 *)&p->key[p->keyLen]; } } } return 0; } float ZHashTable::getValF( int i ) { clearLast(); if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( p->type != zhFLT ) { convert( p->type, &p->key[p->keyLen], p->valLen, zhFLT, &last, &lastLen ); return *(float *)last; } else { return *(float *)&p->key[p->keyLen]; } } } return 0; } double ZHashTable::getValD( int i ) { clearLast(); if( 0 <= i && i < hashTableSize ) { ZHashRecord *p = hashTable[i]; if( p ) { if( p->flags & zhDELETED ) return 0; if( p->type != zhDBL ) { convert( p->type, &p->key[p->keyLen], p->valLen, zhDBL, &last, &lastLen ); return *(double *)last; } else { return *(double *)&p->key[p->keyLen]; } } } return 0; } void *ZHashTable::getValp( int i ) { int valLen = 0; void *s = getValb( i, &valLen ); if( s ) { assert( valLen == sizeof(void *) ); return *(void **)s; } return 0; } int ZHashTable::getVali( int i ) { int valLen = 0; void *s = getValb( i, &valLen ); if( s ) { assert( valLen == sizeof(int) ); return *(int *)s; } return 0; } unsigned int ZHashTable::getValu( int i ) { int valLen = 0; void *s = getValb( i, &valLen ); if( s ) { assert( valLen == sizeof(int) ); return *(unsigned int *)s; } return 0; } float ZHashTable::getValf( int i ) { int valLen = 0; void *s = getValb( i, &valLen ); if( s ) { assert( valLen == sizeof(float) ); return *(float *)s; } return 0.f; } double ZHashTable::getVald( int i ) { int valLen = 0; void *s = getValb( i, &valLen ); if( s ) { assert( valLen == sizeof(double) ); return *(double *)s; } return 0.0; } int ZHashTable::isS( char *key, char *cmp ) { char *val = getS( key ); if( val && cmp ) { return !strcmp( val, cmp ); } return 0; } // PUT //------------------------------------------------------------------------------------------ void ZHashTable::putB( char *key, char *val, int valLen ) { bputB( key, strlen(key)+1, val, valLen, zhBIN ); } void ZHashTable::putS( char *key, char *val, int valLen ) { bputB( key, strlen(key)+1, val, valLen, zhSTR ); } void ZHashTable::putI( char *key, int val ) { bputB( key, strlen(key)+1, (char *)&val, sizeof(val), zhS32 ); } void ZHashTable::putU( char *key, unsigned int val ) { bputB( key, strlen(key)+1, (char *)&val, sizeof(val), zhU32 ); } void ZHashTable::putL( char *key, S64 val ) { bputB( key, strlen(key)+1, (char *)&val, sizeof(val), zhS64 ); } void ZHashTable::putF( char *key, float val ) { bputB( key, strlen(key)+1, (char *)&val, sizeof(val), zhFLT ); } void ZHashTable::putD( char *key, double val ) { bputB( key, strlen(key)+1, (char *)&val, sizeof(val), zhDBL ); } void ZHashTable::putP( char *key, void *ptr, int freeOnReplace, int delOnNul ) { if( delOnNul && !ptr ) { del( key ); } else { bputB( key, -1, (char *)&ptr, sizeof(ptr), freeOnReplace ? zhPFR : zhPTR ); } } char *ZHashTable::bputB( void *key, int keyLen, char *val, int valLen, int type, int flags ) { if( keyLen == -1 ) { keyLen = strlen( (char*)key ) + 1; } if( valLen == -1 ) { valLen = 0; if( val ) { valLen = strlen( val ) + 1; } } hasAnyChanged = 1; if( val && numRecords >= hashTableSize / 2 - 1 ) { // If the table is 50% utilized, then go double its size // and rebuild the whole hash table int _numRecords = 0; int _hashTableSize = hashTableSize * 2; ZHashRecord **_hashTable = (ZHashRecord **)malloc( sizeof(ZHashRecord*) * _hashTableSize ); memset( _hashTable, 0, sizeof(ZHashRecord*) * _hashTableSize ); for( int i=0; i<hashTableSize; i++ ) { if( hashTable[i] && !(hashTable[i]->flags & zhDELETED) ) { // a non-deleted record to add to the new table internalSet( _hashTable, _hashTableSize, hashTable[i]->key, hashTable[i]->keyLen, hashTable[i] ); _numRecords++; } } free( hashTable ); hashTable = _hashTable; hashTableSize = _hashTableSize; numRecords = _numRecords; resizeCount++; resetCallback(); } if( val ) { ZHashRecord *recPtr; int recordSize = sizeof(ZHashRecord) + keyLen + valLen; if( fastModeAllocate ) { if( ! fastModeBuffer ) { fastModeBuffer = (char *)malloc( fastModeAllocate ); fastModePtr = fastModeBuffer; } else if( fastModePtr+recordSize >= &fastModeBuffer[fastModeAllocate] ) { fastModeResizes++; int newSize = fastModeAllocate * 2; fastModeBuffer = (char *)realloc( fastModeBuffer, newSize ); fastModePtr = &fastModeBuffer[fastModeAllocate]; fastModeAllocate = newSize; } recPtr = (ZHashRecord *)fastModePtr; fastModePtr += recordSize; } else { recPtr = (ZHashRecord *)malloc( recordSize ); } recPtr->flags = flags; recPtr->type = type; recPtr->keyLen = keyLen; recPtr->valLen = valLen; memcpy( recPtr->key, key, keyLen ); memcpy( &recPtr->key[keyLen], val, valLen ); numRecords += internalSet( hashTable, hashTableSize, (char*)key, keyLen, recPtr ); return &recPtr->key[keyLen]; } else { // Deleting record numRecords -= internalSet( hashTable, hashTableSize, (char *)key, keyLen, NULL ); return 0; } } void ZHashTable::bputS( void *key, int keyLen, char *val, int valLen ) { bputB( key, keyLen, val, valLen, zhSTR ); } void ZHashTable::bputI( void *key, int keyLen, int val ) { bputB( key, keyLen, (char *)&val, sizeof(val), zhS32 ); } void ZHashTable::bputU( void *key, int keyLen, unsigned int val ) { bputB( key, keyLen, (char *)&val, sizeof(val), zhU32 ); } void ZHashTable::bputL( void *key, int keyLen, S64 val ) { bputB( key, keyLen, (char *)&val, sizeof(val), zhS64 ); } void ZHashTable::bputF( void *key, int keyLen, float val ) { bputB( key, keyLen, (char *)&val, sizeof(val), zhFLT ); } void ZHashTable::bputD( void *key, int keyLen, double val ) { bputB( key, keyLen, (char *)&val, sizeof(val), zhDBL ); } void ZHashTable::bputP( void *key, int keyLen, void *ptr, int freeOnReplace, int delOnNul ) { if( delOnNul && !ptr ) { del( (char*)key, keyLen ); } else { bputB( key, keyLen, (char *)&ptr, sizeof(ptr), freeOnReplace ? zhPFR : zhPTR ); } } void ZHashTable::putEncoded( char *string ) { if( !string || !*string ) return; const int _START_KEY = 1; const int _START_UNIT = 2; const int _UNIT_QUOTE_ENDS = 3; const int _UNIT_SPACE_ENDS = 4; const int _UNIT_DONE = 5; const int _START_VAL = 6; int state = _START_KEY; char *buf = NULL; int bufCount; const int BUFSIZE = 4096; char key[BUFSIZE]; char val[BUFSIZE]; for( char *c=string; ; c++ ) { switch( state ) { case _START_KEY: state = _START_UNIT; buf = key; bufCount = 0; c--; break; case _START_UNIT: if( *c == '\'' ) { state = _UNIT_QUOTE_ENDS; } else if( *c != ' ' ) { state = _UNIT_SPACE_ENDS; c--; } break; case _UNIT_QUOTE_ENDS: if( *c == '\\' ) { // Escape c++; buf[bufCount++] = *c; assert( bufCount < BUFSIZE ); } else { if( *c == '\'' ) { buf[bufCount] = 0; state = _UNIT_DONE; } else { buf[bufCount++] = *c; assert( bufCount < BUFSIZE ); } } break; case _UNIT_SPACE_ENDS: if( *c == ' ' || (buf==key && *c == '=') || *c == 0 ) { c--; buf[bufCount] = 0; state = _UNIT_DONE; } else { buf[bufCount++] = *c; assert( bufCount < BUFSIZE ); } break; case _UNIT_DONE: if( buf == key ) { state = _START_VAL; } else { putS( key, val ); state = _START_KEY; } c--; break; case _START_VAL: buf = val; bufCount = 0; if( *c == '=' ) { state = _START_UNIT; } break; } if( *c == 0 && c >= string ) { break; } } } // TOUCH //------------------------------------------------------------------------------------------ char *ZHashTable::touchS( char *key, int keyLen ) { char *ptr = bgetb( key, keyLen, 0, 0, 1 ); if( !ptr ) { char *nulstr = ""; ptr = bputB( key, keyLen, nulstr, 1, zhSTR ); } return ptr; } int *ZHashTable::touchI( char *key, int keyLen ) { char *ptr = bgetb( key, keyLen, 0, 0, 1 ); if( !ptr ) { int zero = 0; ptr = bputB( key, keyLen, (char *)&zero, sizeof(zero), zhS32 ); } return (int *)ptr; } unsigned int *ZHashTable::touchU( char *key, int keyLen ) { char *ptr = bgetb( key, keyLen, 0, 0, 1 ); if( !ptr ) { unsigned int zero = 0; ptr = bputB( key, keyLen, (char *)&zero, sizeof(zero), zhU32 ); } return (unsigned int *)ptr; } S64 *ZHashTable::touchL( char *key, int keyLen ) { char *ptr = bgetb( key, keyLen, 0, 0, 1 ); if( !ptr ) { S64 zero = 0; ptr = bputB( key, keyLen, (char *)&zero, sizeof(zero), zhS64 ); } return (S64 *)ptr; } float *ZHashTable::touchF( char *key, int keyLen ) { char *ptr = bgetb( key, keyLen, 0, 0, 1 ); if( !ptr ) { float zero = 0; ptr = bputB( key, keyLen, (char *)&zero, sizeof(zero), zhFLT ); } return (float *)ptr; } double *ZHashTable::touchD( char *key, int keyLen ) { char *ptr = bgetb( key, keyLen, 0, 0, 1 ); if( !ptr ) { double zero = 0; ptr = bputB( key, keyLen, (char *)&zero, sizeof(zero), zhDBL ); } return (double *)ptr; } int ZHashTable::hasChanged() { return hasAnyChanged; } int ZHashTable::hasChanged( int i ) { if( 0 <= i && i < hashTableSize ) { ZHashRecord *c = hashTable[i]; if( c && !(c->flags & zhDELETED) ) { return (c->flags & zhCHANGED); } } return 0; } int ZHashTable::hasChanged( char *key, int keyLen ) { ZHashRecord *rec = lookup( key, keyLen ); if( rec && !(rec->flags & zhDELETED) ) { return (rec->flags & zhCHANGED); } return 0; } void ZHashTable::setChanged( int i ) { if( 0 <= i && i < hashTableSize ) { ZHashRecord *c = hashTable[i]; if( c && !(c->flags & zhDELETED) ) { c->flags |= zhCHANGED; } } } void ZHashTable::setChanged( char *key, int keyLen ) { ZHashRecord *rec = lookup( key, keyLen ); if( rec && !(rec->flags & zhDELETED) ) { rec->flags |= zhCHANGED; } } void ZHashTable::clearChanged( int i ) { if( 0 <= i && i < hashTableSize ) { ZHashRecord *c = hashTable[i]; if( c && !(c->flags & zhDELETED) ) { c->flags &= ~zhCHANGED; } } } void ZHashTable::clearChanged( char *key, int keyLen ) { ZHashRecord *rec = lookup( key, keyLen ); if( rec && !(rec->flags & zhDELETED) ) { rec->flags &= ~zhCHANGED; } } void ZHashTable::clearChangedAll() { for( int i=0; i<hashTableSize; i++ ) { clearChanged( i ); } hasAnyChanged = 0; } // FREE FUNCTIONS //------------------------------------------------------------------------------------------ ZHashTable *zHashTable( char *fmt, ... ) { static char temp[4096*4]; int size = 0; { va_list argptr; va_start( argptr, fmt ); vsprintf( temp, fmt, argptr ); va_end( argptr ); size = strlen(temp)+1; assert( size < sizeof(temp) ); } ZHashTable *h = new ZHashTable( 64, max(512,size*4) ); h->putEncoded( temp ); return h; } char *zHashTablePack( ZHashTable &hash, unsigned int *mallocSize/*=0*/ ) { int size = hash.size(); int i = 0; char *k, *v; int keyLen = 0; int valLen = 0; int count = 0; assert( sizeof(int) == 4 ); int len = 4 + 4 + 4 + 4; // Prefixed by version, endianness, len, and count for( i=0; i<size; i++ ) { k = (char *)hash.getKey( i, &keyLen ); v = (char *)hash.getValb( i, &valLen ); if( k ) { len += 4 + 4 + 4; // size of key, val, type len += keyLen; len += valLen; // ADD padding len += (4-(keyLen&3)) & 3; len += (4-(valLen&3)) & 3; count++; } } char zero[4] = { 0, }; char *buf = (char *)malloc( len ); if( mallocSize ) { *mallocSize = len; } char *d = buf + 16; for( i=0; i<size; i++ ) { k = (char *)hash.getKey( i, &keyLen ); v = (char *)hash.getValb( i, &valLen ); int keyPad = (4-(keyLen&3)) & 3; int valPad = (4-(valLen&3)) & 3; int type = hash.getType( i ); if( k ) { memcpy( d, &type, 4 ); d += 4; memcpy( d, &keyLen, 4 ); d += 4; memcpy( d, &valLen, 4 ); d += 4; memcpy( d, k, keyLen ); d += keyLen; memcpy( d, zero, keyPad ); d += keyPad; memcpy( d, v, valLen ); d += valLen; memcpy( d, zero, valPad ); d += valPad; } } char *version = "1.0\0"; strcpy( buf+0, version ); // version: so we can read older formats if changes are introduced *(int *)(buf+4) = zHashTableMachineIsBigEndian(); // endianness, for possible byteswap in unpack *(int *)(buf+8) = len; *(int *)(buf+12) = count; return buf; } int zHashTableUnpack( char *bin, ZHashTable &hash ) { char *s = bin; // GET VERSION char version[4]; memcpy( version, s, 4 ); assert( !strcmp( version, "1.0" ) ); s += 4; // DEAL WITH ENDIAN int byteswap = 0; int bigendian = *(int *)s; if( bigendian > 0 ) { bigendian = 1; } if( bigendian != zHashTableMachineIsBigEndian() ) { byteswap = 1; } s += 4; // LENGTH and COUNT for hash entries int len = *(int *)s; if( byteswap ) { BYTESWAP(len); } int origLen = len; s += 4; int count = *(int *)s; if( byteswap ) { BYTESWAP(count); } s += 4; // REMOVE header len -= 16; // EXTRACT each field with padding for( int i=0; i<count; i++ ) { int type = *(int *)s; if( byteswap ) { BYTESWAP(type); } s += 4; int keyLen = *(int *)s; if( byteswap ) { BYTESWAP(keyLen); } int keyPad = (4-(keyLen&3)) & 3; s += 4; int valLen = *(int *)s; if( byteswap ) { BYTESWAP(valLen); } int valPad = (4-(valLen&3)) & 3; s += 4; char *key = s; // Does the key need to be byteswapped? // HACKY solution: we don't know the "type" of the key, so we can't know when it needs // to be byte-swapped; typically keys are strings, which don't need to be. However, // if the key happens to be a numeric (atomic) type, it DOES need to be. So try to // detect the use of integer keys, and byteswap them. if( byteswap && keyLen==4 ) { printf( "WARNING: ambiguous key in zHashTableUnpack(): " ); if( isprint(key[0]) && isprint(key[1]) && isprint(key[2]) && key[3]==0 ) { printf( "(%s) - not swapped.\n", key ); // looks like a string, don't byteswap } else { zHashTableByteSwap( (unsigned char *)key, keyLen ); printf( "(%d) - swapped.\n", *(int*)key ); } } s += keyLen + keyPad; char *val = s; if( byteswap && type!=zhBIN && type!=zhSTR ) { zHashTableByteSwap( (unsigned char *)val, valLen ); } s += valLen + valPad; hash.bputB( key, keyLen, val, valLen, type ); len -= keyLen + valLen + keyPad + valPad + 4 + 4 + 4; } assert( len == 0 ); return origLen; } void zHashTableLoad( FILE *f, ZHashTable &hash ) { // f points to the size of the packed hash, but we need to peek a bit // further ahead to get at the endian flag in the hash. This inelegance // is because the pack/unpack were originally written to contain their // own endian info for network etc, and by doing this look-ahead we don't // have to require the caller to pass a byteswap flag to this function. int info[3]; fread( info, sizeof(int), 3, f ); int dataIsBigEndian = info[2] ? 1 : 0; int byteswap = dataIsBigEndian == zHashTableMachineIsBigEndian() ? 0 : 1; fseek( f, -(long)sizeof(int)*3, SEEK_CUR ); unsigned int bufSize; zHashTableFreadEndian( &bufSize, sizeof( bufSize ), 1, f, byteswap ); char *buf = (char *)malloc( bufSize ); fread( buf, bufSize, 1, f ); zHashTableUnpack( buf, hash ); free( buf ); } void zHashTableSave( ZHashTable &hash, FILE *f ) { unsigned int bufSize; char *buf = zHashTablePack( hash, &bufSize ); fwrite( &bufSize, sizeof( bufSize ), 1, f ); fwrite( buf, bufSize, 1, f ); free( buf ); } #ifdef ZHASHTABLE_SELF_TEST #pragma message( "BUILDING ZHASHTABLE_SELF_TEST" ) #include "math.h" #include "ztime.h" void main() { int i, j; // INSERT a bunch of things into the table and remember them in a separate list #define TESTS (10000) struct Test { char *key; int keyLen; int type; int size; union { char *bin; char *str; int s32; unsigned int u32; S64 s64; float flt; double dbl; }; } tests[TESTS]; // The free copy is taking a long time, I think that it might be because there's some // weird fragmentation. To stop this, pre allocate all of the compare memory // and just increment a pointer, never freeing it. int bufSize = (sizeof(Test)+150) * TESTS; char *buffer = (char *)malloc( bufSize ); char *tail = &buffer[ bufSize ]; char *ptr = buffer; // ZHashTable hash( 64, 0 ); // ZHashTable hash( 64, TESTS*256 ); // ZHashTable hash( TESTS * 4, TESTS * 256, 0 ); ZHashTable hash( TESTS * 4, TESTS * 256, 1 ); int totalCollisions = 0; int totalReallocs = 0; int totalResizes = 0; srand( 0 ); ZTime start = zTimeNow(); zprofReset( -1 ); zprofBeg( root ); for( int trials=0; trials<200; trials++ ) { printf( "trial %d\n", trials ); ptr = buffer; zprofBeg( write_block ); for( i=0; i<TESTS; i++ ) { //printf( "put: i = %d\n", i ); tests[i].keyLen = rand() % 16 + 4; tests[i].key = ptr; ptr += tests[i].keyLen; assert( ptr < tail ); for( j=0; j<tests[i].keyLen; j++ ) { tests[i].key[j] = rand() % 256; } tests[i].type = ( rand() % (zhDBL - zhBIN) ) + zhBIN; switch( tests[i].type ) { case zhBIN: tests[i].size = rand() % 100; tests[i].bin = ptr; ptr += tests[i].size; assert( ptr < tail ); for( j=0; j<tests[i].size; j++ ) { tests[i].bin[j] = rand() % 256; } zprofBeg( real_write ); hash.bputB( tests[i].key, tests[i].keyLen, tests[i].bin, tests[i].size ); zprofEnd(); break; case zhSTR: tests[i].size = rand() % 100; tests[i].str = ptr; ptr += tests[i].size+1; assert( ptr < tail ); for( j=0; j<tests[i].size; j++ ) { tests[i].str[j] = (rand() % 255) + 1; } tests[i].str[ tests[i].size ] = 0; zprofBeg( real_write ); hash.bputS( tests[i].key, tests[i].keyLen, tests[i].str ); zprofEnd(); break; case zhS32: tests[i].s32 = rand(); zprofBeg( real_write ); hash.bputI( tests[i].key, tests[i].keyLen, tests[i].s32 ); zprofEnd(); break; case zhU32: tests[i].u32 = rand(); zprofBeg( real_write ); hash.bputU( tests[i].key, tests[i].keyLen, tests[i].u32 ); zprofEnd(); break; case zhS64: tests[i].s64 = ( ((long long)rand()) << 32 ) | rand(); zprofBeg( real_write ); hash.bputL( tests[i].key, tests[i].keyLen, tests[i].s64 ); zprofEnd(); break; case zhFLT: tests[i].flt = (float)rand(); zprofBeg( real_write ); hash.bputF( tests[i].key, tests[i].keyLen, tests[i].flt ); zprofEnd(); break; case zhDBL: tests[i].dbl = (double)rand(); zprofBeg( real_write ); hash.bputD( tests[i].key, tests[i].keyLen, tests[i].dbl ); zprofEnd(); break; //case zhPTR: //case zhPFR: } } zprofEnd(); // QUERY back out zprofBeg( read_block ); for( i=0; i<TESTS; i++ ) { switch( tests[i].type ) { case zhBIN: { int valLen; char *val = hash.bgetb( tests[i].key, tests[i].keyLen, &valLen ); assert( valLen == tests[i].size ); assert( ! memcmp( val, tests[i].bin, tests[i].size ) ); break; } case zhSTR: { char *val = hash.bgetS( tests[i].key, tests[i].keyLen ); assert( (int)strlen(val) == tests[i].size ); assert( ! strcmp( val, tests[i].str ) ); break; } case zhS32: { int val = hash.bgetI( tests[i].key, tests[i].keyLen ); assert( val == tests[i].s32 ); break; } case zhU32: { unsigned int val = hash.bgetU( tests[i].key, tests[i].keyLen ); assert( val == tests[i].u32 ); break; } case zhS64: { S64 val = hash.bgetL( tests[i].key, tests[i].keyLen ); assert( val == tests[i].s64 ); break; } case zhFLT: { float val = hash.bgetF( tests[i].key, tests[i].keyLen ); assert( val == tests[i].flt ); break; } case zhDBL: { double val = hash.bgetD( tests[i].key, tests[i].keyLen ); assert( val == tests[i].dbl ); break; } //case zhPTR: //case zhPFR: } } zprofEnd(); zprofBeg( hash_clear ); totalCollisions += hash.getCollisions(); totalReallocs += hash.getFastModeResizes(); totalResizes += hash.getResizeCount(); hash.clear(); zprofEnd(); } zprofEnd(); zprofSortTree(); zprofDumpToFile( "prof.txt", "root" ); FILE *f = fopen( "prof.txt", "a" ); fprintf( f, "collisions = %d fastModeReallocs = %d resizes = %d\n", totalCollisions, totalReallocs, totalResizes ); fclose( f ); // baseline: 19.5, 19.8 // eliminating read made no difference... it's all in write // Test that last is getting deleted // Test conversions // Test all the gets and puts // Test the get(int i) are workign // Test isS // Test touches // Test Encoded // Test del // Test change flags // Test pointers, pointer frees // test on empty /* ZHashTable table( 1 ); table.putS( "key1", "val1" ); table.putS( "key2", "val2" ); // test that it doesn't find key3 assert( table.getS( "key3" ) == 0 ); // test that it does find keys 1 & 2 assert( !strcmp( table.getS( "key1" ), "val1" ) ); assert( !strcmp( table.getS( "key2" ), "val2" ) ); // test deleting key1 table.putS( "key1", 0 ); assert( table.getS( "key1" ) == 0 ); // test all of the various binary and text funcs char binKey[4] = { (char)0x00, (char)0x01, (char)0x00, (char)0x02 }; char binVal[4] = { (char)0x00, (char)0x00, (char)0xFF, (char)0x00 }; table.bputB( binKey, 4, binVal, 4 ); int fetchBinValLen = 0; char *fetchBinVal = table.get ( binKey, 4, &fetchBinValLen ); assert( !memcmp( fetchBinVal, binVal, 4 ) ); assert( fetchBinValLen == 4 ); table.putS( "key3", "123456789", 4 ); assert( !memcmp( table.getS("key3"), "1234", 4 ) ); table.putI( "key4", 1234 ); assert( table.getI("key4") == 1234 ); table.putF( "key5", 1234.56f ); assert( fabs(table.getF("key5") - 1234.56f) < 0.01f ); table.putD( "key6", 1234.56789 ); assert( table.getD("key6") == 1234.56789 ); table.puti( "key7", 0xFFFFFFFF ); assert( table.geti("key7") == -1 ); table.putf( "key8", 1234.56f ); assert( table.getf("key8") == 1234.56f ); table.putd( "key9", 1234.56 ); assert( table.getd("key9") == 1234.56 ); // test the buffer usage char *buf0 = (char *)malloc( 6 ); strcpy( buf0, "test0" ); char *buf1 = (char *)malloc( 6 ); strcpy( buf1, "test1" ); table.putp( "key10", buf0, 1 ); assert( table.getp("key10") == buf0 ); // test that it get's freed when it is overwritten table.putp( "key10", buf1, 1 ); #ifdef _DEBUG #ifdef WIN32 // In win32 debug the freed buffer will be overwritten with "0xdd" assert( table.getp("key10") == buf1 ); assert( !memcmp( buf0, "\xdd\xdd\xdd\xdd\xdd", 5 ) ); #endif #endif // test that it isn't freed if it isn't asked to table.putp( "key11", buf1, 0 ); table.putp( "key11", 0 ); assert( table.getp("key11") == 0 ); assert( !memcmp( buf1, "test1", 5 ) ); table.iputS( 0, "123456789", 4 ); assert( !memcmp( table.igetS(0), "1234", 4 ) ); table.iputI( 1, 1234 ); assert( table.igetI(1) == 1234 ); table.iputF( 2, 1234.56f ); assert( fabs(table.igetF(2) - 1234.56f) < 0.01f ); table.iputD( 3, 1234.56789 ); assert( table.igetD(3) == 1234.56789 ); table.iputi( 4, 0xFFFFFFFF ); assert( table.igeti(4) == -1 ); table.iputf( 5, 1234.56f ); assert( table.igetf(5) == 1234.56f ); table.iputd( 6, 1234.56 ); assert( table.igetd(6) == 1234.56 ); char *buf2 = (char *)malloc( 5 ); strcpy( buf2, "test" ); table.iputp( 7, buf2 ); assert( !strcmp((char*)table.igetp(7),"test") ); // @TODO // test all the the getVal types // test that the pointer type works and frees correctly // even when there is a double delete // test double delete table.clear( 4 ); table.putS( "key1", "val1" ); table.putS( "key1", 0 ); table.putS( "key1", "val2" ); table.putS( "key1", 0 ); table.putS( "key1", "val3" ); table.putEncoded( "key1=val1 'key 2'=val2 key3='val 3' 'key\\'4'='val\\'4'" ); assert( !strcmp(table.getS( "key1" ), "val1") ); assert( !strcmp(table.getS( "key 2" ), "val2") ); assert( !strcmp(table.getS( "key3" ), "val 3") ); char *a = table.getS( "key'4" ); assert( !strcmp(a, "val'4") ); table.putI( "inttest", 0xffffffff ); int b = table.getI( "inttest" ); */ } #endif
import { palette } from 'lib/styles/palette'; import transitions from 'lib/styles/transitions'; import React, { useEffect } from 'react'; import styled from 'styled-components'; import ModalPortal from './ModalPortal'; interface IModalInnerStyled { width: number; height: number; isModal: boolean; } interface ModalTemplateProps extends IModalInnerStyled { children: React.ReactNode; className?: string; onToggleModal: () => void; } function ModalTemplate({ width, height, isModal, children, className, onToggleModal, ...rest }: ModalTemplateProps) { useEffect(() => { if (isModal) window.document.body.style.overflow = 'hidden'; return () => { window.document.body.style.overflow = 'unset'; }; }, [isModal]); return ( <ModalPortal> <ModalTemplateBlock onMouseDown={onToggleModal} {...rest}> <ModalInner width={width} height={height} isModal={isModal} className={className} onMouseDown={(e) => e.stopPropagation()} > {children} </ModalInner> <ModalBackground /> </ModalTemplateBlock> </ModalPortal> ); } const ModalTemplateBlock = styled.div` position: fixed; width: 100%; height: 100%; top: 0; left: 0; z-index: 9999; `; const ModalInner = styled.div<IModalInnerStyled>` position: absolute; z-index: 9999; background-color: ${palette.white}; top: 0; bottom: 0; right: 0; left: 0; margin: auto; width: ${({ width }) => width}px; height: ${({ height }) => height}px; border-radius: 12px; animation: ${transitions.fadeIn} 0.4s ease-in-out; `; const ModalBackground = styled.div` display: block; width: 100%; height: 100%; background-color: ${palette.black}; position: absolute; left: 0; top: 0; opacity: 0.4; `; export default ModalTemplate;
import React, { useState } from "react"; import axios from "axios"; import crossIcon from "../../assets/images/cross_icon.png"; /** * This is the EditFormChat modal that allows users to edit the topic of a resource * @param {{onClose: function, topics: Array<string>, getThreads: function, currentTopic: string, chatId: string}} props Properties for the EditFormChat component * @returns {React.Component} EditFormChat modal */ export default function EditFormChat({ onClose, topics, getThreads, currentTopic, chatId }) { const [topicid, setTopicid] = useState(currentTopic); const [title, setTitle] = useState(`Save as ${currentTopic}`); /** * A function to handle submission of a topic to which to transfer the resource to */ function handleChangeTopic() { // Check if the title already exists in topics if (topicid === currentTopic) { onClose(); return; } axios .post(`http://localhost:8000/edit_topic`, { userid: localStorage.getItem("ideagen_user_id"), chatid: chatId, topicid: topicid, prevtopicid: currentTopic, }) .then( (response) => { //console.log(response) getThreads(); onClose(); }, (error) => { console.log(error); } ); }; /** * A function to handle the change in the selected topic * @param {string} value The topic selected */ function handleTopicId(value) { setTopicid(value); if (value === currentTopic) { setTitle(`Save as ${currentTopic}`); } else { setTitle("Save"); } }; return ( <> <div className="fixed inset-0 bg-black opacity-50 z-40"></div> <div className="fixed top-1/4 left-1/2 transform -translate-x-1/2 bg-white p-8 rounded-md shadow-md w-80 md:w-96 md:scale-110 max-w-full z-50"> <div className="flex justify-between mb-4"> <div> <h2 className="text-xl font-bold text-left">Change Idea Bracket</h2> <p className="text-gray-500 text-left"> Organize your thoughts better </p> </div> <button onClick={onClose} className="text-gray-600 hover:text-gray-800 absolute top-4 right-4" > <img src={crossIcon} alt="Close" className="h-4 w-4" /> </button> </div> {/* Select with any radiobox */} <div className="flex flex-col space-y-2"> <label htmlFor="topic" className="text-gray-700 text-left"> Choose a topic </label> <select id="topic" className="border border-gray-300 p-2 rounded-lg" onChange={(e) => handleTopicId(e.target.value)} > {topics.map((topic, index) => ( <option key={index} value={topic}> {topic} </option> ))} </select> </div> <button onClick={handleChangeTopic} className="bg-gray-300 hover:bg-gray-400 text-white p-2 rounded-full w-full mt-4" disabled={!title} > {title} </button> </div> </> ); };
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiplicationTableThreads { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); Runnable task1 = () -> { System.out.println("Thread 1 (5's table): New -> Runnable"); displayTable(5, 1, 5); System.out.println("Thread 1: Runnable -> Terminated"); }; Runnable task2 = () -> { System.out.println("Thread 2 (10's table): New -> Runnable"); displayTable(10, 6, 10); System.out.println("Thread 2: Runnable -> Terminated"); }; executor.submit(task1); executor.submit(task2); executor.shutdown(); } private static void displayTable(int num, int start, int end) { for (int i = start; i <= end; i++) { System.out.println(num + " * " + i + " = " + (num * i)); } } }
--- title: "DLL 2021, R section" author: - "mesako" - "Margaret" - "Samson" - "Zac" - "darachm" date: "Typeset on 2021-06-18" output: bookdown::gitbook: css: style.css config: toc: before: | <li><a href="./">DLL 2021 R workshops</a></li> edit: https://github.com/darachm/dll-r/edit/main/%s download: ["html"] #,"pdf"] highlight: zenburn includes: after_body: footer.html #number_sections: false split_by: section documentclass: book github-repo: darachm/dll-r description: "A living syllabus for the R section of DLL 2021, at Stanford" #site: bookdown::bookdown_site #biblio-style: apalike #link-citations: yes --- # Workshop Introduction This short 3-day course in R aims to give you a basic framework and skills for working effectively with your research mentors. Together, we will get oriented with basic skills (e.g. using RStudio, documenting your process with R Markdown, reading data in, basic data analysis, and visualization) and concepts for how to organize your research workflows in R. We intend for this starting point to empower you to accomplish research-related tasks in R. R is a high-level data analysis scripting language ^[and also a "GNU" project, apparently!]. While it is very easy to write programs in this language, it is designed first as an environment that stitches together cutting edge research methods with flexible visualization and reporting frameworks. R has swept to be the de facto high-level language for data analysis because of the rich ecosystem of dispersed open-source developers. [Here's some examples](https://www.r-graph-gallery.com/) of plots you generate in R. [Here's an example](https://bioconductor.org/packages/release/workflows/vignettes/cytofWorkflow/inst/doc/cytofWorkflow.html) of the types of workflows and analyses you can generate in R (all the plots, and the website too). Heck, this website is generated by the R package `bookdown` from Rmd files, which you will learn to write. ## Workshop goals <!-- darach: I thought it might be good for this section to be more specific, whadda think? revert/change back if that's a no --> We aim for all participants to be able to: - use the [Rstudio IDE](https://www.rstudio.com/products/rstudio/) (open source edition) - know how to store and manipulate data in variables - read in data from computer files in various formats - process these with functions to generate statistical summaries - turn these into various plots using the base graphics and ggplot2 library - read in packages from various sources and know how to start using them - do these steps in workflows that scale to analyzing many many files - write all of this up as an Rmarkdown file to report your analysis and findings to collaborators ## Structure and resources ### Workshop schedule Each day will have a slightly different schedule, but you can expect a mix of synchronous and asynchronous work sessions, as well as two breaks in that day's workshop. Please visit each day's specific page for the exact schedule: + [Day 3 Schedule](https://darachm.github.io/dll-r/day-3-intoduction-to-r.html) + [Day 4 Schedule](https://darachm.github.io/dll-r/day-4-tidyverse-and-visualizations.html) + [Day 5 Schedule](https://darachm.github.io/dll-r/day-5-building-workflows-using-packages-writing-reusable-code-sharing-analyses.html) Each time segment lists who among the teaching team will be around to assist. We encourage you to poke the Slack channel (so below for info) with questions, but you can feel free to tag (@) or directly message the person responsible for the time slot/content you have questions about. ### Asynchronous sessions Asynchronous here means self-paced learning that takes place off-Zoom. You will be expected to progress through this website during asynchronous work time in this 3-day period. We developed this website/document for your reference, as a living textbook and collection of "slides" and code snippets. As you go through this website during the asynchronous sessions, you should also complete the exercises provided in the accompanying worksheets. If you have questions and/or need help, you should reach out to us and your peers on Slack. We are also happy to jump into a Zoom call to work through issues with you. Tips: - You can shrink the table of contents (left) by clicking the four lines icon in the top menu. - You can click on footnotes ^[to read them, then go back by clicking the arrow]. #### Slack channel While you are working in asynchronous sessions, or if you just need help during the remainder of your program, there is a Slack channel available where you can go for ideas/help. The channel is called *#learn-R* and should be accessible to you on the SSRP Slack server. ### Synchronous sessions Synchronous here means live, group learning that takes place on-Zoom. During synchronous meetings, you should plan to work directly with your peers and us on focused tasks. We will also be there to help with confusing or challenging topics that you want to discuss with someone live. During the schedule synchronous session (check each day's schedule for timing), you should log on to the provided Zoom link. ## Workshop expectations 1. Be respectful and compassionate. 2. Teach one another, learn from one another. 3. Aim for productive struggle. + You will learn best if you make a good faith effort before seeking help. + However, you should always seek help if you feel truly stuck. 4. Create your own sense of challenge. + Pick activities that you will learn and grow from. + If you don't find something challenging, make it challenging for yourself.