text
stringlengths
184
4.48M
<?php namespace App\Http\Requests; use App\Exceptions\ApiFailedException; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; class ResumeRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'personal_profile' => 'nullable|array', 'personal_profile.name' => 'required|string|max:255', 'personal_profile.job_title' => 'required|string|max:255', 'personal_profile.email' => 'nullable|string|email|max:255', 'personal_profile.phone_number' => 'nullable|string|max:255', 'personal_profile.city' => 'nullable|string|max:255', 'personal_profile.country' => 'nullable|string|max:255', 'personal_profile.summary' => 'nullable|string', 'education' => 'nullable|array', 'education.*.year' => 'required|string', 'education.*.degree' => 'required|string|max:255', 'education.*.school' => 'required|string|max:255', 'expertise' => 'nullable|array', 'expertise.*.name' => 'required|string|max:255', 'skills_and_experience' => 'nullable|array', 'skills_and_experience.*.year' => 'required|string', 'skills_and_experience.*.organization' => 'required|string|max:255', 'skills_and_experience.*.job' => 'required|string|max:255', 'skills_and_experience.*.title' => 'required|string|max:255', 'skills_and_experience.*.description' => 'nullable|string', 'courses' => 'nullable|array', 'courses.*.year' => 'required|string', 'courses.*.name' => 'required|string|max:255', 'extra_curricular_activities' => 'nullable|array', 'extra_curricular_activities.*' => 'required|string|max:255', 'languages' => 'nullable|array', 'languages.*' => 'required|string|max:255', 'hobbies' => 'nullable|array', 'hobbies.*' => 'required|string|max:255', 'certificates' => 'nullable|array', 'certificates.*.year' => 'required|string', 'certificates.*.authority' => 'required|string|max:255', 'certificates.*.title' => 'required|string|max:255', 'certificates.*.title' => 'required|string|max:255', 'custom_sections' => 'nullable|array', 'custom_section.*.title' => 'required|string|max:255', 'custom_section.*.description' => 'required|string|max:255', 'certificates.*.header' => 'required|string|max:255', 'certificates.*.title' => 'required|string|max:255', 'certificates.*.description' => 'required|string|max:255', ]; } /** * Handle a failed validation attempt for API. */ protected function failedValidation(Validator $validator) { if (request()->is('api/*')) { throw new ApiFailedException($validator->errors()); } } }
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function buildTree(preorder: number[], inorder: number[]): TreeNode | null { return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); }; function build( preorder: number[], preStart: number, preEnd: number, inorder: number[], inStart: number, inEnd: number ): TreeNode | null { if (preStart > preEnd) return null; // 前序遍历根节点就是第一个 const rootVal = preorder[preStart]; let index = 0; // 找中序遍历的根节点的位置 for (let value of inorder) { if (value === rootVal) { index = inorder.indexOf(value); } } let leftSize = index - inStart; let root = new TreeNode(rootVal); root.left = build( preorder, preStart + 1, leftSize + preStart, inorder, inStart, index - 1); root.right = build( preorder, leftSize + preStart + 1, preEnd, inorder, index + 1, inEnd ) return root; }
import React from 'react'; import PageTitle from '../PageTitle'; import '../../stylesheets/portfolio.css'; import ProjectCard from './ProjectCard'; import { projects } from './ProjectData'; const Portfolio = () => { const title = 'My Latest Project'; const desc = 'Checkout my latest JavaScript, React and Rails projects'; return ( <div className="projects-page"> <PageTitle title={title} desc={desc} /> <ul className="projects-container"> {projects.map((project, index) => ( <li id={`project-container${index + 1}`} className="project-container-all" key={`project-${project.id}`} > <ProjectCard status={project.status} title={project.title} projectLink={project.projectLink} liveLink={project.liveLink} /> </li> ))} </ul> </div> ); }; export default Portfolio;
# Zitadel Postrges Traefik Secure This repo is a minimal template to use Traefik v2 on localhost with HTTPS support. To get started, just clone this repo: ## Thanks [traefik-v2-https-ssl-localhost](https://github.com/Heziode/traefik-v2-https-ssl-localhost) [jimsgarage zitadel](https://github.com/JamesTurland/JimsGarage/tree/main/Zitadel) [jimsgargage youtube](https://www.youtube.com/watch?v=1T1uxKW06Vs) ```bash git clone https://github.com/fluffy-bunny/zitadel-traefik-secure.git ``` Next, go to the root of the repo (`cd zitadel-traefik-secure`) and generate certificates using [mkcert](https://github.com/FiloSottile/mkcert) : ```bash # If it's the firt install of mkcert, run mkcert -install # Generate certificate for domain "localhost.dev" mkcert -cert-file certs/local-cert.pem -key-file certs/local-key.pem "localhost.dev" "*.localhost.dev" ``` Create networks that will be used by Traefik: ```bash docker network create proxy ``` Now, start containers with : ```bash # Start Zitadel docker-compose -f docker-compose.yml up -d ``` You can now go to your browser at [whoami.localhost.dev](https://whoami.localhost.dev), enjoy :rocket: ! You can now go to your browser at [zitadel.localhost.dev](https://zitadel.localhost.dev), enjoy :rocket: ! You can now go to your browser at [pgadmin.localhost.dev](https://pgadmin.localhost.dev), enjoy :rocket: ! You can now go to your browser at [smtp.localhost.dev](https://smtp.localhost.dev), enjoy :rocket: ! *Note: you can access to Træfik dashboard at: [traefik.localhost.dev](https://traefik.localhost.dev)* Don't forget that you can also map TCP and UDP through Træfik. ## hosts file Windows ```txt 127.0.0.1 localhost.dev traefik.localhost.dev whoami.localhost.dev smtp.localhost.dev zitadel.localhost.dev pgadmin.localhost.dev ``` ## Zitadel SMTP I configured zitadel to use SMTP4DEV ```bash smtp4dev:25 ``` [smtp4dev localhost](https://smtp.localhost.dev/) ## License MIT
from django.shortcuts import render, HttpResponse from django.http import JsonResponse from rest_framework import viewsets, status #gives access to @api_view decorator from rest_framework.decorators import api_view # access to Django REST Framework page with JSON data from rest_framework.response import Response from .serializers import * from .models import * import json # (from Digital Ocean Tutorial) # from .serializers import TodoSerializer # Create your views here. # class TODOView(viewsets.ModelViewSet): # serializer_class = TodoSerializer # queryset = TODO.objects.all() @api_view(['GET']) def apiRoutes(request): # api_urls = { # 'List': '/user-list/', # 'Detail View': '/user-detail/<str:pk>/', # 'Create': '/user-create/', # 'Update': '/user-update/<str:pk>/', # 'Delete': '/user-delete/<str:pk>/', # } api_urls = { 'List': '/thing-list/', 'Detail View': '/thing-detail/<str:pk>/', 'Create': '/thing-create/', 'Update': '/thing-update/<str:pk>/', 'Delete': '/thing-delete/<str:pk>/', } return Response(api_urls) @api_view(['GET']) def thingList(request): # getting the django model instances things = Thing.objects.all().order_by('id') # then putting those models into the correct serializer for that model + amount serializer = ThingSerializer(things, many=True) return Response(serializer.data) @api_view(['GET']) def thingDetail(request, pk): thing = Thing.objects.get(id=pk) serializer = ThingSerializer(thing, many=False) return Response(serializer.data) @api_view(['POST']) def thingCreate(request): # parse the request.data serializer = ThingSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: print(serializer.errors) return Response(serializer.errors) @api_view(['POST']) def thingUpdate(request, pk): thing = Thing.objects.get(id=pk) serializer = ThingSerializer(instance=thing,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['DELETE']) def thingDelete(request, pk): thing = Thing.objects.get(id=pk) thing.delete() return Response("Item deleted!") @api_view(['POST']) def songCreate(request): serializer = SongSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: print(serializer.errors) return Response(serializer.errors) @api_view(['GET']) def songList(request): songs = Song.objects.all().order_by('id') print(songs) serializer = SongSerializer(songs, many=True) return Response(serializer.data) #-------------------- Testing out hyper linked model serializer viewsets -------------------------------# # class view for hyper model serializer class HyperViewSet(viewsets.ModelViewSet): serializer_class = HyperUserSerializer queryset = User.objects.all() class HyperViewDetail(viewsets.ModelViewSet): serializer_class = HyperUserSerializer queryset = User.objects.all() def retrieve(self, request, pk=None): try: user = self.queryset.get(id=pk) serializer = self.serializer_class(user, context={'request': request}) return Response(serializer.data) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND)
import random import numpy as np from PIL import Image as image # 进行聚类中心获取 def get_centroids(data, clusters, k): k_centroids = [] for i in range(k): cluster_indices = np.nonzero(clusters[:, :, 0] == i) cluster_points = data[cluster_indices] centroids = np.mean(cluster_points, axis=0) k_centroids.append(centroids) return k_centroids # 判断是否有同样的样本 def is_same(centroids, cmp): for centroid in centroids: if np.all(centroid == cmp): return True return False # k_means++算法计算与中心最近距离 def nearest(point, centroids): min_dist = np.inf m = np.shape(centroids)[0] for i in range(m): dist = distance(point, centroids[i]) if min_dist < dist: min_dist = dist return min_dist # 用于k_means++算法获得初始中心 def rand_center_plus_plus(data, k: int = 2): centroids = [] x = np.random.randint(0, np.shape(data)[0]) y = np.random.randint(0, np.shape(data)[1]) centroids.append([data[x][y]]) dist = [] for i in range(1, k): sum_all = 0 for j in range(np.shape(data)[0]): for ids in range(np.shape(data)[1]): dist.append((nearest(data[j][ids], centroids), (j, ids))) sum_all += dist[-1] sum_all = random.random() * sum_all for di in dist: sum_all -= di[0] if sum_all > 0: continue centroids.append(di[1]) break return centroids # 进行中心随机生成 def rand_center(data, k: int = 2): centroids = [] print(np.shape(data)) for i in range(0, k): x = np.random.randint(0, np.shape(data)[0]) y = np.random.randint(0, np.shape(data)[1]) while is_same(centroids, data[x][y]): x = np.random.randint(0, np.shape(data)[0]) y = np.random.randint(0, np.shape(data)[1]) centroids.append(data[x][y]) return centroids # 进行欧式距离计算 def distance(vec_a, vec_b): vec_a = np.array(vec_a) vec_b = np.array(vec_b) return np.linalg.norm(vec_a - vec_b) # 生成图片 def make_picture(data, clusters): pic_new = image.new("RGB", (np.shape(data)[0], np.shape(data)[1])) # 颜色表 color_state = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [255, 0, 255]] for i in range(clusters.shape[0]): for j in range(clusters.shape[1]): pic_new.putpixel((i, j), tuple(color_state[int(clusters[i, j, 0])])) pic_new.save("result.jpeg", "JPEG") def run_kmeans(data, k): print("----- 随机初始化center --------") centroids = rand_center(data, k) print("进行计算") clusters = np.zeros((np.shape(data)[0], np.shape(data)[1], 2)) changed = True op = 0 while changed: print("第{}次计算".format(op)) op += 1 changed = False for i in range(np.shape(data)[0]): for j in range(np.shape(data)[1]): min_dist = np.inf cluster_id = -1 for ids in range(k): dist = distance(data[i][j], centroids[ids]) if dist < min_dist: cluster_id = ids min_dist = dist if clusters[i, j, 0] != cluster_id: changed = True clusters[i, j, 0] = cluster_id clusters[i, j, 1] = min_dist centroids = get_centroids(data, clusters, k) make_picture(data, clusters) print("----- finished -----")
<h2 class="text-info">Manage Users <small class="text-muted">For <holder id="txt-org-name"></holder></small> <button class="btn btn-outline-secondary" id="btn-show-users" disabled="disabled">Show Users</button></h2> <hr class="mb-12"> <form class="form-inline"> <div class="form-group mb-2"> <label for="staticfilter" class="sr-only">Search </label> <input id="staticfilter" type="search" class="form-control-plaintext light-table-filter" data-table="order-table" placeholder="Search keyword here.."> </div> </form> <div class="table-responsive"> <table class="sortable table table-striped table-hover table-sm order-table"> <caption>Existing users for <holder id="txt-org-name-table"></holder> </caption> <thead> <tr> <th>#</th> <th></th> <th>Full Name</th> <th>ID</th> <th>Phone</th> </tr> </thead> <tbody id="allExistingUsers"> </tbody> </table> </div> <hr class="mb-4"> <center class="align-center"> <button type="button" class="btn btn-outline-primary" id="btn-add-new" data-toggle="modal" data-target="#modal-add-user">Add New User</button> <button type="button" class="btn btn-outline-secondary">Bulk Add New User</button> </center> <!-- MODAL: Add New User --> <div class="modal fade" id="modal-add-user" tabindex="-1" role="dialog" aria-labelledby="modal-add-user-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modal-add-user-label">Add New User</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="user-name" class="col-form-label">Full Name:</label> <input type="text" class="form-control" id="user-name" placeholder="Eg: Muhammad Bin Abdullah"> </div> <div class="row"> <div class="col-auto"> <label class="" for="user-mobile">Mobile Number:</label> <div class="input-group mb-2"> <div class="input-group-prepend"> <div class="input-group-text">+</div> </div> <input type="text" class="form-control" id="user-mobile" placeholder="Ex: 60122557193"> </div> </div> </div> <!-- ./row--> <div class="form-group"> <label for="user-id" class="col-form-label">Student ID:</label> <input type="text" class="form-control" id="user-id" placeholder="Eg: UMC123456"> </div> <div class="form-group"> <hr class="mb-4"> <span class="text-muted">This user's <text class="text-dark">organization</text> will be set to <holder class="text-dark" id="txt-org-name-modal"></holder>.</span> <hr class="mb-4"> </div> <input type="hidden" id="user-organization-unique-id"> <input type="hidden" id="user-organization"> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="btnAddUserSave"">Add & Assign User</button> </div> </div> </div> </div> <script> $('#modal-add-user').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // Button that triggered the modal var organization = button.data('organization') // Extract info from data-* attributes var modal = $(this) modal.find('.modal-title').text(organization + ': Add & Assign New User') //modal.find('#session-org').val(organization) }) </script> <!-- MODAL: EDIT User --> <div class=" modal fade" id="modal-edit-user" tabindex="-1" role="dialog" aria-labelledby="modal-edit-user-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modal-edit-user-label">Edit user</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="user-name-2" class="col-form-label">Full Name:</label> <input type="text" class="form-control" id="user-name-2" placeholder="Eg: Muhammad Bin Abdullah"> </div> <div class="row"> <div class="col-auto"> <label class="" for="user-mobile-2">Mobile Number:</label> <div class="input-group mb-2"> <div class="input-group-prepend"> <div class="input-group-text">+</div> </div> <input type="text" class="form-control" id="user-mobile-2" placeholder="Ex: 60122557193"> </div> </div> </div> <!-- ./row--> <div class="form-group"> <label for="user-id-2" class="col-form-label">Student ID:</label> <input type="text" class="form-control" id="user-id-2" placeholder="Eg: UMC123456"> </div> <div class="form-group"> <hr class="mb-4"> <span class="text-muted">This user <text class="text-dark">organization</text> is <holder class="text-dark" id="txt-org-name-modal-2"></holder>.</span> <hr class="mb-4"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="btnEditUserSave">Save</button> </div> </div> </div> </div> <script> $('#modal-edit-user').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // Button that triggered the modal var organization = button.data('organization') // Extract info from data-* attributes var name = button.data('name') var uniqueId = button.data('unique-id') var phone = button.data('phone') var modal = $(this) modal.find('.modal-title').text('Edit User ' + name) $('#user-name-2').val(name); $('#user-mobile-2').val(phone); console.log("organization is:" + organization); $('#user-id-2').val(uniqueId); $('#txt-org-name-modal-2').html(organization); //modal.find('#session-org').val(organization) }) </script> <!-- MODAL: ASSIGN SESSION TO User --> <div class="modal fade" id="modal-assign-session" tabindex="-1" role="dialog" aria-labelledby="modal-assign-session-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modal-assign-session-label">Assign sessions.</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class=""">Simply tick the sessions that is relevant for this user to assign him/her to that session.</p> <table class=" table table-sm table=hover"> <thead> <tr> <th scope="col">Course Name</th> <th scope="col">Assign</th> </tr> </thead> <tbody id="assignTableBody"> </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <script> $('#modal-assign-session').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // Button that triggered the modal var organization = button.data('organization') // Extract info from data-* attributes var name = button.data('name') var uniqueId = button.data('unique-id') var mobile = button.data('mobile') var modal = $(this) modal.find('.modal-title').html('Assign session for <text class="text-primary">' + name + '</text> <small classs="text-muted">(' + uniqueId + ')<small>') modal.find('assign_UFE1003').on('click', updateAssignment(mobile)) db.collection('sessions/UMC/2019-4/').doc("ZQiQQSsr6SCHOI0PfqoB") .get().then(function () { if () }) }) </script> <script> console.log("Hello from " + window.location.pathname + window.location.search); firebase.auth().onAuthStateChanged(function (user) { if (user) { //console.log("user.providerData[0].phoneNumber.substring(1) is " + user.providerData[0].phoneNumber.substring(1)); console.log("ayam"); db.collection("users").where("phone", "==", user.providerData[0].phoneNumber.substring(1)) .get().then(function (userData) { userData.forEach(function (userSingle) { console.log("Current userSingle is: " + userSingle.data().organization); $('#txt-name-top').html(userSingle.data().name); $('#txt-org-name').html(userSingle.data().organization); $('#txt-org-name-table').html(userSingle.data().organization); $('#btn-add-new').attr("data-organization", userSingle.data().organization); $('#txt-org-name-modal').html(userSingle.data().organization); $('#btn-show-users').attr("onClick", 'loadExistingUsers("' + userSingle.data().organization + '")'); $('#user-organization-unique-id').val(userSingle.data().organization_unique_id); $('#user-organization').val(userSingle.data().organization); //loadExistingUsers(userSingle.data().organization); }) // Populate Modal Body Table for Assinment db.collection("sessions/UMC/2019-4/") .get().then(function (allSessions) { var tableBody = document.getElementById('assignTableBody'); while (tableBody.firstChild) { tableBody.removeChild(tableBody.firstChild); } allSessions.forEach(function (eachSession) { console.log("Now eachSession: " + eachSession.data().session_name); var row = document.createElement('tr'); var cellName = document.createElement('td'); cellName.appendChild(document.createTextNode(eachSession.data().session_name)); var cellAction = document.createElement('td'); cellAction.innerHTML = '<form> ' + '<div class="form-check"> ' + ' <input type="checkbox" class="form-check-input" id="assign_' + eachSession.data().session_code + '"> ' + ' <label class="sr-only" for="exampleCheck1">Assign User</label> ' + '</div>' '</form>'; var cellActionNew = document.createElement('td'); cellActionNew.innerHTML = '<a href="#" id="assign_' + eachSession.data().session_code + '"><span class="label label-success">Assign</span></a>'; row.appendChild(cellName); row.appendChild(cellActionNew); tableBody.appendChild(row); }); }).catch(function (e) { console.log("Error getting list of sessions:", e); }); }).then(function () { console.log("Err.... Done?"); $('#btn-show-users').removeAttr('disabled'); }).catch(function (e) { console.log("Error fetching user details: ", e); }); } else { console.log("User NOT signed in."); } }); function loadExistingUsers(orgName) { //console.log("orgName requested is: " + orgName); db.collection("users").where("organization", "==", orgName) .onSnapshot(function (allUsers) { var tableBody = document.getElementById('allExistingUsers'); while (tableBody.firstChild) { tableBody.removeChild(tableBody.firstChild); } var i = 1; allUsers.forEach(function (eachUser) { console.log("Now processing: " + eachUser.data().name); var row = document.createElement('tr'); var cellNum = document.createElement('td'); cellNum.appendChild(document.createTextNode(i)); var cellAction = document.createElement('td'); cellAction.innerHTML = '<button class="btn btn-small" ' + 'onClick="deleteUser("' + orgName + '","' + eachUser.id + '")" ' + 'data-toggle="tooltip" data-placement="top" title="Delete User">' + '<i class="far fa-trash-alt text-danger"></i>' + '</button> ' + '<button class="btn btn-small" ' + ' data-toggle="modal" data-target="#modal-assign-session" ' + ' data-unique-id="' + eachUser.id + '" ' + ' data-name="' + eachUser.data().name + '" ' + ' data-mobile="' + eachUser.data().phone + '" ' + ' data-toggle="tooltip" data-placement="right" title="Assign Session">' + '<i class="fas fa-calendar-check text-primary"></i>' + '</button>'; var cellName = document.createElement('td'); cellName.innerHTML = '<a href="#" data-toggle="modal" data-target="#modal-edit-user" ' + ' data-name="' + eachUser.data().name + '" ' + ' data-organization="' + eachUser.data().organization + '" ' + ' data-phone="' + eachUser.data().phone + '" ' + ' data-unique-id="' + eachUser.id + '" ' + ' >' + eachUser.data().name + '</a>'; var cellId = document.createElement('td'); cellId.appendChild(document.createTextNode(eachUser.id)); var cellPhone = document.createElement('td'); cellPhone.appendChild(document.createTextNode(eachUser.data().phone)); row.appendChild(cellNum); row.appendChild(cellAction); row.appendChild(cellName); row.appendChild(cellId); row.appendChild(cellPhone); tableBody.appendChild(row); i = i + 1; }); // Hide show users buttons $('#btn-show-users').hide(); // Enable Tooltips $(function () { $('[data-toggle="tooltip"]').tooltip() }) }).catch(function (e) { console.log("Error fetching all existing user of " + orgName + " :", e); }); } function deleteUser(userId, orgName) { document.preventDefault() db.collection("users/").doc(userId).delete().then(function () { console.log("Deleted user " + userId); loadExistingUsers(orgName); }).catch(function (e) { console.log("Error deleting user " + userId + ": ", e); }); } $('#btnEditUserSave').on('click', function () { //$(this).preventDefault() db.collection("users/").doc($('#user-id-2').val()) .update({ name: $('#user-name-2').val(), phone: $('#user-mobile-2').val(), }).then(function () { console.log("saved user "); $('#modal-edit-user').modal('hide') }).catch(function (e) { console.log("Error saving user:", e); }); }) $('#btnAddUserSave').on('click', function () { //$(this).preventDefault() db.collection("users/").doc($('#user-id').val()) .set({ name: $('#user-name').val(), phone: $('#user-mobile').val(), organization: $('#user-organization').val(), organization_unique_id: $('#user-organization-unique-id').val(), unique_id: $('#user-id').val() }, { merge: true }).then(function () { console.log("Saved new user!"); }).catch(function (e) { console.log("Error saving new user:", e); }); db.collection("auth_users/").doc($('#user-mobile').val()) .set({ active: true }).then(function () { console.log("Added user auth!"); $('#modal-add-user').modal('hide') }).catch(function (e) { console.log("Error saving user auth:", e); }); }) function updateAssignment(mobile) { console.log("updateAssignment called!"); // Create a reference to the SF doc. var sfDocRef = db.collection("sessions/UMC/2019-4/").doc("ZQiQQSsr6SCHOI0PfqoB"); return db.runTransaction(function (transaction) { // This code may get re-run multiple times if there are conflicts. return transaction.get(sfDocRef).then(function (sfDoc) { if (!sfDoc.exists) { throw "Document does not exist!"; } var existingParticipants = sfDoc.data().session_participants; existingParticipants.push(String(mobile)); console.log("New existingParticipants is: " + JSON.stringify(existingParticipants)); transaction.update(sfDocRef, { session_participants: existingParticipants }); }); }).then(function () { console.log("Transaction successfully committed!"); $('#modal-assign-session').modal('hide'); }).catch(function (error) { console.log("Transaction failed: ", error); }); } </script>
import Sequelize from 'sequelize'; const { Op } = Sequelize; const getRandomIndex = (size) => Math.floor(Math.random() * size); const shuffleCards = (cards) => { for (let i = 0; i < cards.length; i += 1) { const randomIndex = getRandomIndex(cards.length); const currentItem = cards[i]; const randomItem = cards[randomIndex]; cards[i] = randomItem; cards[randomIndex] = currentItem; } return cards; }; const makeDeck = () => { const deck = []; const suits = ['♥️', '♦️', '♣️', '♠️']; for (let i = 0; i < suits.length; i += 1) { const currentSuit = suits[i]; for (let j = 1; j <= 13; j += 1) { let cardName = j; if (cardName === 1) { cardName = 'A'; } else if (cardName === 11) { cardName = 'J'; } else if (cardName === 12) { cardName = 'Q'; } else if (cardName === 13) { cardName = 'K'; } let cardRank = j; if (cardRank > 10) { cardRank = 10; } const card = { name: cardName, suit: currentSuit, rank: cardRank, }; deck.push(card); } } return deck; }; const getWinner = (p1Hand, p2Hand) => { const p1Score = p1Hand[0].rank + p1Hand[1].rank; const p2Score = p2Hand[0].rank + p2Hand[1].rank; if (p1Score > p2Score) return 1; if (p1Score < p2Score) return 2; return 0; }; export default function initGamesController(db) { const create = async (req, res) => { const cardDeck = shuffleCards(makeDeck()); const newGame = { gameState: { cardDeck, player1Hand: [], player2Hand: [], }, }; try { const user = await db.User.findByPk(req.cookies.userId); // find current user if (!user) throw new Error('cannot find user'); const game = await db.Game.create(newGame); // create row in games table if (!game) throw new Error('cannot create new game'); const opponent = await db.User.findOne({ // find a random user that is NOT current user where: { id: { [Op.not]: req.cookies.userId } }, order: Sequelize.literal('random()'), }); if (!opponent) throw new Error('cannot find opponent'); // !!! PLAYER NUMBER AND SCORE NOT LOGGED IN DB !!! // create row in games_users table await game.addUser(user, { through: { playerNumber: 1, score: 0 } }); // create row for opponent in games_users table await game.addUser(opponent, { through: { playerNumber: 1, score: 0 } }); res.send({ id: game.id, user: user.email, opponent: opponent.email, }); } catch (error) { res.status(500).send(error); } }; const get = async (req, res) => { const { id } = req.params; try { const game = await db.Game.findByPk(id); if (!game) throw new Error('cannot find game'); res.send({ player1Hand: game.gameState.player1Hand, player2Hand: game.gameState.player2Hand, winner: game.gameState.winner, }); } catch (error) { res.status(500).send(error); } }; const deal = async (req, res) => { const { id } = req.params; try { const game = await db.Game.findByPk(id); if (!game) throw new Error('cannot find game'); // make sure that deck has at least 4 cards, if not make new deck if (game.gameState.cardDeck.length < 4) { game.gameState.cardDeck = shuffleCards(makeDeck()); } // deal 2 cards to each player const player1Hand = [game.gameState.cardDeck.pop(), game.gameState.cardDeck.pop()]; const player2Hand = [game.gameState.cardDeck.pop(), game.gameState.cardDeck.pop()]; // calculate card ranks to get winner const winner = getWinner(player1Hand, player2Hand); // update db await game.update({ gameState: { cardDeck: game.gameState.cardDeck, player1Hand, player2Hand, winner, }, }); res.send({ player1Hand, player2Hand, winner, }); } catch (error) { res.status(500).send(error); } }; return { create, get, deal }; }
<!DOCTYPE html> <html lang="pt-br" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>API REST Senai</title> <style> /* Estilos CSS anteriores aqui */ body { font-family: Arial, sans-serif; } h1 { color: #333; } h2 { margin-top: 20px; color: #555; } table { border-collapse: collapse; width: 100%; margin-top: 10px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } tr:nth-child(even) { background-color: #f2f2f2; } form { margin-top: 20px; } .form-group { margin-bottom: 10px; } .form-group label { display: block; font-weight: bold; margin-bottom: 5px; } .form-group input[type="text"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; } .form-group input[type="submit"], .form-group button { background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px; } .form-group input[type="submit"]:hover, .form-group button:hover { background-color: #45a049; } .delete-btn { background-color: #f44336; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px; } .delete-btn:hover { background-color: #d32f2f; } </style> </head> <body> <h1>API REST Senai</h1> <h2>Responsáveis</h2> <table> <thead> <tr> <th>ID</th> <th>Nome</th> <th>Ações</th> </tr> </thead> <tbody> <tr th:each="responsavel : ${responsaveis}"> <td th:text="${responsavel.id}"></td> <td th:text="${responsavel.nome}"></td> <td> <form th:action="@{'/responsavel/' + ${id}}" method="post"> <input type="hidden" name="_method" value="delete"> <button type="submit" class="delete-btn">Excluir</button> </form> </td> </tr> </tbody> </table> <form id="formResponsavel" action="/responsavel" method="post"> <div class="form-group"> <label for="idResponsavel">ID:</label> <input type="text" id="idResponsavel" name="idResponsavel" required> </div> <div class="form-group"> <label for="nomeResponsavel">Nome:</label> <input type="text" id="nomeResponsavel" name="nomeResponsavel" required> </div> <div class="form-group"> <input type="submit" value="Cadastrar Responsável"> </div> </form> <h2>Ambientes</h2> <table> <thead> <tr> <th>ID</th> <th>Nome</th> <th>Ações</th> </tr> </thead> <tbody> <tr th:each="ambiente : ${ambientes}"> <td th:text="${ambiente.id}"></td> <td th:text="${ambiente.nome}"></td> <td> <form action="/ambiente/{id}" method="post"> <button type="submit" class="delete-btn">Excluir</button> </form> </td> </tr> </tbody> </table> <form id="formAmbiente" action="/ambiente" method="post"> <div class="form-group"> <label for="idAmbiente">ID:</label> <input type="text" id="idAmbiente" name="idAmbiente" required> </div> <div class="form-group"> <label for="nomeAmbiente">Nome:</label> <input type="text" id="nomeAmbiente" name="nomeAmbiente" required> </div> <div class="form-group"> <input type="submit" value="Cadastrar Ambiente"> </div> </form> <h2>Ativos Patrimoniais</h2> <table> <thead> <tr> <th>ID</th> <th>Nome</th> <th>Ações</th> </tr> </thead> <tbody> <tr th:each="ativo : ${ativos}"> <td th:text="${ativo.id}"></td> <td th:text="${ativo.nome}"></td> <td> <form action="/ativo/{id}" method="post"> <button type="submit" class="delete-btn">Excluir</button> </form> </td> </tr> </tbody> </table> <form id="formAtivo" action="/ativo" method="post"> <div class="form-group"> <label for="idAtivo">ID:</label> <input type="text" id="idAtivo" name="idAtivo" required> </div> <div class="form-group"> <label for="nomeAtivo">Nome:</label> <input type="text" id="nomeAtivo" name="nomeAtivo" required> </div> <div class="form-group"> <input type="submit" value="Cadastrar Ativo"> </div> </form> </body> </html>
import Overlay from "./Overlay"; import Wrapper from "./Wrapper"; import FigureContainer from "./FigureContainer"; import SmallLake from "./images/Lake_Misasako.jpg"; import Mountains from "./images/mountains.jpg"; import Lake from "./images/lake.jpg"; import Forest from "./images/forest.jpg"; // import Beach from "./images/IMG_20200717_130156_985.jpg"; import { useState } from "react"; import { FaHtml5, FaCss3Alt, FaReact, FaGitAlt, FaGithub, FaWordpress, FaNpm, } from "react-icons/fa"; import { BsBootstrap } from "react-icons/bs"; import { TbBrandJavascript } from "react-icons/tb"; import { SiSass, SiNetlify, SiTypescript } from "react-icons/si"; const Section = () => { const [galleryVisible, setGalleryVisible] = useState(false); const [detailsVisible, setDetailsVisible] = useState({ project1: false, project2: false, project3: false, project4: false, }); const toggleDetails = (project) => { setDetailsVisible((prevState) => ({ ...prevState, [project]: !prevState[project], })); }; return ( <> <section id="homepage" className="homepage flex__row--center-center"> {/* <img src={Beach} alt="" /> */} <Overlay /> <Wrapper /> </section> <section className="section section__about flex__col--center-center"> <div className="container"> <div className="wrapper about__container"> <article className="self-contained"> <img src={Mountains} alt="mountains" /> <h2 className="heading__secondary">Quick History</h2> <p className="paragraph"> I spent two years of my professional life helping clients find their visual identities and bring them to light in the best way possible. I have worked with small and large businesses including Jeffries and Madison, Harper and Partners Inc., Stipple Unlimited, and Arivaci & Co. </p> </article> <article className="self-contained"> <img src={Mountains} alt="mountains" /> <h2 className="heading__secondary">self-taught web developer</h2> <p className="paragraph"> I spent two years of my professional life helping clients find their visual identities and bring them to light in the best way possible. I have worked with small and large businesses including Jeffries and Madison, Harper and Partners Inc., Stipple Unlimited, and Arivaci & Co. </p> </article> <article className="self-contained"> <img src={Mountains} alt="mountains" /> <h2 className="heading__secondary">Amateur Photographer</h2> <p className="paragraph"> I spent two years of my professional life helping clients find their visual identities and bring them to light in the best way possible. I have worked with small and large businesses including Jeffries and Madison, Harper and Partners Inc., Stipple Unlimited, and Arivaci & Co. </p> </article> </div> </div> </section> <section id="about" className="section section__skills flex__col--center-center" > <div className="container"> <div className="wrapper"> <span className="color-primary span__page--title">My Skills</span> <div className="self-contained"> <h3>Front End</h3> <ul className="skills__list"> <li> <FaHtml5 style={{ color: "chocolate" }} /> <span>HTML</span> </li> <li> <FaCss3Alt style={{ color: "deepskyblue" }} /> <span>CSS</span> </li> <li> <TbBrandJavascript style={{ color: "yellow" }} /> <span>JavaScript</span> </li> <li> <FaReact style={{ color: "aqua" }} /> <span>React</span> </li> <li> <BsBootstrap style={{ color: "orchid" }} /> <span>BootStrap</span> </li> <li> <SiSass style={{ color: "hotpink" }} /> <span>SCSS</span> </li> </ul> </div> <div className="self-contained"> <h3>version control</h3> <ul className="skills__list group2"> <li> <FaGitAlt style={{ color: "orangered" }} /> <span>Git</span> </li> <li> <FaGithub /> <span>GitHub</span> </li> <li> <SiNetlify style={{ color: "teal" }} /> <span>Netlify</span> </li> </ul> </div> <div className="self-contained"> <h3>familiar with</h3> <ul className="skills__list group3"> <li> <SiTypescript style={{ color: "dodgerblue" }} /> <span>TypeScript</span> </li> <li> <FaWordpress style={{ color: "white" }} /> <span>WordPress</span> </li> <li> <FaNpm style={{ color: "red" }} /> <span>NPM</span> </li> </ul> </div> </div> </div> </section> <section className="section section__gallery"> {!galleryVisible ? ( <div className="overlay overlay--drk flex__col--center-center"> <h2 className="heading__secondary"> I am also a passionate Amatuer photographer </h2> <button className="btn gallery__reveal-btn" onClick={() => setGalleryVisible(true)} > view my Photography Gallery </button> </div> ) : ( /* <span className="color-primary span__page--title">Photography</span> */ <div className="grid__container"> <div className="grid__image image--1"> <img src={Mountains} alt="nature" /> </div> <div className="grid__image image--2"> <img src={SmallLake} alt="nature" /> </div> <div className="grid__image image--3"> <img src={SmallLake} alt="nature" /> </div> <div className="grid__image image--4"> <img src={Lake} alt="nature" /> </div> <div className="grid__image image--5"> <img src={Forest} alt="nature" /> </div> <div className="grid__image image--6"> <img src={SmallLake} alt="nature" /> </div> <div className="grid__image image--7"> <img src={Lake} alt="nature" /> </div> <div className="grid__image image--8"> <img src={Forest} alt="nature" /> </div> <div className="grid__image image--9"> <img src={Mountains} alt="nature" /> </div> <div className="grid__image image--10"> <img src={SmallLake} alt="nature" /> </div> <div className="grid__image image--11"> <img src={SmallLake} alt="nature" /> </div> <div className="grid__image image--12"> <img src={Forest} alt="nature" /> </div> <div className="grid__image image--13"> <button className="btn gallery__hide-btn" onClick={() => setGalleryVisible(false)} > Hide Photography Gallery </button> <button className="btn gallery__instagram-btn"> View More on Instagram </button> </div> </div> )} </section> <section id="portfolio" className="section section__portfolio flex__col--center-center" > <div className="container"> <h2 className="heading__secondary">Portfolio</h2> <div className="margin-tb--md"> <FigureContainer detailsVisible={detailsVisible} toggleDetails={toggleDetails} /> </div> </div> </section> </> ); }; export default Section;
<?php namespace matpoppl\ImageCaptcha; class GDImage { public $gd; private $width = null; private $height = null; private function __construct($gd, $width = null, $height = null) { if (! $gd) { throw new \InvalidArgumentException('Unsupported GD resource'); } $this->gd = $gd; $this->width = $width; $this->height = $height; } public function __destruct() { if ($this->gd) { imagedestroy($this->gd); } $this->gd = null; } public function getWidth() { if (null === $this->width) { $this->width = imagesx($this->gd); } return $this->width; } public function getHeight() { if (null === $this->height) { $this->height = imagesy($this->gd); } return $this->height; } public function scale($ratio) { $width = $this->getWidth() * $ratio; $height = $this->getHeight() * $ratio; $gd = imagescale($this->gd, $width, $height, \IMG_NEAREST_NEIGHBOUR); return new static($gd, $width, $height); } public function affine(array $affine, $clip = null) { $gd = imageaffine($this->gd, $affine, $clip); return new static($gd, null, null); } public function addColor($color) { if (is_int($color)) { return $color; } if (is_string($color)) { $color = self::hex2rgb($color); } if (! is_array($color)) { throw new \InvalidArgumentException('Unsupported color definition'); } switch (count($color)) { case 4: list($r, $g, $b, $a) = $color; break; case 3: $a = null; list($r, $g, $b) = $color; break; default: throw new \UnexpectedValueException('Unsupported color count'); break; } $color = (null === $a) ? imagecolorallocate($this->gd, $r, $g, $b) : imagecolorallocatealpha($this->gd, $r, $g, $b, $a); return $color; } public function background($color) { imagefill($this->gd, 0, 0, $this->addColor($color)); return $this; } public function stroked($size, $x, $y, $textcolor, $strokecolor, $str, $px) { $textcolor = $this->addColor($textcolor); $strokecolor = $this->addColor($strokecolor); for($c1 = ($x-abs($px)), $z1 = ($x+abs($px)); $c1 <= $z1; $c1++) { for($c2 = ($y-abs($px)), $z2 = ($y+abs($px)); $c2 <= $z2; $c2++) { imagestring($this->gd, $size, $c1, $c2, $str, $strokecolor); } } imagestring($this->gd, $size, $x, $y, $str, $textcolor); return $this; } public function applyNoise() { $inthalf = mt_getrandmax() / 2; for ($y1 = 0; $y1 < $this->height;) { $x2 = 0; for ($x1 = 0; $x1 < $this->width;) { $x2 = $x1 + mt_rand(1, 10); $y2 = $y1 + mt_rand(1, 10); $color = $this->addColor(self::randomRGBA(true)); if (mt_rand() < $inthalf) { imageline($this->gd, $x2, $y2, $x1, $y1, $color); } else { imageline($this->gd, $x1, $y1, $x2, $y2, $color); } $x1 += mt_rand(4, 8); } $y1 += mt_rand(4, 8); } return $this; } public function applyWave($period = 10, $amplitude = 5) { $img = $this->gd; $width = $this->getWidth(); $height = $this->getHeight(); $p = $period * rand(1, 3); $k = mt_rand(0, 100); for ($i = 0; $i<$width; $i++) { $dst_y = intval( sin($k+$i/$p) * $amplitude ); imagecopy($img, $img, $i-1, $dst_y, $i, 0, 1, $height); } $k = mt_rand(0,100); for ($i = 0; $i<$height; $i++) { $dst_x = intval( sin($k+$i/$p) * $amplitude ); imagecopy($img, $img, $dst_x, $i-1, 0, $i, $width, 1); } return $this; } public static function createWithDims($width, $height) { $gd = imagecreatetruecolor($width, $height); return new static($gd, $width, $height); } public static function randomRGBA($ignoreAlpha = false) { $max = 255; $r = mt_rand(0, $max); $g = mt_rand(0, $max); $b = mt_rand(0, $max); $a = $ignoreAlpha ? null : mt_rand(0, 25); return [$r, $g, $b, $a]; } public static function hex2rgb($hex) { $hex = trim($hex, '# '); $a = null; if (strlen($hex) < 5) { $parts = str_split($hex, 1); $parts[0] .= $parts[0]; $parts[1] .= $parts[1]; $parts[2] .= $parts[2]; } else { $parts = str_split($hex, 2); } if (4 === count($parts)) { $a = hexdec(strlen($parts[3]) < 2 ? $parts[3].$parts[3] : $parts[3]); if ($a > 127) { $a /= 2; } } list($r, $g, $b) = array_map('hexdec', $parts); return [$r, $g, $b, $a]; } }
<div class="mt-4"> <app-search-profile [withUsernameField]="false" [endPointResource]="'employee'" (searchCompleted)="searchCompleted($event)"></app-search-profile> </div> <div> <div id="divData" style="display:none;" class="card-shadow"> <form [formGroup]="frmGroup" (validSubmit)="formSubmit()"> <div> <div class="card card-no-shadow"> <div class="card-header"> Employee </div> <div class="card-body mb-4"> <div class="col-sm-12"> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Workday Number</label> <input type="number" class="form-control" placeholder="######" formControlName="workdayNumber"> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Identification Card</label> <input type="number" class="form-control" placeholder="#-####-####" formControlName="identificationCard"> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Company Site</label> <select #site class="form-select" aria-label="Default select example" formControlName="site" (change)="getBanks(site.value)"> <option value="">-- Please choose one --</option> <option *ngFor="let site of initData?.sites" [value]="site.value"> {{site.display}}</option> </select> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">My Supervisor</label> <input type="text" class="form-control" placeholder="My Supervisor" matInput formControlName="supervisor" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn"> <mat-option *ngFor="let sup of filteredOptions | async" [value]="sup.value"> {{sup.display}} </mat-option> </mat-autocomplete> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">First Name</label> <input type="text" #code class="form-control" placeholder="first name" formControlName="firstName" [value]="this.frmGroup.get('firstName')?.value | titlecase"> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Last Name</label> <input type="text" class="form-control" placeholder="last name" formControlName="lastName" [value]="this.frmGroup.get('lastName')?.value |titlecase"> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Birth Date</label> <input type="text" class="form-control" formControlName="birthDate" placeholder="mm/dd/yyyy" [matDatepicker]="BirthDate" (click)="BirthDate.open()" (dateChange)="setAge($event.value)"> <mat-datepicker #BirthDate></mat-datepicker> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Age</label> <input type="number" class="form-control" readonly placeholder="##" formControlName="age"> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Job Title</label> <select class="form-select" aria-label="Default select example" formControlName="jobTitle"> <option value="">-- Please choose one --</option> <option *ngFor="let job of initData?.jobs" [value]="job.value" [disabled]="!job.isActive">{{job.display}}</option> </select> </div> </div> <div class="col-sm-12 col-md-6"> <label class="form-label">Salary</label> <div class="input-group"> <input type="number" class="form-control" placeholder="############" formControlName="salary"> <span class="input-group-text">.00</span> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Bank Name</label> <select class="form-select" formControlName="bankName"> <option value="">-- Please choose one --</option> <option *ngFor="let bank of banks" [value]="bank.value"> {{bank.display}}</option> </select> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Bank Account Number</label> <input type="text" class="form-control" placeholder="IBAN ##################" formControlName="bacAccountNumber"> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Hire Date</label> <input type="text" class="form-control" placeholder="mm/dd/yyyy" [matDatepicker]="hireDate" formControlName="hireDate" (click)="hireDate.open()"> <mat-datepicker #hireDate></mat-datepicker> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label class="form-label">Fire Date</label> <input type="text" class="form-control" placeholder="mm/dd/yyyy" [matDatepicker]="fireDate" formControlName="fireDate" (click)="fireDate.open()"> <mat-datepicker #fireDate></mat-datepicker> </div> </div> </div> <div class="row"> <div class="col-12"> <div class="form-group"> <div class="d-grid mt-4"> <button type="button" [ngClass]="{ 'btn-danger': !isActive, 'btn-success': isActive }" class="btn btn-block" btnCheckbox formControlName="isActive"> <i *ngIf="isActive" class="far fa-check-square"></i> <i *ngIf="!isActive" class="far fa-square"></i> {{ isActive ? 'Enable' : 'Disable' }} </button> </div> </div> </div> </div> </div> </div> <div class="card-footer"> <button type="submit" id="cmdSave" class="btn btn-primary mt-1 mb-1" style="margin-right: 10px;" [disabled]="isSaving"> <i *ngIf="!isSaving" class="fa fa-save"></i> <i *ngIf="isSaving" class="fas fa-sync fa-spin"></i> Save </button> <button type="button" id="cmdCancel" class="btn btn-danger" (click)="closeForm()"> <i class="fa fa-times"></i> Cancel </button> </div> </div> </div> </form> </div> </div> <div class="mt-4"> <div class="card"> <div class="card-header"> <i class="fas fa-project-diagram"></i> Employees </div> <div class="card-body mt-4"> <div class="table-responsive"> <table id="tblResult" datatable [dtOptions]="dtOptions" class="table table-striped table-bordered w-100"> <thead> <tr> <th style="width: 110px;">Workday #</th> <th style="width: 280px;">Name</th> <th>Id Card</th> <th>Status</th> <th style="width: 5px;">&nbsp;</th> </tr> </thead> <tbody></tbody> </table> </div> </div> <div class="card-footer"> <button type="button" class="btn btn-primary" (click)="add()"> <i class="fa fa-plus"></i> Add new </button> </div> </div> </div>
import { builtinEquations } from "./logic/equations"; import { InputData, Interval, NumberFunction, OrdinaryDifferentialEquation, Point, } from "./logic/definitions"; /** Абстрактный класс чтения входных данных. */ abstract class Reader { protected abstract get selectedEquationIndex(): number; protected abstract get rawX0(): string; protected abstract get rawY0(): string; protected abstract get rawDifferentiateIntervalStart(): string; protected abstract get rawDifferentiateIntervalEnd(): string; protected abstract get rawStep(): string; protected abstract get rawEpsilon(): string; /** Считать входные данные. */ public async read(): Promise<InputData> { return { equation: this.readEquation(), startCondition: this.readStartCondition(), differentiateInterval: this.readDifferentiateInterval(), step: this.readStep(), epsilon: this.readEpsilon(), }; } private readEquation(): OrdinaryDifferentialEquation { return builtinEquations[this.selectedEquationIndex]; } private readStartCondition(): Point { return { x: this._parseFloatWithComma(this.rawX0), y: this._parseFloatWithComma(this.rawY0), }; } private readDifferentiateInterval(): Interval { return { start: this._parseFloatWithComma(this.rawDifferentiateIntervalStart), end: this._parseFloatWithComma(this.rawDifferentiateIntervalEnd), }; } private readStep(): number { return this._parseFloatWithComma(this.rawStep); } private readEpsilon(): number { return this._parseFloatWithComma(this.rawEpsilon); } private _parseFloatWithComma(value: string): number { value = value.replace(",", "."); return parseFloat(value); } } /** * Класс для чтения входных данных из формы. */ class ReaderFromForm extends Reader { protected get selectedEquationIndex(): number { const inputTypeOptions = document.getElementsByName("equation"); for (let i = 0; i < inputTypeOptions.length; i++) { const optionElement = inputTypeOptions[i] as HTMLInputElement; if (optionElement.checked) { return i; } } throw new ReadError("Не выбрано уравнение"); } protected get rawX0(): string { const input = document.querySelector('[name="x0"]') as HTMLInputElement; return input.value; } protected get rawY0(): string { const input = document.querySelector('[name="y0"]') as HTMLInputElement; return input.value; } protected get rawDifferentiateIntervalStart(): string { const input = document.querySelector('[name="start"]') as HTMLInputElement; return input.value; } protected get rawDifferentiateIntervalEnd(): string { const input = document.querySelector('[name="end"]') as HTMLInputElement; return input.value; } protected get rawStep(): string { const input = document.querySelector('[name="h"]') as HTMLInputElement; return input.value; } protected get rawEpsilon(): string { const input = document.querySelector( '[name="epsilon"]' ) as HTMLInputElement; return input.value; } } class ReadError extends Error { constructor(message: string) { super(message); this.name = "ReadError"; } } /** * Получить экземпляр класса для чтения входных данных в зависимости от того, * что выбрал пользователь. */ export function getReader(): Reader { return new ReaderFromForm(); }
import React from 'react'; import {FlatList, SafeAreaView, StyleSheet, View} from 'react-native'; import colors from '../../../config/colors'; import {BackBtnHeader} from '../../components/headers/BackBtnHeader'; import {CompletedAssetItem} from './CompletedAssetItem'; import Strings from '../../../config/strings'; import {completeAssetObj} from '../../../models/api_response/CompleteAssetResModel'; import {completeInfoObj} from '../../../models/api_response/MyAssetsResModel'; import {ProgressBar} from '../../components/ProgressBar'; import {NoDataTxt} from '../../components/NoDataTxt'; import {AppText} from '../../components/AppText'; import {PriceTxt} from '../../components/PriceTxt'; import {ViewLine} from '../../components/ViewLine'; import {GILROY} from '../../../config'; type Props = { completeAssetListData : completeAssetObj[], completeAssetData : completeInfoObj, noDataVisible : boolean, progressVisible : boolean } export const CompletedAssetView = React.memo<Props>((props) => { const completeListHeadData = props.completeAssetData ; const completeListHeadString = Strings.completeAsset ; const numberFormat = (value : number) => { if(value !== null) { const re = '\\d(?=(\\d{' + 3 + '})+' + '\\D' + ')'; // @ts-ignore const num = value.toFixed(Math.max(0, ~~2)); const str = num.replace(new RegExp(re, 'g'), '$&' + ','); return str; } else { return "0.00" } } return( <SafeAreaView style={styles.completeAssetMainCont}> <BackBtnHeader backBtnVisible={true} title={Strings.completeAsset.completeAssetHeaderTxt}/> <View style={styles.completeAssetSubCont}> <View> <View style={styles.completeAssetCardMainCont}> <View> <AppText style={styles.completeAssetCardTitleTxt} text={completeListHeadString.completeAssetCardTitleTxt}/> </View> <View style={styles.completeAssetPriceCont}> <PriceTxt priceTxt={numberFormat(completeListHeadData?.amount === null ? 0 : completeListHeadData?.amount)} currencyVisible={true} priceStyle={styles.completeAssetPriceTxt} currencyStyle={styles.completeAssetCurrencyPriceTxt}/> </View> </View> <View style={styles.completeAssetPaymentMainCont}> <View style={styles.completeAssetPaymentSubCont}> <AppText style={styles.completeAssetPaymentTxt} text={completeListHeadString.completeAssetTotalPayment + " : " + completeListHeadData.total_payments}/> </View> </View> <ViewLine style={styles.completeAssetViewLine}/> <View style={styles.completeAssetTitleCont}> <View> <AppText style={styles.completeAssetTitleTxt} text={"My Assets"}/> </View> </View> </View> {props.completeAssetListData.length > 0 ?<FlatList data={props.completeAssetListData} showsVerticalScrollIndicator={false} showsHorizontalScrollIndicator={false} renderItem={({item, index}) => <CompletedAssetItem length={props.completeAssetListData.length} index={index} item={item}/>} keyExtractor={(item, index) => index.toString()}/> : null} {props.progressVisible ? <ProgressBar/> : null} {props.noDataVisible ? <NoDataTxt/> : null} </View> </SafeAreaView> ) }) const styles = StyleSheet.create({ completeAssetMainCont : { flex:1, backgroundColor:colors.backgroundColor }, completeAssetSubCont : { flex:1, backgroundColor:colors.backgroundColor, paddingStart:15, paddingEnd:15 }, completeAssetCardMainCont : { backgroundColor:colors.completeAsset, borderRadius:16, justifyContent:'center', alignItems:'center', paddingTop:25, paddingBottom:25, marginTop:20 }, completeAssetCardTitleTxt : { fontFamily:GILROY.medium, fontSize:16, color:colors.white }, completeAssetPriceCont : { marginTop:3, flexDirection:'row', }, completeAssetPriceTxt : { fontFamily:GILROY.semi_bold, fontSize:28, fontWeight:'600', color:colors.white }, completeAssetCurrencyPriceTxt : { fontFamily:GILROY.semi_bold, fontSize:14, fontWeight:'600', color:colors.white, marginBottom:5 }, completeAssetPaymentMainCont : { flexDirection:'row', marginTop:15 }, completeAssetPaymentSubCont : { flex:1, flexDirection:'row-reverse' }, completeAssetPaymentTxt : { fontFamily:GILROY.medium, fontSize:14, color:colors.lightTxt }, completeAssetViewLine : { marginTop:15, height:2 }, completeAssetTitleCont : { flexDirection:'row', marginTop:15, }, completeAssetTitleTxt : { fontFamily:GILROY.semi_bold, fontSize:18 } })
namespace ecommerce.sdk.douyin; [Description("发布商品和发布SPU前需要调用此接口查看类目是否为SPU类目,如果是,会返回对应的管控策略和SPU发布表单")] [DouyinRetCode(10000,"success","","","")] [DouyinRetCode(50002,"业务处理失败","读取失败","isv.business-failed:2012013","检查参数入参")] [DouyinRetCode(80000,"风控拦截","操作人非法","isv.risk-control-failed:20121002","查看操作人信息")] public class SpuGetSpuRuleReq : IDouyinReq<SpuGetSpuRuleRsp> { public string GetMethod() { return "spu.getSpuRule"; } public string GetUrl() { return "/spu/getSpuRule"; } [JsonPropertyName("category_id")] [Description("类目ID")] [NotNull] public long? CategoryId { get; set; } } [Description("发布商品和发布SPU前需要调用此接口查看类目是否为SPU类目,如果是,会返回对应的管控策略和SPU发布表单")] public class SpuGetSpuRuleRsp { [JsonPropertyName("spu_property_rule")] [Description("SPU属性规则")] public List<SpuPropertyRuleItem> SpuPropertyRule { get; set; } public class SpuPropertyRuleItem { [JsonPropertyName("property_name")] [Description("属性名")] public string PropertyName { get; set; } [JsonPropertyName("property_id")] [Description("属性ID")] public long PropertyId { get; set; } [JsonPropertyName("is_required")] [Description("是否必填,0:非必填,1:必填")] public long IsRequired { get; set; } [JsonPropertyName("value_type")] [Description("输入类型 select:单选,multi_select:多选,text:输入框,timestamp:时间戳,timeframe:时间区间")] public string ValueType { get; set; } [JsonPropertyName("property_type")] [Description("属性类型,0 绑定属性 1关键属性 2销售属性")] public long PropertyType { get; set; } [JsonPropertyName("diy_type")] [Description("是否支持枚举可输入")] public long DiyType { get; set; } [JsonPropertyName("max_select_num")] [Description("最大可选数量,多选时需要用")] public long MaxSelectNum { get; set; } [JsonPropertyName("values")] [Description("属性值")] public List<ValuesItem> Values { get; set; } public class ValuesItem { [JsonPropertyName("value_id")] [Description("属性值ID,对于输入框类型,填0即可")] public long ValueId { get; set; } [JsonPropertyName("value_name")] [Description("属性值,属性值的中文")] public string ValueName { get; set; } } } [JsonPropertyName("spu_images_rule")] [Description("SPU图片规则")] public SpuImagesRuleItem SpuImagesRule { get; set; } public class SpuImagesRuleItem { [JsonPropertyName("is_required")] [Description("是否必填")] public long IsRequired { get; set; } [JsonPropertyName("max_num")] [Description("最大数量")] public long MaxNum { get; set; } [JsonPropertyName("min_num")] [Description("最小数量")] public long MinNum { get; set; } } [JsonPropertyName("spu_actual_images_rule")] [Description("SPU实物图规则(实物图:证明SPU存在的图片,如版权页、包装图)")] public SpuActualImagesRuleItem SpuActualImagesRule { get; set; } public class SpuActualImagesRuleItem { [JsonPropertyName("is_required")] [Description("是否必填")] public long IsRequired { get; set; } [JsonPropertyName("max_num")] [Description("最大数量")] public long MaxNum { get; set; } [JsonPropertyName("min_num")] [Description("最小数量")] public long MinNum { get; set; } } [JsonPropertyName("control_type")] [Description("0-不管控,商家在该类目下发布商品时,不强制要求命中SPU。 - 1-弱管控,商家在该类目下发布商品时,强制要求命中SPU(即关键属性必须一致),但绑定属性不强制要求一致。 - 2-强管控,商家在该类目下发布商品时,强制要求命中SPU,且绑定属性必须一致。")] public long ControlType { get; set; } [JsonPropertyName("support_spu_product")] [Description("- true 表示商家在该类目基于SPU发布商品,发商品的管控策略见管控类型。 - false 表示商家在该类目不需要基于SPU发布商品。不用发布SPU,直接发布商品即可。")] public bool SupportSpuProduct { get; set; } [JsonPropertyName("support_create_spu")] [Description("true-可以发布SPU,false-不能发布SPU")] public bool SupportCreateSpu { get; set; } [JsonPropertyName("spu_material_rules")] [Description("SPU素材规则(素材类型:主图)")] public List<SpuMaterialRulesItem> SpuMaterialRules { get; set; } public class SpuMaterialRulesItem { [JsonPropertyName("material_rule")] [Description("SPU素材的具体规则")] public MaterialRuleItem MaterialRule { get; set; } public class MaterialRuleItem { [JsonPropertyName("name")] [Description("素材名称")] public string Name { get; set; } [JsonPropertyName("is_required")] [Description("是否必填,0:非必填,1:必填")] public long IsRequired { get; set; } [JsonPropertyName("min_num")] [Description("最小数量")] public long MinNum { get; set; } [JsonPropertyName("max_num")] [Description("最大数量")] public long MaxNum { get; set; } [JsonPropertyName("max_size")] [Description("最大容量,单位为M")] public long MaxSize { get; set; } [JsonPropertyName("aspect_ratio")] [Description("素材类型为图片时的尺寸比")] public List<string> AspectRatio { get; set; } [JsonPropertyName("pixel")] [Description("素材类型为图片时的像素比")] public List<long> Pixel { get; set; } [JsonPropertyName("data_format")] [Description("数据格式类型,例如jpg、png等格式")] public List<string> DataFormat { get; set; } } [JsonPropertyName("material_type")] [Description("素材类型枚举值:1-主图")] public int MaterialType { get; set; } } [JsonPropertyName("spu_proof_rules")] [Description("证明材料规则(证明材料类型:实物图、版权页)")] public List<SpuProofRulesItem> SpuProofRules { get; set; } public class SpuProofRulesItem { [JsonPropertyName("proof_type")] [Description("实物证明类型,枚举值:2-实物图、6-版权页")] public int ProofType { get; set; } [JsonPropertyName("proof_rule")] [Description("SPU证明材料的具体规则")] public ProofRuleItem ProofRule { get; set; } public class ProofRuleItem { [JsonPropertyName("name")] [Description("证明材料名称")] public string Name { get; set; } [JsonPropertyName("is_required")] [Description("是否必填,0:非必填,1:必填")] public long IsRequired { get; set; } [JsonPropertyName("min_num")] [Description("最小数量")] public long MinNum { get; set; } [JsonPropertyName("max_num")] [Description("最大数量")] public long MaxNum { get; set; } [JsonPropertyName("max_size")] [Description("最大容量,单位为M")] public long MaxSize { get; set; } [JsonPropertyName("aspect_ratio")] [Description("素材类型为图片时的尺寸比")] public List<string> AspectRatio { get; set; } [JsonPropertyName("pixel")] [Description("素材类型为图片时的像素比")] public List<long> Pixel { get; set; } [JsonPropertyName("data_format")] [Description("数据格式类型")] public List<string> DataFormat { get; set; } } } }
import 'package:flutter/material.dart'; import '../../constants/colors.dart'; import '../screens/customer-folder/customer_model.dart'; import 'bottom-app-bar-widget/bottom_app_bar_traight.dart'; class CustomerContactWidget extends StatefulWidget { CustomerModel contactList; CustomerContactWidget({ Key? key, required this.contactList, }) : super(key: key); @override State<CustomerContactWidget> createState() => _CustomerContactWidgetState(); } class _CustomerContactWidgetState extends State<CustomerContactWidget> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xffF2F2F2), body: ListView.builder( shrinkWrap: true, itemCount: widget.contactList.contact.length, itemBuilder: (context, index) { String _emailController = widget.contactList.contact[index].email ?? ""; String _phoneController = widget.contactList.contact[index].tel?? ""; String _departmanController = widget.contactList.contact[index].department ?? ""; String _birthdayController = widget.contactList.contact[index].birthDay ?? ""; String _adresController = widget.contactList.contact[index].address ?? ""; String _contactController = widget.contactList.contact[index].contactName ?? ""; return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Card( elevation: 8.0, margin: EdgeInsets.only(left: 20, right: 20, top: 20, bottom: 20), child: Column( children: [ Container( height: 50, color: blueColor, alignment: Alignment.center, padding: const EdgeInsets.symmetric(horizontal: 10.0), child: new Text( "${_contactController}", style: new TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), ), SizedBox( height: 30, ), Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(left: 10), child: Text( "E-mail", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ), ), Container( padding: const EdgeInsets.only( left: 10.0, right: 10, ), child: TextFormField( initialValue: _emailController, decoration: InputDecoration( helperStyle: TextStyle( color: Colors.grey, fontSize: 17), ), ), ), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(left: 10), child: Text( "Telefon", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ), ), Container( padding: const EdgeInsets.only( left: 10.0, right: 10, ), child: TextFormField( initialValue: _phoneController, decoration: InputDecoration( helperStyle: TextStyle( color: Colors.grey, fontSize: 17), ), ), ), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(left: 10), child: Text( "Departman", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ), ), Container( padding: const EdgeInsets.only( left: 10.0, right: 10, ), child: TextFormField( initialValue: _departmanController, decoration: InputDecoration( helperStyle: TextStyle( color: Colors.grey, fontSize: 17), ), ), ), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(left: 10), child: Text( "Doğum Tarihi", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ), ), Container( padding: const EdgeInsets.only( left: 10.0, right: 10, ), child: TextFormField( initialValue: _birthdayController, decoration: InputDecoration( helperStyle: TextStyle( color: Colors.grey, fontSize: 17), ), ), ), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(left: 10), child: Text( "Adres", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ), ), Container( padding: const EdgeInsets.only( left: 10.0, right: 10, ), child: TextFormField( minLines: 4, maxLines: null, initialValue: _adresController, decoration: InputDecoration( helperStyle: TextStyle( color: Colors.grey, fontSize: 17), ), ), ), ], ), ), SizedBox( height: 20, ), Text("") ], ), ) ], ); }), bottomNavigationBar: BottomAppBarStraightWidget(), ); } }
package com.jones.goldenmonitor.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class Swagger2 implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/swagger-ui.html**") .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.any()) // .paths(PathSelectors.regex("*/controller/*")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("API information").build(); } }
// // MenubarPresenter.swift // Timer // // Created by Anton Cherkasov on 23.02.2024. // import Foundation protocol MenubarPresenterProtocol { func menuWillOpen() func menuItemHasBeenClicked(_ id: MenuIdentifier) func timerDidChange(state: TimerState) func presentStatistics(_ interval: TimeInterval) } final class MenubarPresenter { var interactor: MenubarInteractorProtocol? var menubar: MenubarViewProtocol? var itemsFactory: ItemsFactoryProtocol weak var output: MenubarOutput? lazy var formatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional formatter.zeroFormattingBehavior = .pad formatter.allowedUnits = [.second, .minute, .hour] return formatter }() // MARK: - Initialization init( itemsFactory: ItemsFactoryProtocol, output: MenubarOutput ) { self.itemsFactory = itemsFactory self.output = output } } // MARK: - MenubarPresenterProtocol extension MenubarPresenter: MenubarPresenterProtocol { func presentStatistics(_ interval: TimeInterval) { menubar?.configure(.today, withItem: itemsFactory.makeTotalToday(interval: interval)) } func menuWillOpen() { interactor?.fetchData() } func menuItemHasBeenClicked(_ id: MenuIdentifier) { switch id { case .stop: interactor?.stop() case .pauseResume: interactor?.pauseResume() case .period(let value): interactor?.start(with: value) case .quit: interactor?.quit() case .today: assertionFailure("Not supported") case .settings: output?.showSettings() } } func timerDidChange(state: TimerState) { var title: String? switch state { case .active(let start, let remainingTime): let end = start.addingTimeInterval(remainingTime) title = formatter.string(from: start, to: end) menubar?.configure(.stop, withItem: itemsFactory.makeStopItem(isEnabled: true)) menubar?.configure(.pauseResume, withItem: itemsFactory.makePause(isEnabled: true)) case .paused(let start, let remainingTime): let end = start.addingTimeInterval(remainingTime) title = formatter.string(from: start, to: end) menubar?.configure(.stop, withItem: itemsFactory.makeStopItem(isEnabled: true)) menubar?.configure(.pauseResume, withItem: itemsFactory.makeResume(isEnabled: true)) case .inactive: menubar?.configure(.stop, withItem: itemsFactory.makeStopItem(isEnabled: false)) menubar?.configure(.pauseResume, withItem: itemsFactory.makePause(isEnabled: false)) } menubar?.configureButton(title: title ?? "", iconName: "bolt.fill") } }
import datetime import flask import flask_json from typing import List import request_context import request_utils import scope.database.date_utils as date_utils import scope.database.patient.activities import scope.database.patient.safety_plan import scope.database.patient.scheduled_assessments import scope.database.patient.values_inventory patient_summary_blueprint = flask.Blueprint( "patient_summary_blueprint", __name__, ) def compute_patient_summary( activity_documents: List[dict], safety_plan_document: dict, scheduled_assessment_documents: List[dict], values_inventory_document: dict, ) -> dict: """ { # assignedValuesInventory <- True, if assigned is True, and editedDateTime of an activity with value < assignedDateTime assignedValuesInventory: boolean; # assignedSafetyPlan <- True, if assigned is True, and lastUpdatedDateTime < assignedDateTime in safety plan singleton assignedSafetyPlan: boolean; # scheduledAssessments that are not completed and dueDate <= today. assignedScheduledAssessments: IScheduledAssessment[]; } """ # assignedValuesInventory assigned_values_inventory: bool = values_inventory_document["assigned"] if assigned_values_inventory: assigned_values_inventory_datetime = date_utils.parse_datetime( values_inventory_document["assignedDateTime"] ) for activity_current in activity_documents: # If an activity with value was created after the assignment, the assignment is resolved if ( "valueId" in activity_current and date_utils.parse_datetime(activity_current["editedDateTime"]) > assigned_values_inventory_datetime ): assigned_values_inventory = False break # assignedSafetyPlan assigned_safety_plan: bool = safety_plan_document["assigned"] if assigned_safety_plan: if "lastUpdatedDateTime" in safety_plan_document: assigned_safety_plan = date_utils.parse_datetime( safety_plan_document["lastUpdatedDateTime"] ) < date_utils.parse_datetime(safety_plan_document["assignedDateTime"]) # assignedScheduledAssessments assigned_scheduled_assessments = list( filter( lambda scheduled_assessment_current: ( (not scheduled_assessment_current["completed"]) and ( date_utils.parse_date(scheduled_assessment_current["dueDate"]) <= datetime.date.today() ) ), scheduled_assessment_documents, ) ) return { "assignedValuesInventory": assigned_values_inventory, "assignedSafetyPlan": assigned_safety_plan, "assignedScheduledAssessments": assigned_scheduled_assessments, } @patient_summary_blueprint.route( "/<string:patient_id>/summary", methods=["GET"], ) @flask_json.as_json def get_patient_summary(patient_id): """ Obtain patient summary to be used by patient app. """ context = request_context.authorized_for_patient(patient_id=patient_id) patient_collection = context.patient_collection(patient_id=patient_id) activity_documents = scope.database.patient.activities.get_activities( collection=patient_collection, ) activity_documents = activity_documents or [] safety_plan_document = scope.database.patient.safety_plan.get_safety_plan( collection=patient_collection, ) scheduled_assessment_documents = ( scope.database.patient.scheduled_assessments.get_scheduled_assessments( collection=patient_collection, ) ) scheduled_assessment_documents = scheduled_assessment_documents or [] values_inventory_document = ( scope.database.patient.values_inventory.get_values_inventory( collection=patient_collection, ) ) if not all( [ safety_plan_document, values_inventory_document, ] ): request_utils.abort_document_not_found() return compute_patient_summary( activity_documents=activity_documents, safety_plan_document=safety_plan_document, scheduled_assessment_documents=scheduled_assessment_documents, values_inventory_document=values_inventory_document, )
// // UIButton+Extension.m // Weibo11 // // Created by JYJ on 15/12/5. // Copyright © 2015年 itheima. All rights reserved. // #import "UIButton+Extension.h" @implementation UIButton (Extension) #pragma mark --- 创建默认按钮--有字体、颜色--有图片---有背景 + (instancetype)buttonWithTitle:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font imageName:(NSString *)imageName target:(id)target action:(SEL)action backImageName:(NSString *)backImageName { UIButton *button = [[UIButton alloc] init]; // 设置标题 [button setTitle:title forState:UIControlStateNormal]; [button setTitleColor:titleColor forState:UIControlStateNormal]; button.titleLabel.font = font; button.adjustsImageWhenHighlighted = NO; // 图片 if (imageName != nil) { [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal]; NSString *highlighted = [NSString stringWithFormat:@"%@_highlighted", imageName]; [button setImage:[UIImage imageNamed:highlighted] forState:UIControlStateHighlighted]; } // 背景图片 if (backImageName != nil) { [button setBackgroundImage:[UIImage imageNamed:backImageName] forState:UIControlStateNormal]; NSString *backHighlighted = [NSString stringWithFormat:@"%@_highlighted", backImageName]; [button setBackgroundImage:[UIImage imageNamed:backHighlighted] forState:UIControlStateHighlighted]; } // 监听方法 if (action != nil) { [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside]; } return button; } #pragma mark --- 有文字,有颜色,有字体,有图片,没有背景图片 + (instancetype)buttonWithTitle:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font imageName:(NSString *)imageName target:(id)target action:(SEL)action { return [self buttonWithTitle:title titleColor:titleColor font:font imageName:imageName target:target action:action backImageName:nil]; } #pragma mark --- 有文字,有颜色,有字体,没有图片,没有背景 + (instancetype)buttonWithTitle:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font target:(id)target action:(SEL)action { return [self buttonWithTitle:title titleColor:titleColor font:font imageName:nil target:target action:action backImageName:nil]; } #pragma mark --- 有文字,有颜色,有字体,没图片,有背景 + (instancetype)buttonWithTitle:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font target:(id)target action:(SEL)action backImageName:(NSString *)backImageName { return [self buttonWithTitle:title titleColor:titleColor font:font imageName:nil target:target action:action backImageName:backImageName]; } - (void)layoutButtonWithEdgeInsetsStyle:(MKButtonEdgeInsetsStyle)style imageTitleSpace:(CGFloat)space { // self.backgroundColor = [UIColor cyanColor]; /** * 前置知识点:titleEdgeInsets是title相对于其上下左右的inset,跟tableView的contentInset是类似的, * 如果只有title,那它上下左右都是相对于button的,image也是一样; * 如果同时有image和label,那这时候image的上左下是相对于button,右边是相对于label的;title的上右下是相对于button,左边是相对于image的。 */ // 1. 得到imageView和titleLabel的宽、高 CGFloat imageWith = self.imageView.frame.size.width; CGFloat imageHeight = self.imageView.frame.size.height; CGFloat labelWidth = 0.0; CGFloat labelHeight = 0.0; if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) { // 由于iOS8中titleLabel的size为0,用下面的这种设置 labelWidth = self.titleLabel.intrinsicContentSize.width; labelHeight = self.titleLabel.intrinsicContentSize.height; } else { labelWidth = self.titleLabel.frame.size.width; labelHeight = self.titleLabel.frame.size.height; } // 2. 声明全局的imageEdgeInsets和labelEdgeInsets UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero; UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero; // 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值 switch (style) { case MKButtonEdgeInsetsStyleTop: { imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth); labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0); } break; case MKButtonEdgeInsetsStyleLeft: { imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0); labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0); } break; case MKButtonEdgeInsetsStyleBottom: { imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth); labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0); } break; case MKButtonEdgeInsetsStyleRight: { imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0); labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space/2.0, 0, imageWith+space/2.0); } break; default: break; } // 4. 赋值 self.titleEdgeInsets = labelEdgeInsets; self.imageEdgeInsets = imageEdgeInsets; } @end
// Funções geradoras function* geradora1() { // Código qualquer ... yield "valor 1"; // Código qualquer ... yield "valor 2"; // Código qualquer ... yield "valor 3"; } const g1 = geradora1(); // Iteração usando for ... of em uma função geradora for (let valor of g1) { console.log(valor); } // Função geradora que gera valores infinitos function* geradora2() { let i = 0; while (true) { yield i; i++; } } const g2 = geradora2(); console.log(g2.next().value); console.log(g2.next().value); console.log(g2.next().value); console.log(g2.next().value); console.log(g2.next().value); console.log(g2.next().value); console.log(g2.next().value); console.log(g2.next().value);
// Validate form responsible for adding new expense $("#formExpense").validate({ rules: { amount: { required: true, amountMin: true, max: 99999999.99, decimalPlaces: true }, dateOfExpense: { dateTime: true, min: "2000-01-01", dateNotGreaterThanToday: true }, expenseCategoryAssignedToUserId: { required: true }, paymentMethodAssignedToUserId: { required: true } }, messages: { amount: { max: "Please enter a value lower than 100000000." }, dateOfExpense: { min: "Please enter a date equal or greather than 01-01-2000." } }, errorPlacement: function (error, element) { if (element.attr("name") == "amount") error.insertAfter("#divExpenseAmount") else if (element.attr("name") == "dateOfExpense") error.insertAfter("#divExpenseDate") else if (element.attr("name") == "paymentMethodAssignedToUserId") error.insertAfter("#divPaymentMethod") else if (element.attr("name") == "expenseCategoryAssignedToUserId") error.insertAfter("#divExpenseSource") } }); // Show category limits, spent money and calculate left money using AJAX const amountField = document.querySelector("#expenseAmount"); const dateField = document.querySelector("#expenseDate"); const categoryField = document.querySelector("#expenseSource"); const limitInfoField = document.querySelector("#limitInfo"); const moneySpentField = document.querySelector("#moneySpent"); const moneyLeftField = document.querySelector("#moneyLeft"); [categoryField, dateField].forEach(function(element) { element.addEventListener("change", async function() { await showCategoryLimit(); await showMoneySpent(); showCashLeft(); }); }); window.addEventListener("load", () => { showCategoryLimit(); showMoneySpent(); }); amountField.addEventListener("input", () => { showCashLeft(); }); // Show category limit in proper field const showCategoryLimit = async () => { let category = categoryField.options[categoryField.selectedIndex].text.trim(); if (category === "Choose option") { limitInfoField.textContent = "Category required"; } else { let categoryDashed = category.replace(/\s+/g, "-"); let limitAmount = await getCategoryLimit(categoryDashed); if (limitAmount === null) { limitInfoField.textContent = "No limit set"; } else { limitInfoField.textContent = `${limitAmount} PLN`; } } } // Get chosen category monthly limit const getCategoryLimit = async (category) => { try { const res = await fetch(`../api/limit/${category}`); return await res.json();; } catch (e) { console.log('ERROR', e); } } // Show spent money in proper field const showMoneySpent = async () => { let category = categoryField.options[categoryField.selectedIndex].text.trim(); let date = dateField.value; if ((category === "Choose option") || (date === '')) { moneySpentField.textContent = "Category & date required"; } else { let categoryDashed = category.replace(/\s+/g, "-"); let moneySpentAmount = await getMoneySpent(categoryDashed, date); moneySpentField.textContent = `${moneySpentAmount} PLN`; } } // Get spent money in month in chosen category const getMoneySpent = async (category, date) => { try { const res = await fetch(`../api/amount/${category}/${date}`); return await res.json();; } catch (e) { console.log('ERROR', e); } } // Show cash left in proper field const showCashLeft = () => { if (moneyLeftField.classList.contains("moneyLeftPlus")) { moneyLeftField.classList.remove("moneyLeftPlus") } if (moneyLeftField.classList.contains("moneyLeftMinus")) { moneyLeftField.classList.remove("moneyLeftMinus") } let category = categoryField.options[categoryField.selectedIndex].text.trim(); let date = dateField.value; let amount = amountField.value; if ((category === "Choose option") || (date === '') || (amount === '')) { moneyLeft.textContent = "Category, date & amount required"; } else { let limitInfo = limitInfoField.textContent; let moneySpent = moneySpentField.textContent; limitInfo = limitInfo.replace(/[^0-9\.]/g, ''); moneySpent = moneySpent.replace(/[^0-9\.]/g, ''); if ((limitInfo === '')) { moneyLeftField.textContent = "No limit"; } else { limitInfo = Number(limitInfo); moneySpent = Number(moneySpent); amount = amountField.value; cashLeft = limitInfo - moneySpent - amount; if (cashLeft >=0) { moneyLeftField.classList.add("moneyLeftPlus"); } else { moneyLeftField.classList.add("moneyLeftMinus"); } moneyLeftField.textContent = `${cashLeft.toFixed(2)} PLN`; } } }
import React, { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import { getMovieDetails } from "../../api"; import Layout from "../../components/Layout"; import EmptyDataMessage from "../../components/EmptyDataMessage"; import Details from "../../components/Details"; import Tabs from "../../components/Tabs"; import Recommended from "../../components/Recommended"; import Loading from "../../UI/Loading"; const SingleMovie = () => { const { id } = useParams(); const [details, setDetails] = useState({}); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(""); useEffect(() => { getMovieDetails(id) .then((res) => { setDetails(res); }) .catch((error) => { console.log(error); setError(error.response.data.status_message); }) .finally(() => { setIsLoading(false); }); }, [id]); return ( <Layout title={details.title}> <Loading loading={isLoading} isFullHeight> <EmptyDataMessage isEmpty={Object.keys(details).length === 0} isFullHeight > <Details {...details} /> <Tabs id={id} /> <Recommended id={id} /> </EmptyDataMessage> </Loading> </Layout> ); }; export default SingleMovie;
import os import os.path import torch import numpy as np import pandas import csv import random from collections import OrderedDict from .base_video_dataset import BaseVideoDataset from lib.train.data import jpeg4py_loader from lib.train.admin import env_settings import cv2 from lib.train.dataset.depth_utils import get_target_depth, get_layered_image_by_depth class RGBD(BaseVideoDataset): """ LaSOT dataset. Publication: LaSOT: A High-quality Benchmark for Large-scale Single Object Tracking Heng Fan, Liting Lin, Fan Yang, Peng Chu, Ge Deng, Sijia Yu, Hexin Bai, Yong Xu, Chunyuan Liao and Haibin Ling CVPR, 2019 https://arxiv.org/pdf/1809.07845.pdf Download the dataset from https://cis.temple.edu/lasot/download.html !!!!! Song : estimated the depth images from LaSOT dataset, there are 646 sequences with corresponding depth !!!!! """ def __init__(self, root=None, dtype='rgbcolormap', image_loader=jpeg4py_loader, vid_ids=None): # split=None, data_fraction=None): """ args: image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the videos with subscripts -1, -3, and -5 from each class will be used for training. # split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of # vid_ids or split option can be used at a time. # data_fraction - Fraction of dataset to be used. The complete dataset is used by default root - path to the lasot depth dataset. dtype - colormap or depth,, colormap + depth if colormap, it returns the colormap by cv2, if depth, it returns [depth, depth, depth] """ root = env_settings().rgbd_dir if root is None else root super().__init__('RGBD', root, image_loader) self.root = root self.dtype = dtype self.sequence_list = self._build_sequence_list() self.seq_per_class, self.class_list = self._build_class_list() self.class_list.sort() self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)} def _build_sequence_list(self): ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') file_path = os.path.join(ltr_path, 'data_specs', 'rgbd_dataset.txt') sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist() # sequence_list = os.listdir(self.root) return sequence_list def _build_class_list(self): seq_per_class = {} class_list = [] for seq_id, seq_name in enumerate(self.sequence_list): class_name = seq_name.split('/')[0] if class_name not in class_list: class_list.append(class_name) if class_name in seq_per_class: seq_per_class[class_name].append(seq_id) else: seq_per_class[class_name] = [seq_id] return seq_per_class, class_list def get_name(self): return 'rgbd' def has_class_info(self): return True def has_occlusion_info(self): return True def get_num_sequences(self): return len(self.sequence_list) def get_num_classes(self): return len(self.class_list) def get_sequences_in_class(self, class_name): return self.seq_per_class[class_name] def _read_bb_anno(self, seq_path): bb_anno_file = os.path.join(seq_path, "groundtruth_rect.txt") gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False, low_memory=False).values return torch.tensor(gt) # def _read_target_visible(self, seq_path): # # Read full occlusion and out_of_view # # occlusion_file = os.path.join(seq_path, "full_occlusion.txt") # out_of_view_file = os.path.join(seq_path, "out_of_view.txt") # # with open(occlusion_file, 'r', newline='') as f: # occlusion = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]]) # with open(out_of_view_file, 'r') as f: # out_of_view = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]]) # # target_visible = ~occlusion & ~out_of_view # # return target_visible def _get_sequence_path(self, seq_id): ''' Return : - Depth path ''' seq_name = self.sequence_list[seq_id] # class_name = seq_name.split('-')[0] # vid_id = seq_name.split('-')[1] return os.path.join(self.root, seq_name) def get_sequence_info(self, seq_id): depth_path = self._get_sequence_path(seq_id) bbox = self._read_bb_anno(depth_path) ''' if the box is too small, it will be ignored ''' # valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0) valid = (bbox[:, 2] > 10.0) & (bbox[:, 3] > 10.0) # visible = self._read_target_visible(depth_path) & valid.byte() visible = valid return {'bbox': bbox, 'valid': valid, 'visible': visible} def _get_frame_path(self, seq_path, frame_id): ''' return depth image path ''' return os.path.join(seq_path, 'color', '{:08}.jpg'.format(frame_id + 1)), os.path.join(seq_path, 'depth', '{:08}.png'.format( frame_id + 1)) # frames start from 1 def _get_frame(self, seq_path, frame_id, bbox=None): ''' Return : - rgb - colormap from depth image - [depth, depth, depth] ''' color_path, depth_path = self._get_frame_path(seq_path, frame_id) rgb = cv2.imread(color_path) rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB) dp = cv2.imread(depth_path, -1) # max_depth = min(np.max(dp), 10000) # dp[dp > max_depth] = max_depth if self.dtype == 'color': # img = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB) img = rgb elif self.dtype == 'rgbcolormap': colormap = cv2.normalize(dp, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) colormap = np.asarray(colormap, dtype=np.uint8) colormap = cv2.applyColorMap(colormap, cv2.COLORMAP_JET) # colormap = cv2.applyColorMap(cv2.convertScaleAbs(dp, alpha=0.03), cv2.COLORMAP_JET) img = cv2.merge((rgb, colormap)) elif self.dtype == 'centered_colormap': if bbox is None: print('Error !!! require bbox for centered_colormap') return target_depth = get_target_depth(dp, bbox) img = get_layered_image_by_depth(dp, target_depth, dtype=self.dtype) elif self.dtype == 'colormap': dp = cv2.normalize(dp, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) dp = np.asarray(dp, dtype=np.uint8) img = cv2.applyColorMap(dp, cv2.COLORMAP_JET) elif self.dtype == 'colormap_normalizeddepth': ''' Colormap + depth ''' dp = cv2.normalize(dp, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) dp = np.asarray(dp, dtype=np.uint8) colormap = cv2.applyColorMap(dp, cv2.COLORMAP_JET) r, g, b = cv2.split(colormap) img = cv2.merge((r, g, b, dp)) elif self.dtype == 'raw_depth': # No normalization here !!!! image = cv2.merge((dp, dp, dp)) elif self.dtype == 'normalized_depth': dp = cv2.normalize(dp, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) dp = np.asarray(dp, dtype=np.uint8) img = cv2.merge((dp, dp, dp)) # H * W * 3 elif self.dtype == 'rgbd': r, g, b = cv2.split(rgb) dp = cv2.normalize(dp, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) dp = np.asarray(dp, dtype=np.uint8) img = cv2.merge((r, g, b, dp)) elif self.dtype == 'rgb3d': dp = cv2.normalize(dp, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) dp = np.asarray(dp, dtype=np.uint8) dp = cv2.merge((dp, dp, dp)) img = cv2.merge((rgb, dp)) else: print('no such dtype ... : %s' % self.dtype) img = None return img def _get_class(self, seq_path): raw_class = seq_path.split('/')[-2] return raw_class def get_class_name(self, seq_id): depth_path = self._get_sequence_path(seq_id) obj_class = self._get_class(depth_path) return obj_class def get_frames(self, seq_id, frame_ids, anno=None): depth_path = self._get_sequence_path(seq_id) obj_class = self._get_class(depth_path) if anno is None: anno = self.get_sequence_info(seq_id) anno_frames = {} for key, value in anno.items(): anno_frames[key] = [value[f_id, ...].clone() for ii, f_id in enumerate(frame_ids)] frame_list = [self._get_frame(depth_path, f_id, bbox=anno_frames['bbox'][ii]) for ii, f_id in enumerate(frame_ids)] object_meta = OrderedDict({'object_class_name': obj_class, 'motion_class': None, 'major_class': None, 'root_class': None, 'motion_adverb': None}) return frame_list, anno_frames, object_meta
data_manipulation with ‘dyplr’ 2022-09-22 ``` r select(litters_data, group, litter_number, gd0_weight, pups_born_alive) ## # A tibble: 49 × 4 ## group litter_number gd0_weight pups_born_alive ## <chr> <chr> <dbl> <dbl> ## 1 Con7 #85 19.7 3 ## 2 Con7 #1/2/95/2 27 8 ## 3 Con7 #5/5/3/83/3-3 26 6 ## # … with 46 more rows ``` ``` r select(litters_data, group:gd_of_birth) ## # A tibble: 49 × 5 ## group litter_number gd0_weight gd18_weight gd_of_birth ## <chr> <chr> <dbl> <dbl> <dbl> ## 1 Con7 #85 19.7 34.7 20 ## 2 Con7 #1/2/95/2 27 42 19 ## 3 Con7 #5/5/3/83/3-3 26 41.4 19 ## # … with 46 more rows ``` ``` r select(litters_data, -pups_survive) ## # A tibble: 49 × 7 ## group litter_number gd0_weight gd18_weight gd_of_birth pups_born_alive pups_…¹ ## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 Con7 #85 19.7 34.7 20 3 4 ## 2 Con7 #1/2/95/2 27 42 19 8 0 ## 3 Con7 #5/5/3/83/3-3 26 41.4 19 6 0 ## # … with 46 more rows, and abbreviated variable name ¹​pups_dead_birth ``` ``` r select(litters_data, GROUP = group, LiTtEr_NuMbEr = litter_number) ## # A tibble: 49 × 2 ## GROUP LiTtEr_NuMbEr ## <chr> <chr> ## 1 Con7 #85 ## 2 Con7 #1/2/95/2 ## 3 Con7 #5/5/3/83/3-3 ## # … with 46 more rows ``` ``` r rename(litters_data, GROUP = group, LiTtEr_NuMbEr = litter_number) ## # A tibble: 49 × 8 ## GROUP LiTtEr_NuMbEr gd0_weight gd18_weight gd_of_birth pups_…¹ pups_…² pups_…³ ## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 Con7 #85 19.7 34.7 20 3 4 3 ## 2 Con7 #1/2/95/2 27 42 19 8 0 7 ## 3 Con7 #5/5/3/83/3-3 26 41.4 19 6 0 5 ## # … with 46 more rows, and abbreviated variable names ¹​pups_born_alive, ## # ²​pups_dead_birth, ³​pups_survive ``` ``` r select(litters_data, starts_with("gd")) ## # A tibble: 49 × 3 ## gd0_weight gd18_weight gd_of_birth ## <dbl> <dbl> <dbl> ## 1 19.7 34.7 20 ## 2 27 42 19 ## 3 26 41.4 19 ## # … with 46 more rows select(litters_data, ends_with("weight")) ## # A tibble: 49 × 2 ## gd0_weight gd18_weight ## <dbl> <dbl> ## 1 19.7 34.7 ## 2 27 42 ## 3 26 41.4 ## # … with 46 more rows ``` ``` r select(litters_data, litter_number, pups_survive, everything()) ## # A tibble: 49 × 8 ## litter_number pups_survive group gd0_weight gd18_wei…¹ gd_of…² pups_…³ pups_…⁴ ## <chr> <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 #85 3 Con7 19.7 34.7 20 3 4 ## 2 #1/2/95/2 7 Con7 27 42 19 8 0 ## 3 #5/5/3/83/3-3 5 Con7 26 41.4 19 6 0 ## # … with 46 more rows, and abbreviated variable names ¹​gd18_weight, ## # ²​gd_of_birth, ³​pups_born_alive, ⁴​pups_dead_birth ``` ``` r filter(litters_data, gd_of_birth == 20) ## # A tibble: 32 × 8 ## group litter_number gd0_weight gd18_weight gd_of_birth pups_…¹ pups_…² pups_…³ ## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 Con7 #85 19.7 34.7 20 3 4 3 ## 2 Con7 #4/2/95/3-3 NA NA 20 6 0 6 ## 3 Con7 #2/2/95/3-2 NA NA 20 6 0 4 ## # … with 29 more rows, and abbreviated variable names ¹​pups_born_alive, ## # ²​pups_dead_birth, ³​pups_survive ``` ``` r #litter_data2 mutate(litters_data, wt_gain = gd18_weight - gd0_weight, group = str_to_lower(group), # wt_gain_kg = wt_gain * 2.2 ) ## # A tibble: 49 × 9 ## group litter_number gd0_weight gd18_…¹ gd_of…² pups_…³ pups_…⁴ pups_…⁵ wt_gain ## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 con7 #85 19.7 34.7 20 3 4 3 15 ## 2 con7 #1/2/95/2 27 42 19 8 0 7 15 ## 3 con7 #5/5/3/83/3-3 26 41.4 19 6 0 5 15.4 ## # … with 46 more rows, and abbreviated variable names ¹​gd18_weight, ## # ²​gd_of_birth, ³​pups_born_alive, ⁴​pups_dead_birth, ⁵​pups_survive ``` ``` r litters_data = read_csv("./data/FAS_litters.csv", col_types = "ccddiiii") %>% janitor::clean_names() %>% select(-pups_survive) %>% mutate( wt_gain = gd18_weight - gd0_weight, group = str_to_lower(group)) %>% drop_na(wt_gain) litters_data ## # A tibble: 31 × 8 ## group litter_number gd0_weight gd18_weight gd_of_birth pups_…¹ pups_…² wt_gain ## <chr> <chr> <dbl> <dbl> <int> <int> <int> <dbl> ## 1 con7 #85 19.7 34.7 20 3 4 15 ## 2 con7 #1/2/95/2 27 42 19 8 0 15 ## 3 con7 #5/5/3/83/3-3 26 41.4 19 6 0 15.4 ## # … with 28 more rows, and abbreviated variable names ¹​pups_born_alive, ## # ²​pups_dead_birth ``` ``` r litters_data %>% lm(wt_gain ~ pups_born_alive, data = .) ## ## Call: ## lm(formula = wt_gain ~ pups_born_alive, data = .) ## ## Coefficients: ## (Intercept) pups_born_alive ## 13.0833 0.6051 ```
import Paper from '@mui/material/Paper'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableHead from '@mui/material/TableHead'; import TablePagination from '@mui/material/TablePagination'; import TableRow from '@mui/material/TableRow'; import axios from 'axios'; import Button from '@mui/material/Button'; import style from "../../css/postulacion.module.css" import {useState, useEffect} from 'react' import { useStore } from "../../../../controllers/Auth.js" import setScrollTop from '../../../../controllers/setPostScroll.js'; export default function VerPostulacionesColab() { const [datosAceptadas , setDatosAceptadas ]=useState({ indice: [], data: [] }); const token = useStore((state) => state.token); const id_user = useStore((state) => state.id_user); const getPostulaciones = () => { axios.get('https://proyecto-281-production.up.railway.app/api/delivery/getPostulacionColaborador', { headers: { "x-token": token, "id_user": id_user } } ).then((response) => { console.log(response.data.body.postulaciones); setDatosAceptadas({ indice: ["id_user", "id_solicitud", ], data: [...response.data.body.postulaciones] }); }) } useEffect(()=>{ setScrollTop(0); getPostulaciones(); }, []); return ( <> <br></br> <h3>Estados de las postulaciones a <u>Colaboradores</u> de las entregas </h3> <br></br> { <StickyHeadTable setDataTabla={setDatosAceptadas} dataTabla={datosAceptadas}/> } </> ) } function StickyHeadTable({ setDataTabla, dataTabla, setDataTablaPendientes, dataTablaPendientes }) { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(+event.target.value); setPage(0); }; useEffect(() => { console.log(dataTabla) }, []) return ( <Paper sx={{ margin: "auto", maxWidth: 800, overflow: 'hidden' }}> <TableContainer sx={{ maxHeight: 440 }}> <Table stickyHeader aria-label="sticky table"> <TableHead> <TableRow> { ["id_user", "id_solicitud"].map((elemento, i) => <TableCell key={i} align={"left"} style={{ minWidth: 80, fontWeight: 'bold' }} > {elemento} </TableCell> ) } <TableCell align={"center"} style={{ minWidth: 80, fontWeight: 'bold' }} > Estado </TableCell> </TableRow> </TableHead> <TableBody> { dataTabla?.data .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((fila, i) => { return ( <TableRow hover role="checkbox" tabIndex={-1} key={fila.id_solicitud+parseInt(Math.random()*10)}> {dataTabla.indice.map((index, p) => { return ( <TableCell key={fila[index]+parseInt(Math.random()*10)} align={"left"} style={{ minWidth: 5 }}> {fila[index]} </TableCell> ); })} <TableCell align={"center"} className={style.acciones} style={{ minWidth: 80 }}> <Button variant="contained" onClick={(e) => { console.log(fila['id_donacion']); }} style={{ background: "green", borderRadius: "8px", textTransform: "none" }}> Habilitado </Button> </TableCell> </TableRow> ); }) } </TableBody> </Table> </TableContainer> <TablePagination rowsPerPageOptions={[5, 10, 15]} component="div" count={dataTabla?.data.length} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Paper> ); }
package com.example.lsn03app.presentattion.view import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.lifecycle.ViewModelProvider import com.example.lsn03app.databinding.ActivityTaskBinding import com.example.lsn03app.di.Dependencies import com.example.lsn03app.domain.models.Task import com.example.lsn03app.presentattion.viewModel.TaskViewModel import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.* import kotlin.Int as Int class TaskActivity : AppCompatActivity() { lateinit var binding: ActivityTaskBinding private lateinit var mode: String lateinit var taskViewModel: TaskViewModel val taskListID by lazy { intent.getIntExtra(ARG_TASK_LIST_ID, 0) } val taskID by lazy { intent.getIntExtra(ARG_TASK_ID, 0) } val taskName by lazy { intent.getStringExtra(ARG_TASK_NAME).toString() } val taskDesc by lazy { intent.getStringExtra(ARG_TASK_DESCRIPTION).toString() } val taskIsFavourite by lazy { intent.getBooleanExtra(ARG_TASK_IS_FAVOURITE, false) } val createDate by lazy { intent.getStringExtra(ARG_TASK_CREATE_DATE) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTaskBinding.inflate(layoutInflater) taskViewModel = ViewModelProvider(this)[TaskViewModel::class.java] mode = intent.getStringExtra(ARG_TASK_MODE).toString() if (mode == "EDIT") { // Если в режиме редактирования, то кнопка добавления скрыта binding.add.visibility = View.GONE binding.deleteTask.visibility = View.VISIBLE binding.save.visibility = View.VISIBLE binding.createDateContent.visibility = View.VISIBLE binding.createDateText.visibility = View.VISIBLE // taskId = intent.getIntExtra("taskId", 0) binding.taskName.setText(taskName) binding.taskDesc.setText(taskDesc) binding.createDateContent.setText(createDate) binding.isFavouriteTask.isChecked = taskIsFavourite } else if (mode == "CREATE") { // Если в режиме редактирования, то кнопка сохранения скрыта binding.add.visibility = View.VISIBLE binding.deleteTask.visibility = View.INVISIBLE binding.save.visibility = View.INVISIBLE binding.createDateContent.visibility = View.GONE binding.createDateText.visibility = View.GONE } setContentView(binding.root) binding.add.setOnClickListener { val name = binding.taskName.text.toString() val desc = binding.taskDesc.text.toString() val isChecked = binding.isFavouriteTask.isChecked if (desc.isNotEmpty() && name.isNotEmpty()) { taskViewModel.addTask(Task(name, desc, taskListID, isChecked)) finish() } } binding.save.setOnClickListener { val name = binding.taskName.text.toString() val desc = binding.taskDesc.text.toString() val isChecked = binding.isFavouriteTask.isChecked if (desc.isNotEmpty() && name.isNotEmpty()) { taskViewModel.updateTask( Task(name, desc, taskListID, isChecked, taskID) ) finish() } } binding.deleteTask.setOnClickListener { taskViewModel.deleteTask( Task(taskName, taskDesc, taskListID, taskIsFavourite, taskID) ) finish() } } companion object { private const val ARG_TASK_LIST_ID = "taskListID" private const val ARG_TASK_MODE = "mode" private const val ARG_TASK_ID = "taskId" private const val ARG_TASK_NAME = "taskName" private const val ARG_TASK_DESCRIPTION = "taskDesc" private const val ARG_TASK_IS_FAVOURITE = "taskIsFavourite" private const val ARG_TASK_CREATE_DATE = "createDate" //private val taskId:Int = 0 fun getIntent(context: Context, taskListId: Int): Intent { val intent = Intent(context, TaskActivity::class.java) intent.putExtra(ARG_TASK_LIST_ID, taskListId) intent.putExtra(ARG_TASK_MODE, "CREATE") return intent } fun getIntent(context: Context, task: Task): Intent { val intent = Intent(context, TaskActivity::class.java) intent.putExtra(ARG_TASK_ID, task.id) intent.putExtra(ARG_TASK_NAME, task.name) intent.putExtra(ARG_TASK_DESCRIPTION, task.description) intent.putExtra(ARG_TASK_IS_FAVOURITE, task.isFavourite) intent.putExtra(ARG_TASK_LIST_ID, task.taskListId) intent.putExtra(ARG_TASK_MODE, "EDIT") intent.putExtra(ARG_TASK_CREATE_DATE, task.createDate) return intent } } }
/* * MIT License * * Copyright (c) 2022-present Alan Yeh <alan@yeh.cn> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package central.util.function; import lombok.SneakyThrows; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * ThrowableBiConsumer * * @author Alan Yeh * @since 2022/07/12 */ @FunctionalInterface public interface ThrowableBiConsumer<T, U, E extends Exception> { static <T, U, E extends Exception> ThrowableBiConsumer<T, U, E> of(ThrowableBiConsumer<T, U, E> consumer) { return consumer; } /** * 消费 * * @param t 第一个参数 * @param u 第二个参数 * @throws E 执行过程中的异常 */ void accept(T t, U u) throws E; /** * 忽略异常 */ default BiConsumer<T, U> ignoreThrows() { return (T t, U u) -> { try { accept(t, u); } catch (Exception ignored) { } }; } /** * 隐匿异常 * * @return 被包装后的函数 */ default BiConsumer<T, U> sneakThrows() { final var that = this; return new BiConsumer<T, U>() { @Override @SneakyThrows public void accept(T t, U u) { that.accept(t, u); } }; } /** * 处理异常,返回异常处理器的结果 * * @param handler 异常处理器,第一个参数是异常 * @return 被包装后的消费者 */ default BiConsumer<T, U> catchThrows(Consumer<E> handler) { return (T t, U u) -> { try { accept(t, u); } catch (Exception cause) { handler.accept((E) cause); } }; } /** * 处理异常,返回异常处理器的结果 * * @param handler 异常处理器,第一、二个是原参数,第三个是异常 * @return 被包装后的消费者 */ default BiConsumer<T, U> catchThrows(TriConsumer<T, U, E> handler) { return (T t, U u) -> { try { accept(t, u); } catch (Exception cause) { handler.accept(t, u, (E) cause); } }; } }
Use Case: Downloading data from the Sequence Read Archive (SRA) Code details and examples: To download data from the SRA, you can use the SRA Toolkit which provides the `fastq-dump` command for this purpose. 1. First, you need to have the SRA Toolkit installed. If you do not have it installed, you can download it from the NCBI website: https://trace.ncbi.nlm.nih.gov/Traces/sra/sra.cgi?view=software 2. Once you have the SRA Toolkit installed, you can use the following command to download data from SRA. Replace `SRA_RUN_ID` with the actual SRA run accession number. ```bash fastq-dump SRA_RUN_ID ``` This command will download the data in fastq format from the specified SRA run accession. 3. For example, if you want to download data from SRA run accession SRR4052018, you can use the following command: ```bash fastq-dump SRR4052018 ``` This will download the data in fastq format from the specified SRA run accession SRR4052018.
/** Authors: Michael Berg <michael.berg@zalf.de> Maintainers: Currently maintained by the authors. This file is part of the util library used by models created at the Institute of Landscape Systems Analysis at the ZALF. Copyright (C) 2007-2013, Leibniz Centre for Agricultural Landscape Research (ZALF) This program 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 (at your option) any later version. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ABSTRACT_DB_CONNECTIONS_H_ #define ABSTRACT_DB_CONNECTIONS_H_ #include <string> #include "db.h" #include "tools/read-ini.h" namespace Db { /*! * returns the db connections parameter map * - upon the first call the user can change where to find the ini-file * - subsequent calls with a parameter won't change the initial map anymore */ Tools::IniParameterMap& dbConnectionParameters(const std::string& initialPathToIniFile = "db-connections.ini"); //! connection data for schema from given parameter map DBConData dbConData(const Tools::IniParameterMap& dbParams, const std::string& abstractSchema); //! connection data via default parameter map inline DBConData dbConData(const std::string& abstractSchema) { return dbConData(dbConnectionParameters(), abstractSchema); } //! new connection from given parameters DB* newConnection(const Tools::IniParameterMap& dbParameters, const std::string& abstractSchema); //! new connection from default parameters inline DB* newConnection(const std::string& abstractSchema) { return newConnection(dbConnectionParameters(), abstractSchema); } bool attachDB(DB* connection, std::string attachAbstractSchema, std::string alias); } #endif
import Homepage from "./components/homepage"; import CreateContentType from "./components/CreateContentType"; import { Route, Routes, useLocation } from 'react-router-dom'; import MainPage from "./components/MainPage"; import { Provider } from "react-redux"; import appStore from "./components/utils/appStore"; import PDFAssetPage from "./components/PDFAssetPage"; const pages = [ { pageLink: '/create/:contentType', view: <CreateContentType isCopilotPage={true}/>, displayName: 'Create Content' }, { pageLink: '/create/:contentType/', view: <CreateContentType isCopilotPage={true}/>, displayName: 'Create Content Page' }, { pageLink: '/self/preview/:type/', view: <MainPage isCopilotPage={false} />, displayName: 'Main Page' }, { pageLink: '/edit/pdf/', view: <PDFAssetPage />, displayName: 'PDF Asset Page' }, { pageLink: "/edit/pdf/:id", view: <PDFAssetPage />, displayName: 'PDF Asset Page' } ]; function App() { return ( <Provider store={appStore}> <Homepage isCopilotPage={true}/> <Routes location={useLocation()}> {pages.map((page, index) => { return ( <Route exact path={page.pageLink} element={page.view} key={index} /> ); })} </Routes> </Provider> ); } export default App;
#ifndef HITTABLE_LIST_H #define HITTABLE_LIST_H #include "hittable.h" #include <memory> #include <vector> using std::shared_ptr; using std::make_shared; /** * Class representing a list of hittable objects. */ class hittable_list : public hittable { public: hittable_list() {} hittable_list(shared_ptr<hittable> object) { add(object); } void clear() { objects.clear(); } void add(shared_ptr<hittable> object) { objects.push_back(object); } virtual bool hit( const ray& r, double tmin, double tmax, hit_record& rec) const override; public: std::vector<shared_ptr<hittable>> objects; }; /** * Sees if a ray hit any element and in case of hit, computes the nearest data. * @param r - the ray. * @param t_min - the minimal t value. * @param t_max - the maximal t value. * @param rec - output of the hit data in case there is a hit. * @return bool true if the ray hit an object, false otherwise. */ bool hittable_list::hit(const ray& r, double t_min, double t_max, hit_record& rec) const { hit_record temp_rec; bool hit_anything = false; auto closest_so_far = t_max; for (const auto& object : objects) { if (object->hit(r, t_min, closest_so_far, temp_rec)) { hit_anything = true; closest_so_far = temp_rec.t; rec = temp_rec; } } return hit_anything; } #endif
package com.amswh.iLIMS.partner; import com.amswh.framework.Constants; import com.amswh.iLIMS.domain.PartyGroup; import com.amswh.iLIMS.service.ConstantsService; import com.amswh.iLIMS.service.PartyService; import com.amswh.iLIMS.service.PartygroupService; import com.amswh.iLIMS.utils.MyStringUtils; import jakarta.annotation.PostConstruct; import jakarta.annotation.Resource; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; import java.util.*; @Service public class PartnerService implements ApplicationContextAware { private List<String> orderedCodes;// 根据partner的重要程度排序,可以确定哪个服务先调用 Map<String,IPartner> parters=new HashMap<>(); // 用于存放各个Partner实现类 @Resource ConstantsService constantsService; @Resource PartygroupService partygroupService; @PostConstruct public void loadServices(){ Set<String> set1=this.parters.keySet(); this.orderedCodes=new ArrayList<>(); for(String code: Arrays.asList("YQ","HY","MEGA","XNYT","PAJK","RH")){ if(set1.contains(code)){ this.orderedCodes.add(code); } } for(String key:set1){ if(!this.orderedCodes.contains(key)){ this.orderedCodes.add(key); } } for(String code:orderedCodes){ System.out.println(" >>>>>>>>>>>>>> "+ code+" is ready for service"); } } public PatientInfo fetchPatientInfo(String partnerCode,String barCode){ IPartner partner=this.parters.get(partnerCode); if(partner==null){ partner=this.parters.get("NORMAL"); } try { return partner.fetchPatientInfo(barCode); }catch (Exception err){ err.printStackTrace(); } return null; } public PatientInfo fetchPatientInfo(String barCode){ for(String partnerCode:orderedCodes){ try { System.out.println(">>>>>>>>>>>>>>>>>>>"+partnerCode); PatientInfo patient = this.fetchPatientInfo(partnerCode, barCode); if (patient != null) { patient.setPartnerCode(partnerCode); if(!MyStringUtils.isEmpty(patient.getProductCode())){ patient.setProductName(constantsService.getProductName(patient.getProductCode())); } if(!MyStringUtils.isEmpty(patient.getPartnerCode())){ PartyGroup company=partygroupService.getById(patient.getPartnerCode()); if(company!=null) { patient.setPartnerName(company.getFullName()); } } return patient; } } catch(Exception err){ System.out.println("\n调用第三方API异常:partner="+partnerCode+" barCode="+barCode); System.out.println(err.getMessage()+"\n"); err.printStackTrace(); } } return null; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Map<String, IPartner> map = applicationContext.getBeansOfType(IPartner.class); parters = new HashMap<>(); System.out.println("\n"); int index=0; for(String key:map.keySet()){ IPartner value=map.get(key); System.out.println((index++)+" >>>>>>>>>>>>>>>>>> initializing partner service: " + value.whoAmI() + " with class: " + value.getClass().getName()); parters.put(value.whoAmI(), value); } } }
import { withProjectAuth } from "@/lib/auth"; import { addDomain, removeDomain, validateDomain } from "@/lib/api/domains"; import prisma from "@/lib/prisma"; import { changeDomainForImages, changeDomainForLinks, deleteDomainLinks, setRootDomain, } from "@/lib/api/domains"; export default withProjectAuth(async (req, res, project) => { const { slug, domain } = req.query as { slug: string; domain: string }; if ( !slug || typeof slug !== "string" || !domain || typeof domain !== "string" ) { return res .status(400) .json({ error: "Missing or misconfigured project slug or domain" }); } // PUT /api/projects/[slug]/domains/[domain] edit a project's domain if (req.method === "PUT") { const { slug: newDomain, target, type, primary } = req.body; /* If the domain is being changed (and the new domain is valid), we need to: 1. Remove the old domain from Vercel 2. Add the new domain to Vercel 3. If there's a landing page set, update the root domain in Redis 4. Update all links in the project to point to the new domain 5. Update all images in the project to point to the new domain 6. If the domain is being set as the primary domain, set all other domains to not be the primary domain 7. Update the domain in the database along with its primary status */ if (newDomain !== domain) { const validDomain = await validateDomain(newDomain); if (validDomain !== true) { return res.status(422).json({ domainError: validDomain, }); } const response = await Promise.allSettled([ removeDomain(domain), addDomain(newDomain), target && setRootDomain(domain, target, type === "rewrite", newDomain), changeDomainForLinks(domain, newDomain), changeDomainForImages(domain, newDomain), primary && prisma.domain.updateMany({ where: { projectId: project.id, primary: true, }, data: { primary: false, }, }), prisma.domain.update({ where: { slug: domain, }, data: { slug: newDomain, target, type, primary, }, }), ]); return res.status(200).json(response); } else { /* If the domain is not being changed, we only need to: 1. If there's a landing page set, update the root domain in Redis 2. If the domain is being set as the primary domain, set all other domains to not be the primary domain 3. Then, update the domain in the database along with its primary status */ const response = await Promise.allSettled([ target && setRootDomain(domain, target, type === "rewrite"), primary && prisma.domain.updateMany({ where: { projectId: project.id, primary: true, }, data: { primary: false, }, }), prisma.domain.update({ where: { slug: domain, }, data: { target, type, primary, }, }), ]); return res.status(200).json(response); } } else if (req.method === "DELETE") { const response = await Promise.allSettled([ removeDomain(domain), deleteDomainLinks(domain), ]); const deletedDomain = await prisma.domain.delete({ where: { slug: domain, }, }); return res.status(200).json({ ...response, deletedDomain, }); } else { res.setHeader("Allow", ["PUT", "DELETE"]); return res.status(405).json({ error: `Method ${req.method} Not Allowed` }); } });
# 09.1 Weekday Lesson Plan: Introduction to Node.js and ES6 ## Overview This lesson introduces Node.js and the new syntax that comes with ES6. This includes arrow functions and new variables `let` and `const`. We will also cover template literals and how they can be helpful in the development process. > **Important**: Ensure that all activities using the `inquirer` package is using version 8.2.4. The latest version of `inquirer` (version 9+) introduces breaking changes to activities. All activities have version 8.2.4 in their respective `package.json` files but should you or your students install `inquirer`, please use `npm i inquirer@8.2.4`. ## Instructor Notes * In this lesson, students will complete activities `01-Ins_Node-Demo` through `10-Stu_TemplateLiterals`. * Students will be expected to have the latest LTS version of Node.js installed prior to class, but if they don't, be sure to tell them that they can install it using the resources found on the [Node.js installation guide on The Full-Stack Blog](https://coding-boot-camp.github.io/full-stack/nodejs/how-to-install-nodejs). Remind students that it is important to download the recommended LTS or Long Term Support version, since this is the most recent stable release. > **Important**: Because some of the technologies we use in this course like GraphQL and MERN do not work well with Node 18, we will roll back to Node 16. Once these problems have been resolved, using Node v18 will be fine. Follow this [link to our blog on how to install Node.](https://coding-boot-camp.github.io/full-stack/nodejs/how-to-install-nodejs). * Transitioning from client-side to back-end development can be a little confusing at first. Remind students that Node.js is Chrome's V8 engine running on the machine rather than in the browser, giving us access to things like the file system. * If students ask why they are learning Node.js, explain that Node.js allows us to create APIs and build applications using the client-server model. * Remind students to do a `git pull` of the class repo to have today's activities ready and open in VS Code. * If you are comfortable doing so, live-code the solutions to the activities. If not, just use the solutions provided and follow the prompts and talking points for review. * Let students know that the Bonus at the end of each activity is not meant to be extra coding practice, but instead is a self-study on topics beyond the scope of this module for those who want to further their knowledge. ## Learning Objectives By the end of class, students will be able to: * Explain the client-server model. * Run very simple JavaScript files from the command line using Node.js. * Explain arrow functions and how they impact the `this` context. * Use template strings and use `const` and `let` in place of `var`. * Use functional loops like `map()` and `filter()`. ## Slide Deck * [Module 09 Slide Deck](https://docs.google.com/presentation/d/1zkzb8E8ORZbn-JeS47sIEid1bgbN011-xB7CWpzaIQE/edit?usp=sharing) ## Time Tracker | Start | # | Activity Name | Duration | | ----- | --- | ---------------------------------------- | -------- | | 0:00 | 1 | Instructor Do: Stoke Curiosity | 0:10 | | 0:10 | 2 | Instructor Demo: Node.js | 0:05 | | 0:15 | 3 | Student Do: Node.js | 0:15 | | 0:30 | 4 | Instructor Review: Node.js | 0:10 | | 0:40 | 5 | Instructor Demo: Arrow Functions | 0:05 | | 0:45 | 6 | Student Do: Arrow Functions | 0:15 | | 1:00 | 7 | Instructor Review: Arrow Functions | 0:10 | | 1:10 | 8 | Instructor Demo: Let and Const | 0:05 | | 1:15 | 9 | Student Do: Let and Const | 0:15 | | 1:30 | 10 | BREAK | 0:15 | | 1:45 | 11 | Instructor Review: Let and Const | 0:10 | | 1:55 | 12 | Instructor Demo: Functional Loops | 0:05 | | 2:00 | 13 | Student Do: Functional Loops | 0:15 | | 2:15 | 14 | Instructor Review: Functional Loops | 0:10 | | 2:25 | 15 | Instructor Demo: Template Literals | 0:05 | | 2:30 | 16 | Student Do: Template Literals | 0:15 | | 2:45 | 17 | Instructor Review: Template Literals | 0:15 | | 3:00 | 18 | END | 0:00 | --- ## Class Instruction ### 1. Instructor Do: Stoke Curiosity (10 min) * Welcome students to class. * Open the [slide deck](https://docs.google.com/presentation/d/1zkzb8E8ORZbn-JeS47sIEid1bgbN011-xB7CWpzaIQE/edit?usp=sharing) and follow these prompts on their corresponding slides: * **Introduction to Node.js**: Today's class is a milestone as we make the transition from writing client-side code to server-side code using Node.js. * **What is full-stack web development?** * Full-stack web development encompasses the suite of tools required to build both the front and back ends of a web application. * **How much of the stack do we know?** * So far, we have learned about client-side development. The three primary components of client-side code are HTML, CSS, and JavaScript. We can also fetch data from an API for use in the client. * **What is a client?** * A **client** is a piece of computer hardware or software that makes requests to a server. It can be a desktop computer, laptop, mobile device, and beyond! * **What is GitHub Pages doing?** * GitHub Pages is serving content to clients. * **What is a server?** * Depending on the context, a server is both the physical hardware and the software that hears requests from users and returns something, like an HTML or image file, or completes a process. * **What is the client-server model?** * In modern web applications, there is constant back-and-forth communication between the visuals displayed on the user’s browser (the front end) and the data and logic stored on the server (the back end). Clients make requests, and servers respond. * **What is Node.js?** * Node.js allows us to run JavaScript outside the browser as well as on a server. Because Node.js is purely JavaScript, a front-end JavaScript developer can also work on server side code without having to learn a new programming language. Node.js is an open source, cross-platform JavaScript runtime environment designed to be run outside of the browser. It is a general utility that can be used for a variety of purposes including asset compilation, scripting, monitoring, and **most notably as the basis for web servers**. * Navigate to `28-Stu_Mini-Project/Main/Basic/index.js` and demonstrate the following: * 🔑 We are viewing the mini-project that we will be able to build by the end of this module. * 🔑 It is a command-line tool that generates an HTML portfolio page from user input. * First run `npm i` to install inquirer. * Make sure to point out that we will be using Node's native `fs` module for this project. * Run `node index` to start the app and enter in the prompts when asked. * Notice how the provided inputs are now visible in the resulting `index.html` by opening it in the browser. * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ What are we learning? * 🙋 We are learning more about Node.js, third-party modules, and Node's native `fs` module. * ☝️ How does this project build off or extend previously learned material? * 🙋 We are continuing to expand our knowledge of using Javascript to build programs, but this time we are working outside the browser. * ☝️ How does this project relate to your career goals? * 🙋 Part of being a full-stack web developer is being as comfortable working on back-end technologies as you are with front-end technologies. By working on this project, you are adding another tool to your full-stack arsenal, which will ultimately make you a better developer. * Answer any questions before proceeding to the next activity. ### 2. Instructor Demo: Node.js (5 min) * Open `01-Ins_Node-Demo/index.js` in your terminal. * Run `node index.js` from the command line and demonstrate the following: * 🔑 When we run the `index.js` file, we notice that the value of `this` has changed significantly. * 🔑 When we examine the output of the console log, we notice some recognizable methods that are available in Node.js. * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ Why is it necessary to wrap the `console.log` in an invoked function? * 🙋 Simply console logging the `this` keyword will return an empty object, because context only makes sense inside of functions. Without one, we won't have anything to return. * Answer any questions before proceeding to the next activity. * In preparation for the activity, ask TAs to start directing students to the activity instructions found in `02-Stu_Hello-Node/README.md`. ### 3. Student Do: Node.js (15 min) * Direct students to the activity instructions found in `02-Stu_Hello-Node/README.md`. * Break your students into pairs that will work together on this activity. ```md # 📖 Create a Node.js Application Work with a partner to implement the following user story: * As a developer, I want to be able to execute JavaScript programs with Node.js. * As a developer, I want to make a program that accepts a string as an input and logs it to the terminal. ## Acceptance Criteria * It's done when I have created a file, `index.js`, in my working directory. * It's done when I have written JavaScript to log the string "Hellooo, Node!" ## 📝 Notes Refer to the documentation: [Node.js documentation](https://nodejs.org/en/docs/) ## 🏆 Bonus If you have completed this activity, work through the following challenge with your partner to further your knowledge: * What happens when you log `window`? What happens when you try to use `prompt`, `alert`, or `confirm`? Use [Google](https://www.google.com) or another search engine to research this. ``` * While breaking everyone into groups, be sure to remind students and the rest of the instructional staff that questions on Slack or otherwise are welcome and will be handled. It's a good way for your team to prioritize students who need extra help. ### 4. Instructor Review: Node.js (10 min) * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ How comfortable do you feel with the Node.js thus far? (Poll via Fist to Five, Slack, or Zoom) * Assure students that we will cover the solution to help solidify their understanding. If questions remain, remind them to use office hours to get extra help! * Open `02-Stu_Hello-Node/Solved/index.js` in your IDE and explain the following: * We use `console.log()` to print out the string "Hellooo, Node!" in our terminal. ```js console.log("Hellooo, Node!"); ``` * 🔑 When we run `node index.js` and examine the output of the console log, we notice that it logs our string properly. * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ What happens if we were to log `window` to the console? * 🙋 We get an error&mdash;`window` is not defined in Node.js. * ☝️ What kinds of things do we think are possible in the browser, but not possible in Node.js? * 🙋 We can't use prompts, confirms, or alerts because of the `window` object. * ☝️ What can we do if we don't completely understand this? * 🙋 We can refer to supplemental material, read the [Node.js documentation](https://nodejs.org/en/docs/), and stick around for office hours to ask for help. * Answer any questions before proceeding to the next activity. ### 5. Instructor Demo: Arrow Functions (5 min) * Open `03-Ins_Arrow-Function/01-syntax.js` in your browser and demonstrate the following: * In this demonstration, you will give students an overview of arrow functions, including syntax differences, when to use them, and when to avoid them. * Explain to the class that ES6 introduces a newer, shorter syntax for writing functions. Consider the following example found in `03-Ins_Arrow-Function/01-syntax.js`. * 🔑 As you walk students through each of the following functions, see if they can point out the differences in syntax: ```js // ES5 function var createGreeting = function(message, name) { return message + ", " + name + "!"; }; // ES6 arrow function var createGreeting = (message, name) => { return message + ", " + name + "!"; }; ``` * Answer any questions about arrow functions before moving on to some differences between arrow functions and regular functions. * In preparation for the activity, ask TAs to start directing students to the following code found in `03-Ins_Arrow-Function/02-context.js`: ```js // Depending on the environment `setTimeout` is called in, it may refer to one of two objects // In the browser, `setTimeout` is a property of the `window` object // In node, it belongs to a special "Timeout" object var person = { name: "Hodor", saySomething: function() { console.log(this.name + " is thinking..."); setTimeout(function() { console.log(this.name + "!"); }, 100); } }; person.saySomething(); // prints "Hodor is thinking..." // prints "undefined!" 100ms later ``` * Students might still not feel completely comfortable with the `this` keyword in JavaScript yet; reassure them that many experienced developers also have trouble with it. * Point out how this code works as intended: an arrow function automatically binds to the context or object it's created inside of, even if it is not a direct property of that object. The arrow function is created when `saySomething` is run, inside of `person`, right before the `setTimeout` is run. * In preparation for the discussion, ask TAs to start directing students to the following code found in `03-Ins_Arrow-Function/03-property-methods.js`: ```js // Avoid using arrow functions for object methods var dog = { name: "Lassie", sound: "Woof!", makeSound: () => console.log(this.sound), // readTag: () => console.log("The dog's tag reads: " + this.name + ".") }; // Prints `undefined` dog.makeSound(); // Prints `The dog's tag reads: undefined.` dog.readTag(); // In the makeSound and readTag methods, `this` doesn't refer to `dog` // If this code run in node, `this` refers to `module.exports` (the object containing all the exports in this file) // If this code was run in the browser, `this` would refer to the window ``` * Explain that when working with objects, we typically want to avoid using arrow functions for the methods. In these cases, the arrow function will bind to the context it's created inside of (probably the `window` or `module.exports` object). * We can replace regular functions most of the time, except when it comes to using the `this` keyword. * With practice, students will grow more comfortable knowing when to use and not use arrow functions. For now, they can use them most of the time, except as object methods. * Answer any questions before proceeding to the next activity. ### 6. Student Do: Arrow Function Practice (15 min) * Direct students to the activity instructions found in `04-Stu_Arrow-Function-Practice/README.md`. * Break your students into pairs that will work together on this activity. ```md # 🐛 Fix Implementation of Arrow Functions Work with a partner to resolve the following issue(s): * As a user, I want to run a script that will update a movie queue. ## Expected Behavior When a user runs the script, it will add and remove movies from the queue and display the movies currently in the queue. ## Actual Behavior The script exits out with an error message. ## Steps to Reproduce the Problem 1. Navigate to the `Unsolved` folder from the command line. 2. Run `node index.js`. 3. Note the error that is printed. ## 💡 Hints What is an example of when we shouldn't use arrow functions? ## 🏆 Bonus If you have completed this activity, work through the following challenge with your partner to further your knowledge: * How can you shorten the arrow function syntax even further with implicit return statements? Use [Google](https://www.google.com) or another search engine to research this. ``` * While breaking everyone into groups, be sure to remind students and the rest of the instructional staff that questions on Slack or otherwise are welcome and will be handled. It's a good way for your team to prioritize students who need extra help. ### 7. Instructor Review: Arrow Function Practice (10 min) * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ How comfortable do you feel with arrow functions? (Poll via Fist to Five, Slack, or Zoom) * Assure students that we will cover the solution to help solidify their understanding. If questions remain, remind them to use office hours to get extra help! * Use the prompts and talking points (🔑) below to review the following key points: * ✔️ Arrow functions * ✔️ `this` binding * ✔️ Implicit return statements * Open `04-Stu_Arrow-Function-Practice/Solved/index.js` in your IDE and explain the following: * The following `funnyCase()` function is able to use arrow syntax, because there is no `this` context that needs to be preserved: ```js var funnyCase = string => { var newString = ""; for (var i = 0; i < string.length; i++) { if (i % 2 === 0) newString += string[i].toLowerCase(); else newString += string[i].toUpperCase(); } return newString; }; ``` * 🔑 When using arrow functions, we can use an implied return to reduce the code even further, as shown in the following example: ```js var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var doubled = map(numbers, element => element * 2); ``` * 🔑 In the following example, we had to convert the arrow functions back to regular functions to preserve the context of `this` in the object: ```js var netflixQueue = { queue: [ "Mr. Nobody", "The Matrix", "Eternal Sunshine of the Spotless Mind", "Fight Club" ], watchMovie: function() { this.queue.pop(); }, }; ``` * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ Why would you use arrow functions? * 🙋 The syntax is easier to write and makes for cleaner-looking code. * ☝️ What can we do if we don't completely understand this? * 🙋 We can refer to supplemental material, read the [MDN Web Docs on arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), and stick around for office hours to ask for help. * Answer any questions before proceeding to the next activity. ### 8. Instructor Demo: let and const (5 min) * Open `05-Ins_Let-Const/let.js` in your IDE and demonstrate the following: * 🔑 In JavaScript, `var` is **function scoped**. This means that variables and functions defined inside the scope of the function can't escape the function. * 🔑 ES6 offers us a new way to define variables using `let`. Unlike `var`, `let` is **block scoped**. * 🔑 A **block** is created by a pair of curly braces. This includes loops and conditional statements as well as function bodies. Because `let` is block scoped, any variables we define using `let` inside of a block are only available inside of that block. * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ In the following code snippet, why does the variable `i` exist outside of the function scope in the first `for` loop, while `j` in the second `for` loop is `undefined`? ```js // 1. When using var, our counter exists after a for-loop is done for (var i = 0; i < 5; i++) { console.log(i); } console.log(i); // Prints 5 // When using let, our counter is not defined outside of the for-loop block let x = 42; for (let j = 0; j < 5; j++) { console.log(j); console.log(x); } console.log(j); // ReferenceError: j is not defined let j = 42; console.log(j); // prints 42 ``` * 🙋 We used the `var` keyword to assign the variable in the first `for` loop, allowing it to be accessed outside the function scope. The second `for` loop has `j` limited to the function scope because we defined it using the `let` keyword. * Open `05-Ins_Let-Const/const.js` in your IDE and demonstrate the following: * Part of the ES6 syntax is a new keyword called `const`, found in many other programming languages and generally used whenever we know a variable should not be changed. * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ After reviewing this code, can anyone explain a situation when using `const` might not be ideal? * 🙋 Because a variable declared with `const` cannot be reassigned, it might be a bad idea to use it for any data that needs to be mutated. * Answer any questions before proceeding to the next activity. * In preparation for the activity, ask TAs to start directing students to the activity instructions found in `06-Stu_Let-Const/README.md`. ### 9. Student Do: let and const (15 min) * Direct students to the activity instructions found in `06-Stu_Let-Const/README.md`. * Stress that students don't need to completely understand all of the code in the activity. They just need to remember what we have covered about `const`, `let`, and arrow functions. * Break your students into pairs that will work together on this activity. ```md # 🐛 Fix Issue With Scoped Variable Work with a partner to resolve the following issue(s): * As a developer, I want my variables to be correctly scoped so that my functions work correctly. ## Expected Behavior When a user runs the `addGreetingMessage` function, it should log the messages in the correct order inside the console. Hello Tammy How are you? When a user runs the `calloutCounter` function, it should log the messages in the correct order inside the console. 5 Inside the loop 4 Inside the loop 3 Inside the loop 2 Inside the loop 1 Inside the loop Outside of the loop When a user runs the `countMatrix` function, it should log the entire matrix in the correct order inside the console. 1 2 3 4 5 6 7 8 9 ## Actual Behavior The current `addGreetingMessage` function logs: Hello Tammy Hello Tammy The current `calloutCounter` function gives us an error when it is called. The current `countMatrix` function logs: 1 2 3 ## Steps to Reproduce the Problem 1. Navigate to the `Unsolved` folder from the command line. 2. Run `node index.js`. 3. Note the error that is printed. ## 💡 Hints What does it mean when a variable is block scope? ## 🏆 Bonus If you have completed this activity, work through the following challenge with your partner to further your knowledge: * What is the difference between function scope and block scope? Use [Google](https://www.google.com) or another search engine to research this. ``` * While breaking everyone into groups, be sure to remind students and the rest of the instructional staff that questions on Slack or otherwise are welcome and will be handled. It's a good way for your team to prioritize students who need extra help. ### 10. BREAK (15 min) ### 11. Instructor Review: let and const (10 min) * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ How comfortable do you feel with `let` and `const`? (Poll via Fist to Five, Slack, or Zoom) * Assure students that we will cover the solution to help solidify their understanding. If questions remain, remind them to use office hours to get extra help! * Use the prompts and talking points (🔑) below to review the following key points: * ✔️ `let` * ✔️ `const` * Open `06-Stu_Let-Const/Solved/index.js` in your IDE and explain the following: * Inside of our `addGreetingMessage` function we have two `message` variables. * 🔑 `var` is function scoped so we cannot use the same name for a variable inside our function unless we use `let`. * 🔑 `let` is block scoped which lets us use our `message` variable twice since we have two separate blocks in our function. ```js const addGreetingMessage = (name) => { let message = "How are you?"; if(name.length > 0){ let message = "Hello " + name; console.log(message); } console.log(message); } ``` * 🔑 The `calloutCounter` function had two variables named `callout` since we used `const` on the first one, it has made the variable a constant with block scope. * 🔑 The `callout` variable inside the `while...loop` is hoisted to the top of the functions scope because it was created with `var`. * We can easily fix this problem by making each variables block scoped with `let`. ```js const calloutCounter = () => { let callout = 'Outside of the loop'; let counter = 5; while( counter > 0) { let callout = 'Inside the loop'; console.log(counter, callout); counter--; } console.log(callout); } ``` * By using `let` we can ensure that our `index` variables will not be accessed from outside of their scope. * Using `const` lets us know that we shouldn't try renaming variable within its scope. ```js const countMatrix = (matrix) => { for (let index = 0; index < matrix.length; index++) { const line = matrix[index]; for (let index = 0; index < line.length; index++) { const element = line[index]; console.log(element); } } } ``` * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ What is a good use for `let`? * 🙋 When we need to reassign a value. An example of this would be a counter variable like `i`. * ☝️ What can we do if we don't completely understand this? * 🙋 We can refer to supplemental material, read the [MDN Web Docs on let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) and the [MDN Web Docs on const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const), and stick around for office hours to ask for help. * Answer any questions before proceeding to the next activity. ### 12. Instructor Demo: Functional Loops (5 min) * Open `07-Ins_Functional-Loops/index.js` in your browser and demonstrate the following: * `forEach()` performs a callback on each item in the array, mutating it in place. * `filter()` returns a new array of items that result in a truthy value after being passed into the callback. * `map()` is very similar to `forEach()` with the exception that it returns a new array. We can use it to create an array of modified elements if we so choose. * 🔑 Explain that `filter()` and `map()` are used heavily in React when rendering elements from array data. Students have probably seen `forEach()` already, but it's a good stepping stone for understanding `filter()` and `map()`. * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ What is the difference between `filter()` and `forEach()`? * 🙋 `filter()` returns a brand-new array, while `forEach()` mutates the existing array. * ☝️ How is `map()` different than `filter()`? * 🙋 `map()` will return a brand-new array like `filter()` does; however, the length of the array that `map()` returns will be the exact same as the input array. This isn't always the case for the `filter()` method. * Answer any questions before proceeding to the next activity. * In preparation for the activity, ask TAs to start directing students to the activity instructions found in `08-Stu_Functional-Loops/README.md`. ### 13. Student Do: Functional Loops (15 min) * Direct students to the activity instructions found in `08-Stu_Functional-Loops/README.md`. * Break your students into pairs that will work together on this activity. ```md # 📐 Add Comments to Implementation of Functional Loops Work with a partner to add comments describing the functionality of the code found in [filter.js](./Unsolved/filter.js) and [map.js](./Unsolved/map.js). ## 📝 Notes Refer to the documentation: * [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) * [map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) --- ## 🏆 Bonus If you have completed this activity, work through the following challenge with your partner to further your knowledge: * What is the `reduce()` array method? Use [Google](https://www.google.com) or another search engine to research this. ``` * While breaking everyone into groups, be sure to remind students and the rest of the instructional staff that questions on Slack or otherwise are welcome and will be handled. It's a good way for your team to prioritize students who need extra help. ### 14. Instructor Review: Functional Loops (10 min) * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ How comfortable do you feel with functional loops? (Poll via Fist to Five, Slack, or Zoom) * Assure students that we will cover the solution to help solidify their understanding. If questions remain, remind them to use office hours to get extra help! * Use the prompts and talking points (🔑) below to review the following key points: * ✔️ `map()` * ✔️ `filter()` * Open `08-Stu_Functional-Loops/Solved` in your IDE and explain the following: * 🔑 Remember that each of these array methods is just another type of `for` loop. * 🔑 We manipulate each item in an array in some way and return the original mutated array or a modified version of the original array. * With the `map()` method, a callback is run once for every element in the array. The value that is returned gets added to the corresponding index of the new array, as shown in the following example: ```js const originalArray = [1, 3, 2, 5, 10]; const doubledArray = originalArray.map(function(data) { return data * 2; }); console.log(doubledArray); console.log(originalArray); const tripledArray = originalArray.map(data => data * 3); const oddOrEven = originalArray.map(num => (num % 2 === 0 ? "even" : "odd")); ``` * With the `filter()` method, if the callback function returns something truthy, the array element is copied to the new array. Otherwise it is skipped. * In the following example, the first array should contain only prime numbers, and the second should contain only numbers larger than `5`: ```js const originalArray = [1, 3, 2, 5, 10]; const evenNumbers = originalArray.filter(function(data) { if (data % 2 === 0) { return true; } }); console.log(evenNumbers); console.log(originalArray); const isPrime = num => { for (let i = 2; i < num; i++) { if (num % i === 0) return false; } return num !== 1; }; numbers (`primeArray`) const primeArray = originalArray.filter(isPrime); larger than 5(`moreThan5Array`) const moreThan5Array = originalArray.filter(num => num > 5); ``` * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ What are some real-life use cases for the `filter()` method? * 🙋 When filtering out a list of images that contain the word `large` in the file name; when returning an array of all user accounts that use `@gmail.com`; or when grabbing a list of GitHub issues that have a status of `closed`. * ☝️ What is an example of when you might want to map over something? * 🙋 When returning an HTML line-item element for every item in a list while building a to-do list. * Answer any questions before proceeding to the next activity. ### 15. Instructor Demo: Template Literals (5 min) * Open `09-Ins_Template-Literals/index.js` in your browser and demonstrate the following: * 🔑 Using string interpolation, or template literals, we have a new way of concatenating variables to the rest of strings. This is a new feature included in ES6. * 🔑 Template literals are much more readable and easier to manage. Consider the following example: ```js const arya = { first: "Arya", last: "Stark", origin: "Winterfell", allegiance: "House Stark" }; const greeting = `My name is ${arya.first}! I am loyal to ${arya.allegiance}.`; ``` * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ What are the main differences that you notice in syntax between regular string concatenation and template literals? * 🙋 Immediately we notice that template strings use backticks instead of quotes. Additionally, instead of using plus signs, we can now reference variables explicitly using the `${}` syntax. * Answer any questions before proceeding to the next activity. * In preparation for the activity, ask TAs to start directing students to the activity instructions found in `10-Stu_Template-Literals/README.md`. ### 16. Student Do: Template Literals (15 min) * Direct students to the activity instructions found in `10-Stu_Template-Literals/README.md`. * Break your students into pairs that will work together on this activity. ```md # 🏗️ Implement Template Literals Work with a partner to implement the following user story: * As a developer, I want to know how to use template literals inside of a string. ## Acceptance Criteria * It's done when I have created a `music` object in `Unsolved/index.js`. * It's done when I have added `title`, `artist`, and `album` properties to the `music` object. * It's done when I have used template literals inside the `songSnippet` variable to output data from the `music` object. * It's done when I see the results in my command line after I run the `index.js` file. ## 💡 Hints * Can we use template literals in place of string concatenation? ## 🏆 Bonus If you have completed this activity, work through the following challenge with your partner to further your knowledge: * It's easy to get confused about which syntax belongs to which technology. The dollar sign (`$`) is used a lot in JavaScript&mdash;what are some other places you have seen the dollar sign used? Use [Google](https://www.google.com) or another search engine to research this ``` * While breaking everyone into groups, be sure to remind students and the rest of the instructional staff that questions on Slack or otherwise are welcome and will be handled. It's a good way for your team to prioritize students who need extra help. ### 17. Instructor Review: Template Literals (15 min) * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ How comfortable do you feel with template literals? (Poll via Fist to Five, Slack, or Zoom) * Assure students that we will cover the solution to help solidify their understanding. If questions remain, remind them to use office hours to get extra help! * Use the prompts and talking points (🔑) below to review the following key points: * ✔️ Backticks vs. quotation marks * ✔️ `${}` syntax * ✔️ Template literals vs. string concatenation * Open `10-Stu_Template-Literals/Solved/index.js` in your IDE and explain the following: * 🔑 Template strings are much easier to read than traditional string concatenation. * 🔑 Dealing with spacing is a lot easier using template literals. * 🔑 Don't forget to use backticks instead of quotes. This is a very easy mistake to make. * In the following example, we create a template string that will eventually be injected into the DOM: ```js const music = { title: "Yeke Yeke", artist: "Mory Kant", album: "Akwaba Beach" }; const songSnippet = `${music.title} by ${music.artist} from the album ${music.album} is currently playing`; console.log(songSnippet) ``` * 🔑 We use the `${}` syntax to reference the music object and the variables within it in the template literals. * Ask the class the following questions (☝️) and call on students for the answers (🙋): * ☝️ What are the benefits of using template strings? * 🙋 They are easier to read and easier to manage. They also allow us to maintain indentation and formatting of the content when inside the backticks. * ☝️ What can we do if we don't completely understand this? * 🙋 We can refer to supplemental material, read the [MDN Web Docs on template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), and stick around for office hours to ask for help. * Answer any questions before ending the class. ### 18. END (0 min) How did today’s lesson go? Your feedback is important. Please take 5 minutes to complete this [anonymous survey](https://forms.gle/RfcVyXiMmZQut6aJ6). --- © 2023 edX Boot Camps LLC. Confidential and Proprietary. All Rights Reserved.
import React, { useEffect, useState } from "react"; import { FaStar } from "react-icons/fa"; import { Link } from "react-router-dom"; const Products = () => { const [products, setProducts] = useState([]); useEffect(() => { fetch("data.json") .then((res) => res.json()) .then((data) => setProducts(data)) // .catch((error) => console.error(error)); }, []); return ( <div> <div className="text-center mt-5"> <h1 className="text-3xl lg:text-5xl font-bold"> Our All Product </h1> <p className="text-2xl text-gray-500 mt-3"> We are committed to our customer to offer high-quality products at affordable prices. </p> </div> <div className="w-[80%] mx-auto gap-8 p-5 grid lg:grid-cols-3"> {products.map((product) => ( <div key={product.id} className="card card-compact lg:w-80 bg-base-100 shadow-xl hover:shadow-2xl my-12"> <figure> <img className="h-[300px] w-[100%] p-4 rounded-3xl" src={product.image} alt="Product name" /> </figure> <div className="card-body"> <h2 className="card-title font-semibold">{product.productName}</h2> <div className=" flex justify-between font-bold"> <p>Packing: {product.packing} </p> <div className="flex items-center gap-1"> <FaStar className="text-orange-500"></FaStar><p> {product.rating}</p> </div> </div> <p className="font-bold text-lg">Origin: <span className="text-blue-600 ">{product.country}</span></p> <div className="flex justify-between items-center gap-10 mt-3 mb-5"> <> {/* {`/toys/${_id}`} */} <Link to={`/productDetails/${product.id}`}> <button className="px-4 py-2 rounded-md text-white font-bold text-base bg-gradient-to-r from-green-600 to-lime-300 hover:from-lime-300 hover:to-green-600 ..." > View Details </button> </Link> </> <p className=" text-right text-xl font-semibold">Tk {product.price} /kg</p> </div> </div> </div> ))} </div> </div> ); }; export default Products;
using System; public class Aluno { private int matricula; public string nome; private double notaProva1; private double notaProva2; private double notaTrabalho; public Aluno(int matricula, string nome) { this.matricula = matricula; this.nome = nome; notaProva1 = 0.0; notaProva2 = 0.0; notaTrabalho = 0.0; } public void RegistrarNotaProva1(double nota) { notaProva1 = nota; } public void RegistrarNotaProva2(double nota) { notaProva2 = nota; } public void RegistrarNotaTrabalho(double nota) { notaTrabalho = nota; } public double CalcularMediaFinal() { double mediaProvas =(notaProva1 + notaProva2) * 2.5; double mediaTrabalho = notaTrabalho * 2; double mediaFinal = (mediaProvas + mediaTrabalho) / 7; return Math.Round(mediaFinal,2); } } class Program { static void Main(string[] args) { Console.WriteLine("Digite a matrícula do aluno:"); int matricula = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Digite o nome do aluno:"); string nome = Console.ReadLine(); Aluno aluno = new Aluno(matricula, nome); Console.WriteLine("Digite a nota da prova 1:"); double notaProva1 = Convert.ToDouble(Console.ReadLine()); aluno.RegistrarNotaProva1(notaProva1); Console.WriteLine("Digite a nota da prova 2:"); double notaProva2 = Convert.ToDouble(Console.ReadLine()); aluno.RegistrarNotaProva2(notaProva2); Console.WriteLine("Digite a nota do trabalho:"); double notaTrabalho = Convert.ToDouble(Console.ReadLine()); aluno.RegistrarNotaTrabalho(notaTrabalho); double mediaFinal = aluno.CalcularMediaFinal(); Console.WriteLine($"Média final do aluno {aluno.nome}: {mediaFinal}"); } }
<h2>Intersection of Two Arrays</h2> <p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <i>an array of their intersection</i>. Each element in the result must be <b>unique</b> and you may return the result in <b>any order</b>.</p> <h3>Example 1:</h3> <p><b>Input:</b> <code>nums1 = [1, 2, 2, 1], nums2 = [2, 2]</code></p> <p><b>Output:</b> <code>[2]</code></p> <h3>Example 2:</h3> <p><b>Input:</b> <code>nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]</code></p> <p><b>Output:</b> <code>[9, 4]</code></p> <p><b>Explanation:</b> <code>[4, 9]</code> is also accepted.</p> <h3>Constraints:</h3> <ul> <li><code>1 <= nums1.length, nums2.length <= 1000</code></li> <li><code>0 <= nums1[i], nums2[i] <= 1000</code></li> </ul>
import asyncHandler from 'express-async-handler'; import Permission from '../model/permissionModel.js'; // Permission create controller export const createPermission = asyncHandler(async (req, res) => { const { name } = req.body; const findPermission = await Permission.findOne({ name }); if (findPermission) { return res.status(400).json({ message: 'Permission already exists' }); } const permission = await Permission.create({ ...req.body }); res .status(201) .json({ message: 'Permission created successfully', permission }); }); // Get all permissions controller export const getAllPermissions = asyncHandler(async (req, res) => { // find all permissions and reverse the array to get the latest permission first const permission = await Permission.find({}).sort({ createdAt: -1 }); res.status(200).json(permission); }); // Get permission by id controller export const getPermissionById = asyncHandler(async (req, res) => { const id = req.params.id; const permission = await Permission.findById(id); if (!permission) { res.status(404); throw new Error('Permission not found'); } res.status(200).json({ permission }); }); // Delete permission by id controller export const deletePermissionById = asyncHandler(async (req, res) => { const id = req.params.id; const permission = await Permission.findByIdAndDelete(id); if (!permission) { res.status(404); throw new Error('Permission not found'); } res .status(200) .json({ message: 'Permission deleted successfully', permission }); }); // Update permission by id controller export const updatePermissionById = asyncHandler(async (req, res) => { const id = req.params.id; const { name } = req.body; const permission = await Permission.findByIdAndUpdate(id, req.body, { new: true, }); if (!permission) { res.status(404); throw new Error('Permission not found'); } if (name) { permission.slug = permission.makeSlug(); await permission.save(); } res .status(200) .json({ message: 'Permission updated successfully', permission }); });
import React from 'react' import {makeStyles} from '@material-ui/core/styles' import InputAdornment from '@material-ui/core/InputAdornment' import IconButton from '@material-ui/core/IconButton' import SendIcon from '@material-ui/icons/Send' import TextField from '@material-ui/core/TextField' import {stdCornerRadius} from '../style/common_style' const useStyles = makeStyles({ input: { borderRadius: stdCornerRadius, borderTopLeftRadius: 0, borderTopRightRadius: 0, backgroundColor: "#fff", width: "100%", alignSelf: 'center', maxWidth: "450px", '&:hover': { borderWidth: 0 } }, inputNonClickable: { pointerEvents: 'none', }, fieldInput: { height: '36px', borderRadius: stdCornerRadius, paddingRight: stdCornerRadius, }, notchedOutline: { borderWidth: '0px', borderColor: 'white !important' }, }) export type TypingBarProps = { typedMessage: string, onChangeTypedMessage: (message: string) => void, onSendMessage: () => void isDemoMode: boolean } export function TypingBar({typedMessage, onChangeTypedMessage, onSendMessage, isDemoMode}: TypingBarProps): JSX.Element { const classes = useStyles() // necessary to prevent to loose focus when user click send button on mobile const handleMouseDownSend = (event: any) => { event.preventDefault(); }; const sendMessage = (event: any) => { onSendMessage() event.preventDefault(); }; return ( <TextField variant="outlined" autoFocus={!isDemoMode} autoComplete="off" className={`${classes.input} ${isDemoMode ? classes.inputNonClickable : ''}`} id="outlined-basic" placeholder="Type your sentence" value={typedMessage} onChange={(event: any) => onChangeTypedMessage(event.target.value)} onKeyPress={(event: any) => { if (event.key === 'Enter') { sendMessage(event) } }} InputLabelProps={{ shrink: true }} InputProps={{ classes: { notchedOutline: classes.notchedOutline, }, className: classes.fieldInput, endAdornment: <InputAdornment position="end"> <IconButton disabled={isDemoMode} aria-label="Enter" onClick={sendMessage} onMouseDown={handleMouseDownSend} > <SendIcon /> </IconButton> </InputAdornment>, }} > </TextField> ) }
package com.example.myapplication2 import android.graphics.Paint import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.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.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp // データクラス data class AppUsageData( val packageName: String, val totalTimeInForeground: Long ) data class DailyStatistics( val date: String, val apps: List<AppUsageData> ) @Composable fun AppUsageTable(appUsageData: List<AppUsageData>) { val maxTime = appUsageData.maxOfOrNull { it.totalTimeInForeground } ?: 1L Column( modifier = Modifier .padding(16.dp) .fillMaxSize() ) { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { Text(text = "アプリ名", modifier = Modifier.weight(1f)) Text(text = "使用時間 (ms)", modifier = Modifier.weight(1f)) } LazyColumn { items(appUsageData) { data -> Row( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { Text( text = data.packageName, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis ) BarChart( value = data.totalTimeInForeground, maxValue = maxTime, modifier = Modifier .weight(1f) .height(24.dp) ) } } } } } @Composable fun BarChart(value: Long, maxValue: Long, modifier: Modifier = Modifier) { Box(modifier = modifier) { Canvas(modifier = Modifier.fillMaxSize()) { drawIntoCanvas { canvas -> val barWidth = size.width * (value.toFloat() / maxValue.toFloat()) val paint = Paint().apply { color = Color.Blue.toArgb() } // 右側に30%の空白を追加 val widthWithPadding = barWidth * 0.7f canvas.nativeCanvas.drawRect(0f, 0f, widthWithPadding, size.height, paint) } } Text( text = value.toString(), fontSize = 10.sp, modifier = Modifier .align(Alignment.BottomEnd) .padding(end = 4.dp, bottom = 4.dp) ) } }
import type { GetStaticProps, NextPage } from "next"; import Layout from "../../components/layout"; import useTranslation from "next-translate/useTranslation"; import type { PrivacyPolicy as PrivacyPolicyType } from "../../types/privacyPolicy"; import PrivacyPolicyPages from "../../data/privacyPolicy"; import Link from "next/link"; type PrivacyPolicyProps = { pages: PrivacyPolicyType[]; }; const PrivacyPolicy: NextPage<PrivacyPolicyProps> = ({ pages }) => { const { t } = useTranslation("privacy-policy"); return ( <Layout> <h1>{t("title")}</h1> <ul className="collection"> {pages.map((page) => ( <li className="collection-item" key={page.route}> <Link href={`/privacy-policy/${page.route}`}>{page.title}</Link> </li> ))} </ul> </Layout> ); }; export const getStaticProps: GetStaticProps<PrivacyPolicyProps> = async ({ locale, }) => { return { props: { pages: PrivacyPolicyPages, }, }; }; export default PrivacyPolicy;
import java.util.InputMismatchException; import java.util.Scanner; public class Triangle { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a, b, c; System.out.println("Введите длину стороны a:"); a = scanner.nextInt(); System.out.println("Введите длину стороны b:"); b = scanner.nextInt(); System.out.println("Введите длину стороны c:"); c = scanner.nextInt(); if (isInvalidInput(a, b, c)) { System.out.println("Введенные значения находятся за пределами допустимого диапазона от 1 до 1000000000"); } else { try { String triangleType = classifyTriangle(a, b, c); System.out.println(triangleType); } catch (InputMismatchException e) { System.out.println("Введено некорректное значение. Пожалуйста, введите целое число!"); } } scanner.close(); } public static boolean isInvalidInput(int a, int b, int c) { return a <= 0 || b <= 0 || c <= 0 || a > 1000000000 || b > 1000000000 || c > 1000000000; } public static String classifyTriangle(int a, int b, int c) { if (isTriangle(a, b, c)) { if (isEquilateral(a, b, c)) { return "Треугольник равносторонний!"; } else if (isIsosceles(a, b, c)) { return "Треугольник равнобедренный!"; } else { return "Треугольник неравносторонний"; } } else { return "Не треугольник. Сумма длин двух сторон должна быть больше, чем длина третьей стороны"; } } public static boolean isTriangle(int a, int b, int c) { return a + b > c && b + c > a && c + a > b; } public static boolean isEquilateral(int a, int b, int c) { return a == b && b == c; } public static boolean isIsosceles(int a, int b, int c) { return a == b || b == c || c == a; } }
import { memo, useCallback, useMemo } from "react"; import { Button, Card } from "react-bootstrap"; const Comment = (props) => { console.log("I have rendered!") const createdDt = useMemo(() => new Date(props.created), [props.created]); return <Card style={{margin: "0.5rem"}}> <p>{props.comment}</p> <p>Posted on {createdDt.toLocaleDateString()} at {createdDt.toLocaleTimeString()} by {props.author}</p> { props.isLoggedIn ? <Button onClick={() => props.handleCopyComment(props.comment)} variant="secondary">Copy Comment</Button> : <></> } </Card> } export default memo(Comment);
<doc> <head> <title>Grammatica Reference Manual</title> </head> <body> <h1>Handling Ambiguities</h1> <p>Grammar ambiguities are points in the grammar where multiple alternatives conflict. As the parser is deterministic, a single alternative must be chosen and grammar ambiguities are therefore not allowed.</p> <p>By looking several tokens ahead, a parser is able to resolve some grammar ambiguities. The LL parser in Grammatica supports looking many tokens ahead. See the figure below for a simple example that can be resolved by looking more than one token ahead.</p> <figure> <caption>A simple grammar ambiguity. This ambiguity cause problems for parsers with a single look-ahead token, but Grammatica can handle it by resorting to two look-ahead tokens.</caption> <content> <pre>Prod = "a" "b" | "a" "c" ;</pre> </content> </figure> <p>Unfortunately, most ambiguities are not as easy to resolve automatically as the one in the figure above. An infinite number of look-ahead tokens may for example not be enough if the collision can itself consist of an infinite number of tokens. In these cases, the grammar must be rewritten to remove the ambiguity. In the figure below one such ambiguity and a resolution is shown.</p> <figure> <caption>An unresolvable grammar ambiguity and a refactored production. As the number of conflicting tokens is potentially infinite, this ambiguity cannot be resolved by the use of a look-ahead parser. Instead the production must be split into two, as illustrated by <code>NewProd</code> and <code>ProdTail</code>.</caption> <content> <pre>OldProd = "a"* "b" | "a"* "c" ; NewProd = "a"* ProdTail ; ProdTail = "b" | "c" ;</pre> </content> </figure> <p>Unresolvable ambiguities can also occur due to loops in the grammar, causing some token sequence to possibly be repeated infinitely. Some ambiguities are also caused by an optional reference conflicting with the next reference inside a production alternative. All these types of ambiguities are detected by Grammatica and reported to the user.</p> </body> </doc>
package requesters; import Organization.OrganizationType; import exceptions.WrongArgumentInRequestInScriptException; import utility.ScriptChecker; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.Scanner; /** * Позволяет запрашивать у пользователя (читать из файла скрипта) тип организации. */ public class TypeRequester { private Scanner scanner; private boolean trueNull=false; public TypeRequester(Scanner scanner) { this.scanner = scanner; } /** * Запрашивает у пользователя тип организации посредством метода typeRequest, пока не будет введено валидное значение. * @return Введенный тип организации. * @throws WrongArgumentInRequestInScriptException Если прочитанный тип из файла скрипта оказался невалидным. */ public OrganizationType getType() throws WrongArgumentInRequestInScriptException { while(true) { try { OrganizationType type = typeRequest(); if (type == null) { if (trueNull) { return null; } } else return type; } catch (NoSuchElementException e) { System.out.println("Неверный ввод, введите один из типов организации, перечисленных выше."); scanner = new Scanner(System.in); } } } /** * Запрашивает у пользователя (читает из файла скрипта) тип организации и валидирует его. * @return Введенный тип организации. * @throws NoSuchElementException Если при попытке ввода был обнаружен EOF. * @throws WrongArgumentInRequestInScriptException Если прочитанное значение из файла скрипта оказалось невалидным. */ private OrganizationType typeRequest() throws NoSuchElementException, WrongArgumentInRequestInScriptException { try { if (!ScriptChecker.isScriptInProcess) { System.out.print("Введите тип организации: COMMERCIAL, PUBLIC, PRIVATE_LIMITED_COMPANY," + " OPEN_JOINT_STOCK_COMPANY: "); scanner = new Scanner(System.in); } String value = scanner.nextLine().strip(); if (value.isEmpty()) { trueNull=true; return null; } OrganizationType type = OrganizationType.valueOf(value); return type; } catch (IllegalArgumentException e) { if (ScriptChecker.isScriptInProcess) throw new WrongArgumentInRequestInScriptException("Поле type содержит несуществующее значение."); else { System.out.println("Такого типа организации не существует."); return null; } } } }
/* * Copyright (C) 2023 Hong Qiaowei <hongqiaowei@163.com>. All rights reserved. * * This program 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. * * This program 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 this program. If not, see <https://www.gnu.org/licenses/>. */ package org.example.web.websocket.server; import org.eclipse.jetty.websocket.api.WebSocketBehavior; import org.eclipse.jetty.websocket.api.WebSocketPolicy; import org.eclipse.jetty.websocket.server.WebSocketServerFactory; import org.example.util.Const; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.lang.NonNull; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.ServletWebSocketHandlerRegistry; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import org.springframework.web.socket.server.jetty.JettyRequestUpgradeStrategy; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; import org.springframework.web.util.UrlPathHelper; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; /** * @author Hong Qiaowei */ @Configuration @EnableWebSocket public class SpringWebSocketServerConfig implements WebSocketConfigurer { @Bean public DefaultHandshakeHandler defaultHandshakeHandler(ServletContext servletContext) { WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER); // jetty websocket server的配置 // policy.setInputBufferSize(8192); // policy.setIdleTimeout (600_000); WebSocketServerFactory webSocketServerFactory = new WebSocketServerFactory (servletContext, policy); JettyRequestUpgradeStrategy requestUpgradeStrategy = new JettyRequestUpgradeStrategy(webSocketServerFactory); return new DefaultHandshakeHandler(requestUpgradeStrategy); } @Bean public WebSocketServerHandler webSocketServerHandler() { return new WebSocketServerHandler(); } @Bean public WebSocketServerHandshakeInterceptor webSocketServerHandshakeInterceptor() { return new WebSocketServerHandshakeInterceptor(); } @Override public void registerWebSocketHandlers(@NonNull WebSocketHandlerRegistry registry) { // 支持通过/websocket前缀建立websocket连接 if (registry instanceof ServletWebSocketHandlerRegistry) { ((ServletWebSocketHandlerRegistry) registry).setUrlPathHelper( new UrlPathHelper() { @Override public @NonNull String resolveAndCacheLookupPath(@NonNull HttpServletRequest request) { String prefix = "/websocket"; String path = super.resolveAndCacheLookupPath(request); if (path.startsWith(prefix)) { return prefix + "/**"; } return path; } } ); } registry.addHandler (webSocketServerHandler(), "/websocket/**") .addInterceptors (webSocketServerHandshakeInterceptor()) .setAllowedOrigins(Const.S.ASTERISK_STR); } }
package vip.sunke.mybatis; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.Version; import java.io.*; import java.util.Locale; import java.util.Map; /** * @author sunke * @Date 2019-04-29 14:07 * @description */ public class FreeMarkerUtil { private static FreeMarkerUtil fk; private static Configuration cfg; private FreeMarkerUtil() { } public static FreeMarkerUtil getInstance(String freemarkerVersionNo, String templatePath) { if (null == fk) { cfg = new Configuration(new Version(freemarkerVersionNo)); cfg.setClassForTemplateLoading(FreeMarkerUtil.class, templatePath); // cfg.setTemplateLoader(new ClassTemplateLoader(FreeMarkerUtil.class, templatePath)); fk = new FreeMarkerUtil(); } return fk; } /** * @param ftlName 模块名称 * @param root 数据 * @param outFile 输出文件 * @param filePath 输出目录 * @param ftlPath 模块目录 * @throws Exception */ public void printFile(String ftlName, Map<String, Object> root, String outFile, String filePath, String ftlPath) throws Exception { try { File file = new File(filePath + File.separator + outFile); if (!file.getParentFile().exists()) { //判断有没有父路径,就是判断文件整个路径是否存在 file.getParentFile().mkdirs(); //不存在就全部创建 } if (file.exists()) { file.delete(); } Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); Template template = getTemplate(ftlName, ftlPath); template.process(root, out); //模版输出 out.flush(); out.close(); } catch (TemplateException e) { } catch (IOException e) { } finally { } } public Template getTemplate(String ftlName, String ftlPath) throws Exception { try { //通过Freemaker的Configuration读取相应的ftl cfg.setEncoding(Locale.CHINA, "utf-8"); cfg.setDirectoryForTemplateLoading(new File(ftlPath)); //设定去哪里读取相应的ftl模板文件 Template temp = cfg.getTemplate(ftlName); //在模板文件目录中找到名称为name的文件 return temp; } catch (IOException e) { try { cfg.setClassForTemplateLoading(this.getClass(), ftlPath); // cfg.setTemplateLoader(new ClassTemplateLoader(this.getClass(), ftlPath)); Template temp = cfg.getTemplate(ftlName); return temp; } catch (IOException ex) { ex.printStackTrace(); } } return null; } public void print(String ftlName, Map<String, Object> root, String ftlPath, OutputStream outputStream) throws Exception { try { Template temp = getTemplate(ftlName, ftlPath); //通过Template可以将模板文件输出到相应的流 temp.process(root, new PrintWriter(outputStream)); } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void print(String ftlName, Map<String, Object> root, String ftlPath) throws Exception { print(ftlName, root, ftlPath, System.out); } /** * @param fltFile * @param templatePath * @param dataMap * @return */ public String geneFileStr(String fltFile, String templatePath, Map<String, Object> dataMap) { try { Template template = cfg.getTemplate(fltFile, "utf-8"); StringWriter out = new StringWriter(); template.process(dataMap, out); out.flush(); out.close(); return out.getBuffer().toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }
const express = require("express"); const axios = require("axios"); require("dotenv").config(); const app = express(); const port = process.env.PORT || 3000; app.get("/", (req, res) => { let dataToPost = []; const url = `${process.env.MAIN_URL}`; const method = "GET"; // or 'POST', 'PUT', 'DELETE', etc. const headers = { Authorization: `${process.env.BEARER_TOKEN}`, "Content-Type": "application/json", // adjust content type if necessary }; axios({ method, url, headers, }) .then(response => { const promises = response.data["result"]["content"].map(item => { const id = item["id"]; const event = item["name"]; const uri = item["eventURI"] const newUrl = `${process.env.SUB_URL_1}${id}${process.env.SUB_URL_2}`; const yepUrl = `https://www.yepdesk.com/${uri}` return axios({ method, url: newUrl, headers, }).then(newResponse => { const eventData = newResponse.data["result"]; const completed = eventData ? eventData["COMPLETED"] ?? 0 : 0; const total = eventData ? eventData["total"] ?? 0 : 0; const accepted = eventData ? eventData["ACCEPTED"] ?? 0 : 0; const submitted = eventData ? eventData["SUBMITTED"] ?? 0 : 0; const verified = eventData ? eventData["VERIFIED"] ?? 0 : 0; dataToPost.push([ event, yepUrl, completed, total, accepted, submitted, verified, ]); }); }); Promise.all(promises).then(() => { const tableRows = dataToPost.map(row => { return `<tr> <td style="padding: 8px; border: 1px solid #ddd;">${row[0]}</td> <td style="padding: 8px; border: 1px solid #ddd;">${row[1]}</td> <td style="padding: 8px; border: 1px solid #ddd;">${row[2]}</td> <td style="padding: 8px; border: 1px solid #ddd;">${row[3]}</td> <td style="padding: 8px; border: 1px solid #ddd;">${row[4]}</td> <td style="padding: 8px; border: 1px solid #ddd;">${row[5]}</td> <td style="padding: 8px; border: 1px solid #ddd;">${row[5]}</td> </tr>`; }); const table = `<table style="border-collapse: collapse; width: 100%;"> <thead> <tr style="background-color: #f2f2f2;"> <th style="padding: 8px; border: 1px solid #ddd;">Event</th> <th style="padding: 8px; border: 1px solid #ddd;">Yep desk URL</th> <th style="padding: 8px; border: 1px solid #ddd;">Completed</th> <th style="padding: 8px; border: 1px solid #ddd;">Total</th> <th style="padding: 8px; border: 1px solid #ddd;">Accepted</th> <th style="padding: 8px; border: 1px solid #ddd;">Submitted</th> <th style="padding: 8px; border: 1px solid #ddd;">Verified</th> </tr> </thead> <tbody>${tableRows.join("")}</tbody> </table>`; res.send(table); }); }) .catch(error => { console.error("Error:", error); res.status(500).send("An error occurred while fetching data."); }); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
import { useContext } from 'react'; import axios from 'axios'; import { useQuery } from '@tanstack/react-query'; import { useParams } from 'react-router-dom'; import { lang } from '../../dictionary'; import { Context } from '../../AppContext'; import Card from '../Cards/Card'; import CardLoader from '../CardLoader/CardLoader'; const ProductsList = () => { const { category } = useParams(); const { language } = useContext(Context); const { isLoading, error, data } = useQuery( ['fetchData', category], async () => await (await axios.get('http://localhost:5000/products')).data, { select: data => { if (category) return data.filter(item => item.tag === category); return data; } } ); return ( <div className="flex flex-col gap-8"> <h1 className="text-3xl capitalize"> {lang(language, category || 'allProducts')} </h1> <div className="grid grid-cols-1 gap-x-14 gap-y-9 sm:grid-cols-2 lg:grid-cols-3"> {isLoading && [...Array(6)].map((item, index) => <CardLoader key={index} />)} {!isLoading && !error && data.map(item => <Card key={item.id} item={item} />)} {!isLoading && error && <h1>Произошла ошибка при загрузке товаров.</h1>} </div> </div> ); }; export default ProductsList;
/* * I2C Link Layer for Samsung S3FWRN5 NCI based Driver * * Copyright (C) 2015 Samsung Electrnoics * Robert Baldyga <r.baldyga@samsung.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2 or later, as published by the Free Software Foundation. * * This program 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 this program; if not, see <http://www.gnu.org/licenses/>. */ #include <linux/i2c.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/of_gpio.h> #include <linux/of_irq.h> #include <linux/module.h> #include <net/nfc/nfc.h> #include "s3fwrn5.h" #define S3FWRN5_I2C_DRIVER_NAME "s3fwrn5_i2c" #define S3FWRN5_I2C_MAX_PAYLOAD 32 #define S3FWRN5_EN_WAIT_TIME 150 struct s3fwrn5_i2c_phy { struct i2c_client *i2c_dev; struct nci_dev *ndev; unsigned int gpio_en; unsigned int gpio_fw_wake; struct mutex mutex; enum s3fwrn5_mode mode; unsigned int irq_skip:1; }; static void s3fwrn5_i2c_set_wake(void *phy_id, bool wake) { struct s3fwrn5_i2c_phy *phy = phy_id; mutex_lock(&phy->mutex); gpio_set_value(phy->gpio_fw_wake, wake); msleep(S3FWRN5_EN_WAIT_TIME/2); mutex_unlock(&phy->mutex); } static void s3fwrn5_i2c_set_mode(void *phy_id, enum s3fwrn5_mode mode) { struct s3fwrn5_i2c_phy *phy = phy_id; mutex_lock(&phy->mutex); if (phy->mode == mode) goto out; phy->mode = mode; gpio_set_value(phy->gpio_en, 1); gpio_set_value(phy->gpio_fw_wake, 0); if (mode == S3FWRN5_MODE_FW) gpio_set_value(phy->gpio_fw_wake, 1); if (mode != S3FWRN5_MODE_COLD) { msleep(S3FWRN5_EN_WAIT_TIME); gpio_set_value(phy->gpio_en, 0); msleep(S3FWRN5_EN_WAIT_TIME/2); } phy->irq_skip = true; out: mutex_unlock(&phy->mutex); } static enum s3fwrn5_mode s3fwrn5_i2c_get_mode(void *phy_id) { struct s3fwrn5_i2c_phy *phy = phy_id; enum s3fwrn5_mode mode; mutex_lock(&phy->mutex); mode = phy->mode; mutex_unlock(&phy->mutex); return mode; } static int s3fwrn5_i2c_write(void *phy_id, struct sk_buff *skb) { struct s3fwrn5_i2c_phy *phy = phy_id; int ret; mutex_lock(&phy->mutex); phy->irq_skip = false; ret = i2c_master_send(phy->i2c_dev, skb->data, skb->len); if (ret == -EREMOTEIO) { /* Retry, chip was in standby */ usleep_range(110000, 120000); ret = i2c_master_send(phy->i2c_dev, skb->data, skb->len); } mutex_unlock(&phy->mutex); if (ret < 0) return ret; if (ret != skb->len) return -EREMOTEIO; return 0; } static const struct s3fwrn5_phy_ops i2c_phy_ops = { .set_wake = s3fwrn5_i2c_set_wake, .set_mode = s3fwrn5_i2c_set_mode, .get_mode = s3fwrn5_i2c_get_mode, .write = s3fwrn5_i2c_write, }; static int s3fwrn5_i2c_read(struct s3fwrn5_i2c_phy *phy) { struct sk_buff *skb; size_t hdr_size; size_t data_len; char hdr[4]; int ret; hdr_size = (phy->mode == S3FWRN5_MODE_NCI) ? NCI_CTRL_HDR_SIZE : S3FWRN5_FW_HDR_SIZE; ret = i2c_master_recv(phy->i2c_dev, hdr, hdr_size); if (ret < 0) return ret; if (ret < hdr_size) return -EBADMSG; data_len = (phy->mode == S3FWRN5_MODE_NCI) ? ((struct nci_ctrl_hdr *)hdr)->plen : ((struct s3fwrn5_fw_header *)hdr)->len; skb = alloc_skb(hdr_size + data_len, GFP_KERNEL); if (!skb) return -ENOMEM; memcpy(skb_put(skb, hdr_size), hdr, hdr_size); if (data_len == 0) goto out; ret = i2c_master_recv(phy->i2c_dev, skb_put(skb, data_len), data_len); if (ret != data_len) { kfree_skb(skb); return -EBADMSG; } out: return s3fwrn5_recv_frame(phy->ndev, skb, phy->mode); } static irqreturn_t s3fwrn5_i2c_irq_thread_fn(int irq, void *phy_id) { struct s3fwrn5_i2c_phy *phy = phy_id; int ret = 0; if (!phy || !phy->ndev) { WARN_ON_ONCE(1); return IRQ_NONE; } mutex_lock(&phy->mutex); if (phy->irq_skip) goto out; switch (phy->mode) { case S3FWRN5_MODE_NCI: case S3FWRN5_MODE_FW: ret = s3fwrn5_i2c_read(phy); break; case S3FWRN5_MODE_COLD: ret = -EREMOTEIO; break; } out: mutex_unlock(&phy->mutex); return IRQ_HANDLED; } static int s3fwrn5_i2c_parse_dt(struct i2c_client *client) { struct s3fwrn5_i2c_phy *phy = i2c_get_clientdata(client); struct device_node *np = client->dev.of_node; if (!np) return -ENODEV; phy->gpio_en = of_get_named_gpio(np, "s3fwrn5,en-gpios", 0); if (!gpio_is_valid(phy->gpio_en)) return -ENODEV; phy->gpio_fw_wake = of_get_named_gpio(np, "s3fwrn5,fw-gpios", 0); if (!gpio_is_valid(phy->gpio_fw_wake)) return -ENODEV; return 0; } static int s3fwrn5_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct s3fwrn5_i2c_phy *phy; int ret; phy = devm_kzalloc(&client->dev, sizeof(*phy), GFP_KERNEL); if (!phy) return -ENOMEM; mutex_init(&phy->mutex); phy->mode = S3FWRN5_MODE_COLD; phy->irq_skip = true; phy->i2c_dev = client; i2c_set_clientdata(client, phy); ret = s3fwrn5_i2c_parse_dt(client); if (ret < 0) return ret; ret = devm_gpio_request_one(&phy->i2c_dev->dev, phy->gpio_en, GPIOF_OUT_INIT_HIGH, "s3fwrn5_en"); if (ret < 0) return ret; ret = devm_gpio_request_one(&phy->i2c_dev->dev, phy->gpio_fw_wake, GPIOF_OUT_INIT_LOW, "s3fwrn5_fw_wake"); if (ret < 0) return ret; ret = s3fwrn5_probe(&phy->ndev, phy, &phy->i2c_dev->dev, &i2c_phy_ops, S3FWRN5_I2C_MAX_PAYLOAD); if (ret < 0) return ret; ret = devm_request_threaded_irq(&client->dev, phy->i2c_dev->irq, NULL, s3fwrn5_i2c_irq_thread_fn, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, S3FWRN5_I2C_DRIVER_NAME, phy); if (ret) s3fwrn5_remove(phy->ndev); return ret; } static int s3fwrn5_i2c_remove(struct i2c_client *client) { struct s3fwrn5_i2c_phy *phy = i2c_get_clientdata(client); s3fwrn5_remove(phy->ndev); return 0; } static struct i2c_device_id s3fwrn5_i2c_id_table[] = { {S3FWRN5_I2C_DRIVER_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, s3fwrn5_i2c_id_table); static const struct of_device_id of_s3fwrn5_i2c_match[] = { { .compatible = "samsung,s3fwrn5-i2c", }, {} }; MODULE_DEVICE_TABLE(of, of_s3fwrn5_i2c_match); static struct i2c_driver s3fwrn5_i2c_driver = { .driver = { .owner = THIS_MODULE, .name = S3FWRN5_I2C_DRIVER_NAME, .of_match_table = of_match_ptr(of_s3fwrn5_i2c_match), }, .probe = s3fwrn5_i2c_probe, .remove = s3fwrn5_i2c_remove, .id_table = s3fwrn5_i2c_id_table, }; module_i2c_driver(s3fwrn5_i2c_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("I2C driver for Samsung S3FWRN5"); MODULE_AUTHOR("Robert Baldyga <r.baldyga@samsung.com>");
""" test with the TimeGrouper / grouping with datetimes """ from datetime import datetime from io import StringIO import numpy as np import pytest import pytz import pandas.util._test_decorators as td import pandas as pd from pandas import ( DataFrame, DatetimeIndex, Index, MultiIndex, Series, Timestamp, date_range, offsets, ) import pandas._testing as tm from pandas.core.groupby.grouper import Grouper from pandas.core.groupby.ops import BinGrouper @pytest.fixture def frame_for_truncated_bingrouper(): """ DataFrame used by groupby_with_truncated_bingrouper, made into a separate fixture for easier re-use in test_groupby_apply_timegrouper_with_nat_apply_squeeze """ df = DataFrame( { "Quantity": [18, 3, 5, 1, 9, 3], "Date": [ Timestamp(2013, 9, 1, 13, 0), Timestamp(2013, 9, 1, 13, 5), Timestamp(2013, 10, 1, 20, 0), Timestamp(2013, 10, 3, 10, 0), pd.NaT, Timestamp(2013, 9, 2, 14, 0), ], } ) return df @pytest.fixture def groupby_with_truncated_bingrouper(frame_for_truncated_bingrouper): """ GroupBy object such that gb.grouper is a BinGrouper and len(gb.grouper.result_index) < len(gb.grouper.group_keys_seq) Aggregations on this groupby should have dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date") As either the index or an index level. """ df = frame_for_truncated_bingrouper tdg = Grouper(key="Date", freq="5D") gb = df.groupby(tdg) # check we're testing the case we're interested in assert len(gb.grouper.result_index) != len(gb.grouper.group_keys_seq) return gb class TestGroupBy: def test_groupby_with_timegrouper(self): # GH 4161 # TimeGrouper requires a sorted index # also verifies that the resultant index has the correct name df_original = DataFrame( { "Buyer": "Carl Carl Carl Carl Joe Carl".split(), "Quantity": [18, 3, 5, 1, 9, 3], "Date": [ datetime(2013, 9, 1, 13, 0), datetime(2013, 9, 1, 13, 5), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 3, 10, 0), datetime(2013, 12, 2, 12, 0), datetime(2013, 9, 2, 14, 0), ], } ) # GH 6908 change target column's order df_reordered = df_original.sort_values(by="Quantity") for df in [df_original, df_reordered]: df = df.set_index(["Date"]) expected = DataFrame( {"Quantity": 0}, index=date_range( "20130901", "20131205", freq="5D", name="Date", inclusive="left" ), ) expected.iloc[[0, 6, 18], 0] = np.array([24, 6, 9], dtype="int64") result1 = df.resample("5D").sum() tm.assert_frame_equal(result1, expected) df_sorted = df.sort_index() result2 = df_sorted.groupby(Grouper(freq="5D")).sum() tm.assert_frame_equal(result2, expected) result3 = df.groupby(Grouper(freq="5D")).sum() tm.assert_frame_equal(result3, expected) @pytest.mark.parametrize("should_sort", [True, False]) def test_groupby_with_timegrouper_methods(self, should_sort): # GH 3881 # make sure API of timegrouper conforms df = DataFrame( { "Branch": "A A A A A B".split(), "Buyer": "Carl Mark Carl Joe Joe Carl".split(), "Quantity": [1, 3, 5, 8, 9, 3], "Date": [ datetime(2013, 1, 1, 13, 0), datetime(2013, 1, 1, 13, 5), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 2, 10, 0), datetime(2013, 12, 2, 12, 0), datetime(2013, 12, 2, 14, 0), ], } ) if should_sort: df = df.sort_values(by="Quantity", ascending=False) df = df.set_index("Date", drop=False) g = df.groupby(Grouper(freq="6M")) assert g.group_keys assert isinstance(g.grouper, BinGrouper) groups = g.groups assert isinstance(groups, dict) assert len(groups) == 3 def test_timegrouper_with_reg_groups(self): # GH 3794 # allow combination of timegrouper/reg groups df_original = DataFrame( { "Branch": "A A A A A A A B".split(), "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(), "Quantity": [1, 3, 5, 1, 8, 1, 9, 3], "Date": [ datetime(2013, 1, 1, 13, 0), datetime(2013, 1, 1, 13, 5), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 2, 10, 0), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 2, 10, 0), datetime(2013, 12, 2, 12, 0), datetime(2013, 12, 2, 14, 0), ], } ).set_index("Date") df_sorted = df_original.sort_values(by="Quantity", ascending=False) for df in [df_original, df_sorted]: expected = DataFrame( { "Buyer": "Carl Joe Mark".split(), "Quantity": [10, 18, 3], "Date": [ datetime(2013, 12, 31, 0, 0), datetime(2013, 12, 31, 0, 0), datetime(2013, 12, 31, 0, 0), ], } ).set_index(["Date", "Buyer"]) result = df.groupby([Grouper(freq="A"), "Buyer"]).sum() tm.assert_frame_equal(result, expected) expected = DataFrame( { "Buyer": "Carl Mark Carl Joe".split(), "Quantity": [1, 3, 9, 18], "Date": [ datetime(2013, 1, 1, 0, 0), datetime(2013, 1, 1, 0, 0), datetime(2013, 7, 1, 0, 0), datetime(2013, 7, 1, 0, 0), ], } ).set_index(["Date", "Buyer"]) result = df.groupby([Grouper(freq="6MS"), "Buyer"]).sum() tm.assert_frame_equal(result, expected) df_original = DataFrame( { "Branch": "A A A A A A A B".split(), "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(), "Quantity": [1, 3, 5, 1, 8, 1, 9, 3], "Date": [ datetime(2013, 10, 1, 13, 0), datetime(2013, 10, 1, 13, 5), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 2, 10, 0), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 2, 10, 0), datetime(2013, 10, 2, 12, 0), datetime(2013, 10, 2, 14, 0), ], } ).set_index("Date") df_sorted = df_original.sort_values(by="Quantity", ascending=False) for df in [df_original, df_sorted]: expected = DataFrame( { "Buyer": "Carl Joe Mark Carl Joe".split(), "Quantity": [6, 8, 3, 4, 10], "Date": [ datetime(2013, 10, 1, 0, 0), datetime(2013, 10, 1, 0, 0), datetime(2013, 10, 1, 0, 0), datetime(2013, 10, 2, 0, 0), datetime(2013, 10, 2, 0, 0), ], } ).set_index(["Date", "Buyer"]) result = df.groupby([Grouper(freq="1D"), "Buyer"]).sum() tm.assert_frame_equal(result, expected) result = df.groupby([Grouper(freq="1M"), "Buyer"]).sum() expected = DataFrame( { "Buyer": "Carl Joe Mark".split(), "Quantity": [10, 18, 3], "Date": [ datetime(2013, 10, 31, 0, 0), datetime(2013, 10, 31, 0, 0), datetime(2013, 10, 31, 0, 0), ], } ).set_index(["Date", "Buyer"]) tm.assert_frame_equal(result, expected) # passing the name df = df.reset_index() result = df.groupby([Grouper(freq="1M", key="Date"), "Buyer"]).sum() tm.assert_frame_equal(result, expected) with pytest.raises(KeyError, match="'The grouper name foo is not found'"): df.groupby([Grouper(freq="1M", key="foo"), "Buyer"]).sum() # passing the level df = df.set_index("Date") result = df.groupby([Grouper(freq="1M", level="Date"), "Buyer"]).sum() tm.assert_frame_equal(result, expected) result = df.groupby([Grouper(freq="1M", level=0), "Buyer"]).sum() tm.assert_frame_equal(result, expected) with pytest.raises(ValueError, match="The level foo is not valid"): df.groupby([Grouper(freq="1M", level="foo"), "Buyer"]).sum() # multi names df = df.copy() df["Date"] = df.index + offsets.MonthEnd(2) result = df.groupby([Grouper(freq="1M", key="Date"), "Buyer"]).sum() expected = DataFrame( { "Buyer": "Carl Joe Mark".split(), "Quantity": [10, 18, 3], "Date": [ datetime(2013, 11, 30, 0, 0), datetime(2013, 11, 30, 0, 0), datetime(2013, 11, 30, 0, 0), ], } ).set_index(["Date", "Buyer"]) tm.assert_frame_equal(result, expected) # error as we have both a level and a name! msg = "The Grouper cannot specify both a key and a level!" with pytest.raises(ValueError, match=msg): df.groupby( [Grouper(freq="1M", key="Date", level="Date"), "Buyer"] ).sum() # single groupers expected = DataFrame( [[31]], columns=["Quantity"], index=DatetimeIndex( [datetime(2013, 10, 31, 0, 0)], freq=offsets.MonthEnd(), name="Date" ), ) result = df.groupby(Grouper(freq="1M")).sum() tm.assert_frame_equal(result, expected) result = df.groupby([Grouper(freq="1M")]).sum() tm.assert_frame_equal(result, expected) expected.index = expected.index.shift(1) assert expected.index.freq == offsets.MonthEnd() result = df.groupby(Grouper(freq="1M", key="Date")).sum() tm.assert_frame_equal(result, expected) result = df.groupby([Grouper(freq="1M", key="Date")]).sum() tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("freq", ["D", "M", "A", "Q-APR"]) def test_timegrouper_with_reg_groups_freq(self, freq): # GH 6764 multiple grouping with/without sort df = DataFrame( { "date": pd.to_datetime( [ "20121002", "20121007", "20130130", "20130202", "20130305", "20121002", "20121207", "20130130", "20130202", "20130305", "20130202", "20130305", ] ), "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], "whole_cost": [ 1790, 364, 280, 259, 201, 623, 90, 312, 359, 301, 359, 801, ], "cost1": [12, 15, 10, 24, 39, 1, 0, 90, 45, 34, 1, 12], } ).set_index("date") expected = ( df.groupby("user_id")["whole_cost"] .resample(freq) .sum(min_count=1) # XXX .dropna() .reorder_levels(["date", "user_id"]) .sort_index() .astype("int64") ) expected.name = "whole_cost" result1 = ( df.sort_index().groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum() ) tm.assert_series_equal(result1, expected) result2 = df.groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum() tm.assert_series_equal(result2, expected) def test_timegrouper_get_group(self): # GH 6914 df_original = DataFrame( { "Buyer": "Carl Joe Joe Carl Joe Carl".split(), "Quantity": [18, 3, 5, 1, 9, 3], "Date": [ datetime(2013, 9, 1, 13, 0), datetime(2013, 9, 1, 13, 5), datetime(2013, 10, 1, 20, 0), datetime(2013, 10, 3, 10, 0), datetime(2013, 12, 2, 12, 0), datetime(2013, 9, 2, 14, 0), ], } ) df_reordered = df_original.sort_values(by="Quantity") # single grouping expected_list = [ df_original.iloc[[0, 1, 5]], df_original.iloc[[2, 3]], df_original.iloc[[4]], ] dt_list = ["2013-09-30", "2013-10-31", "2013-12-31"] for df in [df_original, df_reordered]: grouped = df.groupby(Grouper(freq="M", key="Date")) for t, expected in zip(dt_list, expected_list): dt = Timestamp(t) result = grouped.get_group(dt) tm.assert_frame_equal(result, expected) # multiple grouping expected_list = [ df_original.iloc[[1]], df_original.iloc[[3]], df_original.iloc[[4]], ] g_list = [("Joe", "2013-09-30"), ("Carl", "2013-10-31"), ("Joe", "2013-12-31")] for df in [df_original, df_reordered]: grouped = df.groupby(["Buyer", Grouper(freq="M", key="Date")]) for (b, t), expected in zip(g_list, expected_list): dt = Timestamp(t) result = grouped.get_group((b, dt)) tm.assert_frame_equal(result, expected) # with index df_original = df_original.set_index("Date") df_reordered = df_original.sort_values(by="Quantity") expected_list = [ df_original.iloc[[0, 1, 5]], df_original.iloc[[2, 3]], df_original.iloc[[4]], ] for df in [df_original, df_reordered]: grouped = df.groupby(Grouper(freq="M")) for t, expected in zip(dt_list, expected_list): dt = Timestamp(t) result = grouped.get_group(dt) tm.assert_frame_equal(result, expected) def test_timegrouper_apply_return_type_series(self): # Using `apply` with the `TimeGrouper` should give the # same return type as an `apply` with a `Grouper`. # Issue #11742 df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]}) df_dt = df.copy() df_dt["date"] = pd.to_datetime(df_dt["date"]) def sumfunc_series(x): return Series([x["value"].sum()], ("sum",)) expected = df.groupby(Grouper(key="date")).apply(sumfunc_series) result = df_dt.groupby(Grouper(freq="M", key="date")).apply(sumfunc_series) tm.assert_frame_equal( result.reset_index(drop=True), expected.reset_index(drop=True) ) def test_timegrouper_apply_return_type_value(self): # Using `apply` with the `TimeGrouper` should give the # same return type as an `apply` with a `Grouper`. # Issue #11742 df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]}) df_dt = df.copy() df_dt["date"] = pd.to_datetime(df_dt["date"]) def sumfunc_value(x): return x.value.sum() expected = df.groupby(Grouper(key="date")).apply(sumfunc_value) result = df_dt.groupby(Grouper(freq="M", key="date")).apply(sumfunc_value) tm.assert_series_equal( result.reset_index(drop=True), expected.reset_index(drop=True) ) def test_groupby_groups_datetimeindex(self): # GH#1430 periods = 1000 ind = date_range(start="2012/1/1", freq="5min", periods=periods) df = DataFrame( {"high": np.arange(periods), "low": np.arange(periods)}, index=ind ) grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day)) # it works! groups = grouped.groups assert isinstance(list(groups.keys())[0], datetime) # GH#11442 index = date_range("2015/01/01", periods=5, name="date") df = DataFrame({"A": [5, 6, 7, 8, 9], "B": [1, 2, 3, 4, 5]}, index=index) result = df.groupby(level="date").groups dates = ["2015-01-05", "2015-01-04", "2015-01-03", "2015-01-02", "2015-01-01"] expected = { Timestamp(date): DatetimeIndex([date], name="date") for date in dates } tm.assert_dict_equal(result, expected) grouped = df.groupby(level="date") for date in dates: result = grouped.get_group(date) data = [[df.loc[date, "A"], df.loc[date, "B"]]] expected_index = DatetimeIndex([date], name="date", freq="D") expected = DataFrame(data, columns=list("AB"), index=expected_index) tm.assert_frame_equal(result, expected) def test_groupby_groups_datetimeindex_tz(self): # GH 3950 dates = [ "2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00", "2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00", ] df = DataFrame( { "label": ["a", "a", "a", "b", "b", "b"], "datetime": dates, "value1": np.arange(6, dtype="int64"), "value2": [1, 2] * 3, } ) df["datetime"] = df["datetime"].apply(lambda d: Timestamp(d, tz="US/Pacific")) exp_idx1 = DatetimeIndex( [ "2011-07-19 07:00:00", "2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00", "2011-07-19 09:00:00", ], tz="US/Pacific", name="datetime", ) exp_idx2 = Index(["a", "b"] * 3, name="label") exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) expected = DataFrame( {"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]}, index=exp_idx, columns=["value1", "value2"], ) result = df.groupby(["datetime", "label"]).sum() tm.assert_frame_equal(result, expected) # by level didx = DatetimeIndex(dates, tz="Asia/Tokyo") df = DataFrame( {"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]}, index=didx, ) exp_idx = DatetimeIndex( ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"], tz="Asia/Tokyo", ) expected = DataFrame( {"value1": [3, 5, 7], "value2": [2, 4, 6]}, index=exp_idx, columns=["value1", "value2"], ) result = df.groupby(level=0).sum() tm.assert_frame_equal(result, expected) def test_frame_datetime64_handling_groupby(self): # it works! df = DataFrame( [(3, np.datetime64("2012-07-03")), (3, np.datetime64("2012-07-04"))], columns=["a", "date"], ) result = df.groupby("a").first() assert result["date"][3] == Timestamp("2012-07-03") def test_groupby_multi_timezone(self): # combining multiple / different timezones yields UTC data = """0,2000-01-28 16:47:00,America/Chicago 1,2000-01-29 16:48:00,America/Chicago 2,2000-01-30 16:49:00,America/Los_Angeles 3,2000-01-31 16:50:00,America/Chicago 4,2000-01-01 16:50:00,America/New_York""" df = pd.read_csv(StringIO(data), header=None, names=["value", "date", "tz"]) result = df.groupby("tz").date.apply( lambda x: pd.to_datetime(x).dt.tz_localize(x.name) ) expected = Series( [ Timestamp("2000-01-28 16:47:00-0600", tz="America/Chicago"), Timestamp("2000-01-29 16:48:00-0600", tz="America/Chicago"), Timestamp("2000-01-30 16:49:00-0800", tz="America/Los_Angeles"), Timestamp("2000-01-31 16:50:00-0600", tz="America/Chicago"), Timestamp("2000-01-01 16:50:00-0500", tz="America/New_York"), ], name="date", dtype=object, ) tm.assert_series_equal(result, expected) tz = "America/Chicago" res_values = df.groupby("tz").date.get_group(tz) result = pd.to_datetime(res_values).dt.tz_localize(tz) exp_values = Series( ["2000-01-28 16:47:00", "2000-01-29 16:48:00", "2000-01-31 16:50:00"], index=[0, 1, 3], name="date", ) expected = pd.to_datetime(exp_values).dt.tz_localize(tz) tm.assert_series_equal(result, expected) def test_groupby_groups_periods(self): dates = [ "2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00", "2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00", ] df = DataFrame( { "label": ["a", "a", "a", "b", "b", "b"], "period": [pd.Period(d, freq="H") for d in dates], "value1": np.arange(6, dtype="int64"), "value2": [1, 2] * 3, } ) exp_idx1 = pd.PeriodIndex( [ "2011-07-19 07:00:00", "2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00", "2011-07-19 09:00:00", ], freq="H", name="period", ) exp_idx2 = Index(["a", "b"] * 3, name="label") exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) expected = DataFrame( {"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]}, index=exp_idx, columns=["value1", "value2"], ) result = df.groupby(["period", "label"]).sum() tm.assert_frame_equal(result, expected) # by level didx = pd.PeriodIndex(dates, freq="H") df = DataFrame( {"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]}, index=didx, ) exp_idx = pd.PeriodIndex( ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"], freq="H", ) expected = DataFrame( {"value1": [3, 5, 7], "value2": [2, 4, 6]}, index=exp_idx, columns=["value1", "value2"], ) result = df.groupby(level=0).sum() tm.assert_frame_equal(result, expected) def test_groupby_first_datetime64(self): df = DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)]) df[1] = df[1].view("M8[ns]") assert issubclass(df[1].dtype.type, np.datetime64) result = df.groupby(level=0).first() got_dt = result[1].dtype assert issubclass(got_dt.type, np.datetime64) result = df[1].groupby(level=0).first() got_dt = result.dtype assert issubclass(got_dt.type, np.datetime64) def test_groupby_max_datetime64(self): # GH 5869 # datetimelike dtype conversion from int df = DataFrame({"A": Timestamp("20130101"), "B": np.arange(5)}) expected = df.groupby("A")["A"].apply(lambda x: x.max()) result = df.groupby("A")["A"].max() tm.assert_series_equal(result, expected) def test_groupby_datetime64_32_bit(self): # GH 6410 / numpy 4328 # 32-bit under 1.9-dev indexing issue df = DataFrame({"A": range(2), "B": [Timestamp("2000-01-1")] * 2}) result = df.groupby("A")["B"].transform(min) expected = Series([Timestamp("2000-01-1")] * 2, name="B") tm.assert_series_equal(result, expected) def test_groupby_with_timezone_selection(self): # GH 11616 # Test that column selection returns output in correct timezone. np.random.seed(42) df = DataFrame( { "factor": np.random.randint(0, 3, size=60), "time": date_range("01/01/2000 00:00", periods=60, freq="s", tz="UTC"), } ) df1 = df.groupby("factor").max()["time"] df2 = df.groupby("factor")["time"].max() tm.assert_series_equal(df1, df2) def test_timezone_info(self): # see gh-11682: Timezone info lost when broadcasting # scalar datetime to DataFrame df = DataFrame({"a": [1], "b": [datetime.now(pytz.utc)]}) assert df["b"][0].tzinfo == pytz.utc df = DataFrame({"a": [1, 2, 3]}) df["b"] = datetime.now(pytz.utc) assert df["b"][0].tzinfo == pytz.utc def test_datetime_count(self): df = DataFrame( {"a": [1, 2, 3] * 2, "dates": date_range("now", periods=6, freq="T")} ) result = df.groupby("a").dates.count() expected = Series([2, 2, 2], index=Index([1, 2, 3], name="a"), name="dates") tm.assert_series_equal(result, expected) def test_first_last_max_min_on_time_data(self): # GH 10295 # Verify that NaT is not in the result of max, min, first and last on # Dataframe with datetime or timedelta values. from datetime import timedelta as td df_test = DataFrame( { "dt": [ np.nan, "2015-07-24 10:10", "2015-07-25 11:11", "2015-07-23 12:12", np.nan, ], "td": [np.nan, td(days=1), td(days=2), td(days=3), np.nan], } ) df_test.dt = pd.to_datetime(df_test.dt) df_test["group"] = "A" df_ref = df_test[df_test.dt.notna()] grouped_test = df_test.groupby("group") grouped_ref = df_ref.groupby("group") tm.assert_frame_equal(grouped_ref.max(), grouped_test.max()) tm.assert_frame_equal(grouped_ref.min(), grouped_test.min()) tm.assert_frame_equal(grouped_ref.first(), grouped_test.first()) tm.assert_frame_equal(grouped_ref.last(), grouped_test.last()) def test_nunique_with_timegrouper_and_nat(self): # GH 17575 test = DataFrame( { "time": [ Timestamp("2016-06-28 09:35:35"), pd.NaT, Timestamp("2016-06-28 16:46:28"), ], "data": ["1", "2", "3"], } ) grouper = Grouper(key="time", freq="h") result = test.groupby(grouper)["data"].nunique() expected = test[test.time.notnull()].groupby(grouper)["data"].nunique() expected.index = expected.index._with_freq(None) tm.assert_series_equal(result, expected) def test_scalar_call_versus_list_call(self): # Issue: 17530 data_frame = { "location": ["shanghai", "beijing", "shanghai"], "time": Series( ["2017-08-09 13:32:23", "2017-08-11 23:23:15", "2017-08-11 22:23:15"], dtype="datetime64[ns]", ), "value": [1, 2, 3], } data_frame = DataFrame(data_frame).set_index("time") grouper = Grouper(freq="D") grouped = data_frame.groupby(grouper) result = grouped.count() grouped = data_frame.groupby([grouper]) expected = grouped.count() tm.assert_frame_equal(result, expected) def test_grouper_period_index(self): # GH 32108 periods = 2 index = pd.period_range( start="2018-01", periods=periods, freq="M", name="Month" ) period_series = Series(range(periods), index=index) result = period_series.groupby(period_series.index.month).sum() expected = Series( range(0, periods), index=Index(range(1, periods + 1), name=index.name) ) tm.assert_series_equal(result, expected) def test_groupby_apply_timegrouper_with_nat_dict_returns( self, groupby_with_truncated_bingrouper ): # GH#43500 case where gb.grouper.result_index and gb.grouper.group_keys_seq # have different lengths that goes through the `isinstance(values[0], dict)` # path gb = groupby_with_truncated_bingrouper res = gb["Quantity"].apply(lambda x: {"foo": len(x)}) dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date") mi = MultiIndex.from_arrays([dti, ["foo"] * len(dti)]) expected = Series([3, 0, 0, 0, 0, 0, 2], index=mi, name="Quantity") tm.assert_series_equal(res, expected) def test_groupby_apply_timegrouper_with_nat_scalar_returns( self, groupby_with_truncated_bingrouper ): # GH#43500 Previously raised ValueError bc used index with incorrect # length in wrap_applied_result gb = groupby_with_truncated_bingrouper res = gb["Quantity"].apply(lambda x: x.iloc[0] if len(x) else np.nan) dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date") expected = Series( [18, np.nan, np.nan, np.nan, np.nan, np.nan, 5], index=dti._with_freq(None), name="Quantity", ) tm.assert_series_equal(res, expected) def test_groupby_apply_timegrouper_with_nat_apply_squeeze( self, frame_for_truncated_bingrouper ): df = frame_for_truncated_bingrouper # We need to create a GroupBy object with only one non-NaT group, # so use a huge freq so that all non-NaT dates will be grouped together tdg = Grouper(key="Date", freq="100Y") with tm.assert_produces_warning(FutureWarning, match="`squeeze` parameter"): gb = df.groupby(tdg, squeeze=True) # check that we will go through the singular_series path # in _wrap_applied_output_series assert gb.ngroups == 1 assert gb._selected_obj._get_axis(gb.axis).nlevels == 1 # function that returns a Series res = gb.apply(lambda x: x["Quantity"] * 2) key = Timestamp("2013-12-31") ordering = df["Date"].sort_values().dropna().index mi = MultiIndex.from_product([[key], ordering], names=["Date", None]) ex_values = df["Quantity"].take(ordering).values * 2 expected = Series(ex_values, index=mi, name="Quantity") tm.assert_series_equal(res, expected) @td.skip_if_no("numba") def test_groupby_agg_numba_timegrouper_with_nat( self, groupby_with_truncated_bingrouper ): # See discussion in GH#43487 gb = groupby_with_truncated_bingrouper result = gb["Quantity"].aggregate( lambda values, index: np.nanmean(values), engine="numba" ) expected = gb["Quantity"].aggregate(np.nanmean) tm.assert_series_equal(result, expected) result_df = gb[["Quantity"]].aggregate( lambda values, index: np.nanmean(values), engine="numba" ) expected_df = gb[["Quantity"]].aggregate(np.nanmean) tm.assert_frame_equal(result_df, expected_df)
/*! * Copyright (c) 2017-present, SeetaTech, Co.,Ltd. * * Licensed under the BSD 2-Clause License. * You should have received a copy of the BSD 2-Clause License * along with the software. If not, See, * * <https://opensource.org/licenses/BSD-2-Clause> * * ------------------------------------------------------------ */ #ifndef DRAGON_CORE_CONTEXT_CUDA_H_ #define DRAGON_CORE_CONTEXT_CUDA_H_ #include "dragon/core/common.h" #include "dragon/utils/device/common_cuda.h" #include "dragon/utils/device/common_cudnn.h" #include "dragon/utils/device/common_nccl.h" namespace dragon { #ifdef USE_CUDA class Workspace; class DRAGON_API CUDAObjects { public: /*! \brief Constructor */ CUDAObjects() { for (int i = 0; i < CUDA_MAX_DEVICES; ++i) { random_seeds_[i] = DEFAULT_RNG_SEED; streams_[i] = vector<cudaStream_t>(); workspaces_[i] = vector<Workspace*>(); cublas_handles_[i] = vector<cublasHandle_t>(); curand_generators_[i] = Map<string, curandGenerator_t>(); #ifdef USE_CUDNN cudnn_handles_[i] = vector<cudnnHandle_t>(); #endif #ifdef USE_NCCL nccl_comms_[i] = Map<string, ncclComm_t>(); #endif } } /*! \brief Destructor */ ~CUDAObjects(); /*! \brief Set the current device */ void SetDevice(int device_id) { CUDA_CHECK(cudaSetDevice(device_id)); } /*! \brief Set the random seed for given device */ void SetRandomSeed(int device_id, int seed) { if (device_id < CUDA_MAX_DEVICES) random_seeds_[device_id] = seed; } /*! \brief Return the current cuda device */ int GetDevice() { int device_id; CUDA_CHECK(cudaGetDevice(&device_id)); return device_id; } /*! \brief Return the random seed of given device */ int GetRandomSeed(int device_id) const { return (device_id < CUDA_MAX_DEVICES) ? random_seeds_[device_id] : DEFAULT_RNG_SEED; } /*! \brief Return the specified cublas handle */ cublasHandle_t cublas_handle(int device_id, int stream_id); /*! \brief Return the specified curand generator */ curandGenerator_t curand_generator(int device_id, int stream_id, int seed); #ifdef USE_CUDNN /*! \brief Return the specified cudnn handle */ cudnnHandle_t cudnn_handle(int device_id, int stream_id); #endif #ifdef USE_NCCL /*! \brief Return the specified nccl comm */ ncclComm_t nccl_comm( int device_id, const string& cache_key, ncclUniqueId* comm_uuid, int comm_size, int comm_rank); #endif /*! \brief Return the default cuda stream of current device */ cudaStream_t default_stream() { return stream(GetDevice(), 0); } /*! \brief Return the default cuda stream of given device */ cudaStream_t default_stream(int device_id) { return stream(device_id, 0); } /*! \brief Return the specified cuda stream */ cudaStream_t stream(int device_id, int stream_id) { auto& streams = streams_[device_id]; if (streams.size() <= unsigned(stream_id)) { streams.resize(stream_id + 1, nullptr); } if (!streams[stream_id]) { CUDADeviceGuard guard(device_id); auto flags = stream_id == 0 ? cudaStreamDefault : cudaStreamNonBlocking; CUDA_CHECK(cudaStreamCreateWithFlags(&streams[stream_id], flags)); } return streams[stream_id]; } /*! \brief Return the workspace of specified cuda stream */ Workspace* workspace(int device_id, int stream_id); /*! \brief The random seed for all devices */ int random_seeds_[CUDA_MAX_DEVICES]; /*! \brief The created streams for all devices */ vector<cudaStream_t> streams_[CUDA_MAX_DEVICES]; /*! \brief The created workspaces for all devices */ vector<Workspace*> workspaces_[CUDA_MAX_DEVICES]; /*! \brief The created cublas handles for all devices */ vector<cublasHandle_t> cublas_handles_[CUDA_MAX_DEVICES]; /*! \brief The created curand generators for all devices */ Map<string, curandGenerator_t> curand_generators_[CUDA_MAX_DEVICES]; #ifdef USE_CUDNN /*! \brief The created cudnn handles for all devices */ vector<cudnnHandle_t> cudnn_handles_[CUDA_MAX_DEVICES]; #endif #ifdef USE_NCCL /*! \brief The created nccl comms for all devices */ Map<string, ncclComm_t> nccl_comms_[CUDA_MAX_DEVICES]; #endif /*! \brief The flag that allows cuBLAS TF32 math type or not */ bool cublas_allow_tf32_ = false; /*! \brief The flag that uses cuDNN or not */ bool cudnn_enabled_ = true; /*! \brief The flag that benchmarks fastest cuDNN algorithms or not */ bool cudnn_benchmark_ = false; /*! \brief The flag that selects deterministic cuDNN algorithms or not */ bool cudnn_deterministic_ = false; /*! \brief The flag that allows cuDNN TF32 math type or not */ bool cudnn_allow_tf32_ = false; private: DISABLE_COPY_AND_ASSIGN(CUDAObjects); }; /*! * \brief The cuda device context. */ class DRAGON_API CUDAContext { public: /*! \brief Constructor */ CUDAContext() : device_id_(0), random_seed_(-1) {} /*! \brief Constructor with the device index */ explicit CUDAContext(int device) : device_id_(device) {} /*! \brief Constructor with the device option */ explicit CUDAContext(const DeviceOption& option) : device_id_(option.device_id()), random_seed_(-1) { CHECK_EQ(option.device_type(), PROTO_CUDA); if (option.has_random_seed()) random_seed_ = int(option.random_seed()); } /*! \brief Allocate a block of device memory */ static void* New(size_t size) { void* data; cudaMalloc(&data, size); CHECK(data) << "\nAllocate device memory with " << size << " bytes failed."; return data; } /*! \brief Allocate a block of host memory */ static void* NewHost(size_t size) { void* data; cudaMallocHost(&data, size); CHECK(data) << "\nAllocate host memory with " << size << " bytes failed."; return data; } /*! \brief Set a memory block to the given value */ static void Memset(size_t n, void* ptr, int value = 0) { auto stream = objects().default_stream(); CUDA_CHECK(cudaMemsetAsync(ptr, value, n, stream)); SynchronizeStream(stream); } /*! \brief Set a memory block to the given value asynchronously */ void MemsetAsync(size_t n, void* ptr, int value = 0) { CUDA_CHECK(cudaMemsetAsync(ptr, value, n, cuda_stream())); } /*! \brief Copy a memory block to the destination */ template <class DestContext, class SrcContext> static void Memcpy(size_t n, void* dest, const void* src) { Memcpy<DestContext, SrcContext>(n, dest, src, current_device()); } /*! \brief Copy a memory block to the destination using given device */ template <class DestContext, class SrcContext> static void Memcpy(size_t n, void* dest, const void* src, int device) { auto stream = objects().default_stream(device); CUDA_CHECK(cudaMemcpyAsync(dest, src, n, cudaMemcpyDefault, stream)); SynchronizeStream(stream); } /*! \brief Copy a memory block to the destination asynchronously */ template <class DestContext, class SrcContext> void MemcpyAsync(size_t n, void* dest, const void* src) { CUDA_CHECK(cudaMemcpyAsync(dest, src, n, cudaMemcpyDefault, cuda_stream())); } /*! \brief Synchronize the given stream */ static void SynchronizeStream(cudaStream_t stream) { cudaStreamSynchronize(stream); auto err = cudaGetLastError(); CHECK_EQ(err, cudaSuccess) << "\nCUDA Error: " << cudaGetErrorString(err); } /*! \brief Deallocate a device memory block */ static void Delete(void* ptr) { cudaFree(ptr); } /*! \brief Deallocate a host memory block */ static void DeleteHost(void* ptr) { cudaFreeHost(ptr); } /*! \brief Switch to the device and select given stream in current thread */ void SwitchToDevice(int stream_id = 0) { objects().SetDevice(device_id_); stream_id_ = stream_id; } /*! \brief Copy a typed memory block to the destination */ template <typename T, class DestContext, class SrcContext> void Copy(int n, T* dest, const T* src) { if (dest == src) return; MemcpyAsync<SrcContext, DestContext>(n * sizeof(T), dest, src); } /*! \brief Wait for the dispatched computation to complete */ void FinishDeviceComputation() { SynchronizeStream(cuda_stream()); } /*! \brief Return the current workspace */ Workspace* workspace() { return objects().workspace(device_id_, stream_id_); } /*! \brief Return the specified workspace */ Workspace* workspace(int device, int stream) { return objects().workspace(device, stream); } /*! \brief Return the current cuda stream */ cudaStream_t cuda_stream() { return objects().stream(device_id_, stream_id_); } /*! \brief Return the specified cuda stream */ cudaStream_t cuda_stream(int device, int stream) { return objects().stream(device, stream); } /*! \brief Return the cublas handle */ cublasHandle_t cublas_handle() { return objects().cublas_handle(device_id_, stream_id_); } /*! \brief Return the curand generator */ curandGenerator_t curand_generator() { return objects().curand_generator(device_id_, stream_id_, random_seed()); } /*! \brief Return the cudnn handle */ #ifdef USE_CUDNN cudnnHandle_t cudnn_handle() { return objects().cudnn_handle(device_id_, stream_id_); } #endif /*! \brief Return the device index */ int device() const { return device_id_; } /*! \brief Return the stream index */ int stream() const { return stream_id_; } /*! \brief Return the random seed */ int random_seed() const { return random_seed_ >= 0 ? random_seed_ : objects().GetRandomSeed(device_id_); } /*! \brief Return the device index of current thread */ static int current_device() { return objects().GetDevice(); } /*! \brief Return the shared context mutex */ static std::mutex& mutex(); /*! \brief Return the thread-local cuda objects */ static CUDAObjects& objects(); /*! \brief Set the stream index */ void set_stream(int stream) { stream_id_ = stream; } private: /*! \brief The device index */ int device_id_; /*! \brief The stream index */ int stream_id_ = 0; /*! \brief The random seed */ int random_seed_; }; #endif // USE_CUDA } // namespace dragon #endif // DRAGON_CORE_CONTEXT_CUDA_H_
import React from "react"; import styled from "styled-components"; import { Link, useNavigate } from "react-router-dom"; import ReactWhatsapp from 'react-whatsapp'; import { FaFacebook, FaInstagram, FaYoutube, FaTwitter, FaLinkedin, FaWhatsapp, } from "react-icons/fa"; import { callNum } from "../../utils/basicInfo"; const FooterContainer = styled.div` background-color: #f7f7f7; padding: 2rem 0 0rem 0; display: flex; flex-direction: column; justify-content: center; align-items: center; @media screen and (max-width: 650px) { /* height: 120%; */ padding: 5rem; } `; const FooterSubscription = styled.section` display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; margin-bottom: 24px; padding: 14px; color: #000; `; const FooterSubHeading = styled.p` margin-bottom: 24px; font-size: 24px; `; const FooterSubText = styled.p` margin-bottom: 24px; font-size: 20px; `; const Form = styled.form` display: flex; justify-content: center; align-items: center; @media screen and (max-width: 820px) { flex-direction: column; width: 80%; } `; const FormInput = styled.input` padding: 10px 20px; border-radius: 2px; margin-right: 10px; outline: none; `; const FooterLinkContainer = styled.div` width: 100%; max-width: 1000px; display: flex; justify-content: center; @media screen and (max-width: 820px) { padding-top: 32px; } `; const FooterLinkWrapper = styled.div` display: flex; @media screen and (max-width: 820px) { flex-direction: column; } `; const FooterLinkItems = styled.div` display: flex; flex-direction: column; align-items: flex-start; margin: 35px; text-align: left; width: 160px; box-sizing: border-box; color: #000; @media screen and (max-width: 420px) { margin: 0; padding: 10px; width: 100%; } `; const FooterLinkItems1 = styled.div` display: flex; flex-direction: column; align-items: flex-start; margin: 0px; text-align: left; width: 360px; box-sizing: border-box; color: #000; img { margin: 10; } @media screen and (max-width: 420px) { margin: 0; padding: 10px; width: 100%; } `; const FooterLinkTitle = styled.h2` margin-bottom: 16px; `; const FooterLink = styled(Link)` color: #000; text-decoration: none; margin-bottom: 1rem; &:hover { color: #0467fb; transition: 0.3s ease-out; } `; const FooterText = styled.p` color: #000; text-decoration: none; margin-top: 2rem; `; export const SocialLogo = styled(Link)` color: #000; justify-self: start; cursor: pointer; text-decoration: none; font-size: 1.5rem; display: flex; align-items: center; justify-content: center; /* margin-bottom: 16px; */ font-weight: bold; `; export const SocialIcons = styled.div` display: flex; /* justify-content: space-between; */ align-items: center; width: 240px; `; export const SocialIconLink = styled.a` color: #000; font-size: 24px; margin: 10px; `; export const ContactParm = styled.p` color: #fff; font-size: 14px; padding: 0px 0px 10px 0px; `; export const Logo = styled.img` width: 15rem; height: 5rem; /* @media screen and (max-width: 720px){ width: '40%'; height: '30%'; } */ `; export const HeroBtnWhatsApp = styled(ReactWhatsapp)` border: none; `; const Footer = () => { const navigate = useNavigate(); return ( <FooterContainer> {/* <FooterSubscription> <FooterSubHeading> gggggg ggghyhyhyyguhhhh hbhjhj kjkjkjkj </FooterSubHeading> <FooterSubText> gggggg ggghyhyhyyguhhhh hbhjhj kjkjkjkj </FooterSubText> <Form> <FormInput> </FormInput> </Form> </FooterSubscription> */} <FooterLinkContainer> <FooterLinkWrapper> <FooterLinkItems1> {/* <Logo src={img2} /> */} <FooterLinkTitle>About Us</FooterLinkTitle> <FooterText to=""> We provide safe and low price taxi service.WE ARE THE BEST IN TOWN </FooterText> </FooterLinkItems1> <FooterLinkItems> <FooterLinkTitle>Quick links</FooterLinkTitle> <FooterLink to="/">HOME</FooterLink> <FooterLink to="/booktaxi">BOOK TAXI</FooterLink> <FooterLink to="/aboutus">ABOUT ME</FooterLink> <FooterLink to="/packages">PACKAGES</FooterLink> </FooterLinkItems> <FooterLinkItems> <FooterLinkTitle>Contact us</FooterLinkTitle> <FooterLink to="">{callNum}</FooterLink> <FooterLink to=""></FooterLink> <FooterLink to=""> Faculty of science, university of colombo,Cumarathunga Munidasa Mawatha,Colombo 00300, Sri Lanka </FooterLink> </FooterLinkItems> <FooterLinkItems> <FooterLinkTitle>Follow us</FooterLinkTitle> <SocialIcons> <SocialIconLink href="https://www.facebook.com/parakrama.saranga" target="_blank" aria-label="Facebook" > <FaFacebook /> </SocialIconLink> <HeroBtnWhatsApp number={'+94716074311'} message="Welcome to Saranga taxi service !!" > <SocialIconLink href="" target="_blank" aria-label="Whatsapp" > <FaWhatsapp /> </SocialIconLink> </HeroBtnWhatsApp> {/* <SocialIconLink href='//www.twitter.com/briandesignz' target='_blank' aria-label='Twitter' rel='noopener noreferrer' > <FaTwitter /> </SocialIconLink> */} </SocialIcons> </FooterLinkItems> </FooterLinkWrapper> </FooterLinkContainer> </FooterContainer> ); }; export default Footer;
DEMO INSTRUCTIONS This is a demonstration of the JavaHelp viewer running in a web browser using the Java Plug-in with JDK1.1.6 or later (does not work with JDK1.2). JavaHelp does not run correctly in web browsers and the appletviewer due to a limitation in Swing 1.1 Beta3. This limitation will be corrected by Swing1.1FCS. In the meantime, a description of how to work around this issue will be posted to the JavaHelp website. You can download JRE/JDK 1.1.7 from http://java.sun.com/products/jdk. It's best to install the JRE before you proceed with the rest of these instructions. These instructions assume that the demos\browser folder is your current folder. 1. In order to reduce download size the Holidays HelpSet used in the demo is not included the browser folder. To include the HelpSet files in browser folder use the jar command: (Win32) jar -xvf ..\hsjar\holidays.jar (Solaris) jar -xvf ../hsjar/holidays.jar 2. Copy jh.jar to the browser folder with following command: (Win32) copy ..\..\javahelp\lib\jh.jar . (Solaris) cp ../../javahelp/lib/jh.jar . 3. Copy the version of Swing included in the JavaHelp release to the lib folder of the JRE or JDK. You must use THIS version of Swing for the demo to work. : (Win32) copy ..\..\swing\swingall.jar {JRE}\lib (Solaris) cp ../../swing/swingall.jar {JRE}/lib NOTE: Be sure that this is the same JRE/JDK to which the Java Plug-in points (see step 6 below). 4. Load the demo page: PluginDemo.html into either Netscape Navigator 4 or Internet Explorer 4. 5. If you do not have the Java Plug-in installed on your system, you will be prompted to do so and led through the automated process of installing it. Note that you may have to use the Advanced tab on the Plug-in ControlPanel to set the correct path to your JRE. 6. When the page is loaded, press the Help button to start the JavaHelp viewer.
<template> <div class="container"> <div class="container-fluid justify-content-center"> <div class="row mt-5" > <div class="col-sm-3" v-for="(transaction, index) in transactions" :key="index"> <ProductCard v-bind:product="transaction"/> </div> </div> </div> </div> </template> <script> import axios from 'axios' import {onBeforeMount, onMounted, ref} from 'vue' import * as fb from '../../utils/firebase.js' import ProductCard from '../../components/ProductCard.vue' export default { components: { ProductCard, }, setup() { //reactive state const name = ref(""); let transactions = ref([]); const dbRef = fb.ref(fb.db); onBeforeMount(() => { fb.getAuth().onAuthStateChanged((user) => { if(user){ console.log(user); name.value = user.email.split('@')[0]; } }) }); onMounted(() => { const transactionsCountRef = fb.ref(fb.db, 'products/'); fb.onValue(transactionsCountRef, (snapshot) => { let data = snapshot.val(); console.log('data:',data) transactions.value = data }); }); function destroy(id, index) { console.log(id); axios.delete(`https://crudcrud.com/api/4682bf7fdfa14d94a4eb20c7cdd18aef/transaction/${id}` ) .then((result) => { transactions.value.splice(index, 1) }).catch((err) => { console.log(err.response.data) }); } return { transactions, name // destroy } } } </script>
# SASS 🚀 Sass (short for syntactically awesome style sheets) is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS). SassScript is the scripting language itself. # SASS Practices Repository ⭐ This repository contains various SASS practices to improve SASS skills and knowledge. # Table of Contents 📃 - Introduction - Installation and Usage - Contributing # Introduction ✅ The SASS is the abbreviation of Syntactically Awesome Style Sheets. It is a CSS pre-processor with syntax advancements. The style sheets in the advanced syntax are processed by the program and compiled into regular CSS style sheets, which can be used in the website. It is a CSS extension that allows to use feature like variables, nesting, imports, mixins, inheritance, etc, all in a CSS-compatible syntax ie., it is compatible with all the CSS versions. # Installation and Usage 🖥️ To use this repository, you need to have a web browser and a code editor. You can use any web browser and code editor of your choice, such as Google Chrome, Firefox, Visual Studio Code, Sublime Text, etc. You can clone or download this repository from GitHub and open the files in your browser to see the output. You can also edit the files in your code editor to modify or experiment with the code. To clone this repository: To download this repository, click on the green “Code” button on the GitHub page and select “Download ZIP”. Then, extract the ZIP file and open the folder in your code editor. # Contributing 🛂 If you want to contribute to this project, you are welcome to do so. You can submit issues, pull requests, or feedback to improve the quality and the content of this project. Please follow these guidelines when contributing: Use clear and descriptive titles and messages for your issues and pull requests. Test your code before submitting it. Add comments to explain your code logic and changes.
package com.cxyhome.top.common.util; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * ID 生成类 */ public class IdGenerator { private final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; private final static Map<Character, Integer> digitMap = new HashMap<>(); static { for (int i = 0; i < digits.length; i++) { digitMap.put(digits[i], i); } } /** * 支持的最大进制数 */ private static final int MAX_RADIX = digits.length; /** * 支持的最小进制数 */ private static final int MIN_RADIX = 2; /** * 将长整型数值转换为指定的进制数(最大支持62进制,字母数字已经用尽) * * @param i 序号 * @param radix 精度 * @return 字符串 */ private static String toString (long i, int radix) { if (radix < MIN_RADIX || radix > MAX_RADIX) radix = 10; if (radix == 10) return Long.toString(i); final int size = 65; int charPos = 64; char[] buf = new char[size]; boolean negative = (i < 0); if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = digits[(int) (-(i % radix))]; i = i / radix; } buf[charPos] = digits[(int) (-i)]; if (negative) { buf[--charPos] = '-'; } return new String(buf, charPos, (size - charPos)); } private static String digits (long val, int digits) { long hi = 1L << (digits << 2); return toString(hi | (val & (hi - 1)), MAX_RADIX) .substring(1); } /** * 以62进制(字母加数字)生成19位UUID,最短的UUID * * @return 19位UUID */ public static String uuid () { UUID uuid = UUID.randomUUID(); long mostSignificantBits = uuid.getMostSignificantBits(); long leastSignificantBits = uuid.getLeastSignificantBits(); StringBuilder sb = new StringBuilder(); sb.append(digits(mostSignificantBits >> 32, 8)); sb.append(digits(mostSignificantBits >> 16, 4)); sb.append(digits(mostSignificantBits, 4)); sb.append(digits(leastSignificantBits >> 48, 4)); sb.append(digits(leastSignificantBits, 12)); return sb.toString(); } public static void main (String[] args) { System.out.println(IdGenerator.uuid()); } }
<?php /** * BuyByRaffleRaffleClassMgr * * This class manages the raffle classes used in the plugin. It allows for setting * the raffle classes upon plugin activation and provides a method to retrieve * a raffle class ID by its name. */ namespace Sgs\Buybyraffle; class BuyByRaffleRaffleClassMgr { /** * Initializes the raffle classes within the WordPress options table. * * This method is intended to be called on plugin activation. It sets up * an array of raffle classes, each with a unique ID and name, and stores * them in the wp_options table for later retrieval. */ public static function init_raffle_classes() { // Define the array of raffle classes $raffle_classes = [ ['raffle_class_id' => 1, 'raffle_class_name' => 'bait'], ['raffle_class_id' => 2, 'raffle_class_name' => 'hero'], ['raffle_class_id' => 3, 'raffle_class_name' => 'solo'] ]; // Save the array of raffle classes in the wp_options table update_option('raffle_classes', $raffle_classes); } /** * Retrieves the raffle class ID by its name. * * @param string $raffle_class_name The name of the raffle class to search for. * @return int|null Returns the ID of the raffle class if found, or null otherwise. * * This method looks up the raffle class ID based on the provided raffle class name. * It is useful when you have the name of the raffle class and need to retrieve its * corresponding ID for database operations or logic checks. */ public static function get_raffle_class_id_by_name($raffle_class_name) { // Retrieve the array of raffle classes from the wp_options table $raffle_classes = get_option('raffle_classes'); // If the option is not set or an error occurred, return null if (!$raffle_classes) { return null; } // Iterate through the array of raffle classes foreach ($raffle_classes as $raffle_class) { // Check if the current class name matches the provided name if ($raffle_class['raffle_class_name'] === $raffle_class_name) { // If a match is found, cast the ID to an integer for consistency and return it return (int) $raffle_class['raffle_class_id']; } } // If no match is found, return null return null; } /** * Retrieves the raffle class name by its ID. * * @param int $raffle_class_id The ID of the raffle class to search for. * @return string|null The name of the raffle class if found, or null otherwise. */ public static function get_raffle_class_name_by_id($raffle_class_id) { $raffle_classes = get_option('raffle_classes'); if (!$raffle_classes) { return null; // The option has not been set or an error occurred. } foreach ($raffle_classes as $raffle_class) { if ((int) $raffle_class['raffle_class_id'] === $raffle_class_id) { return $raffle_class['raffle_class_name']; } } return null; // Raffle class ID not found. } }
import 'package:flutter/material.dart'; import 'package:phoenix_mobile/utils/ui/colors.dart'; import 'package:phoenix_mobile/utils/ui/fonts.dart'; class CardTransactionContainer extends StatelessWidget { final String title; final String prise; final String secondaryTitle; final String usdValue; final VoidCallback onTap; const CardTransactionContainer( {super.key, required this.title, required this.prise, required this.secondaryTitle, required this.onTap, required this.usdValue}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(top: 8), child: InkWell( onTap: onTap, borderRadius: BorderRadius.circular(12), child: Ink( width: double.infinity, decoration: ShapeDecoration( color: AppColors.purple100, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), )), child: Container( padding: EdgeInsets.all(12), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Container( width: 40, height: 40, padding: const EdgeInsets.all(4), decoration: ShapeDecoration( color: AppColors.backgroundSecondary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(32), ), ), ), const SizedBox( width: 12, ), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: AppTypography.font16w400 .copyWith(color: AppColors.textPrimary), ), const SizedBox( height: 3, ), Text(secondaryTitle, style: AppTypography.font14w400 .copyWith(color: AppColors.disabledTextButton)) ], ), ], ), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [ Text(prise, style: AppTypography.font16w400 .copyWith(color: AppColors.textPrimary)), const SizedBox( height: 3, ), Text(usdValue, style: AppTypography.font12w400 .copyWith(color: AppColors.disabledTextButton)), ], ), ], ), ), ), ), ); } }
<div class="container"> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'> <header> <nav> <ol class="breadcrumb repo-breadcrumb"> <li class="breadcrumb-item"><a href="/administrator" [routerLink]="['/administrator']" class="router-link-active">Administrator board</a></li> </ol> </nav> <div class="box"> <div style="margin-top: 7px;"> <button mat-raised-button color="primary" (click)="addNewRank()" *ngIf="role == 'ROLE_ADMINISTRATOR'">Add new rank</button> </div> <div> <form [formGroup]="searchForm"> <div class="form-group has-search block" *ngIf="role == 'ROLE_ADMINISTRATOR'"> <span class="fa fa-search form-control-feedback"></span> <input type="text" class="form-control" formControlName="searchProfessorName" (keyup)="applyFilter()" placeholder="Professor"> </div> <mat-form-field appearance="outline" style="margin-left: 8px; top: 2.8px;"> <mat-label>Scientific area</mat-label> <mat-select formControlName="searchScientificArea" (selectionChange)="applyFilter()"> <mat-option *ngFor="let scientificArea of scientificAreas" [value]="scientificArea.name">{{scientificArea.name}} </mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline" style="margin-left: 8px; top: 2.8px;"> <mat-label>Type rank</mat-label> <mat-select formControlName="searchTypeRank" (selectionChange)="applyFilter()"> <mat-option *ngFor="let typeRank of typeRanks" [value]="typeRank.name">{{typeRank.name}} </mat-option> </mat-select> </mat-form-field> <div class="block" *ngIf="this.searchProfessorName != '' || this.searchScientificArea != '' || this.searchTypeRank != ''"> <span class="cross" (click)="resetSearch()" title="Reset search">x</span> </div> </form> </div> <div class="push" style="margin-top: 7px;"><button mat-raised-button color="warn" (click)="delete()" *ngIf="role == 'ROLE_ADMINISTRATOR'" title="Delete selected objects">Delete</button> </div> </div> <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <!-- Checkbox Column --> <ng-container matColumnDef="select"> <th mat-header-cell *matHeaderCellDef> <mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()" [indeterminate]="selection.hasValue() && !isAllSelected()" color="primary"></mat-checkbox> </th> <td mat-cell *matCellDef="let rank;"> <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(rank) : null" [checked]="selection.isSelected(rank)" [aria-label]="checkboxLabel(rank)" color="primary"></mat-checkbox> </td> </ng-container> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th> <ng-container *matCellDef="let rank"> <td mat-cell> {{rank.id}} </td> </ng-container> </ng-container> <ng-container matColumnDef="electionDate"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Election date </th> <ng-container *matCellDef="let rank"> <td mat-cell> {{rank.electionDate | date:'yyyy-MM-dd'}} </td> </ng-container> </ng-container> <ng-container matColumnDef="terminationDate"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Termination date </th> <ng-container *matCellDef="let rank"> <td mat-cell> {{rank.terminationDate | date:'yyyy-MM-dd'}} {{rank.terminationDate ? '' : 'Undefined'}} </td> </ng-container> </ng-container> <ng-container matColumnDef="typeRanks"> <th mat-header-cell *matHeaderCellDef> Type rank </th> <td mat-cell *matCellDef="let rank"> <span>{{rank.typeRanks.name}}</span> </td> </ng-container> <ng-container matColumnDef="scientificArea"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Scientific area </th> <td mat-cell *matCellDef="let rank"> <span>{{rank.scientificArea.name}}</span> </td> </ng-container> <ng-container matColumnDef="professor"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Professor </th> <td mat-cell *matCellDef="let rank"> <span>{{rank.professor.user.name}} {{rank.professor.user.surname}}</span> </td> </ng-container> <ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Actions </th> <ng-container *matCellDef="let rank"> <td mat-cell> <div class="example-button-row"> <button mat-icon-button color="primary" (click)="selectForChange(rank);"> <mat-icon>edit</mat-icon> </button> </div> </td> </ng-container> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let rank; columns: displayedColumns;" (click)="selection.toggle(rank)"></tr> </table> <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons aria-label="Select page of rank"></mat-paginator> </div> <div *ngIf="dataSource?.data.length === 0">No Records Found!</div> </header> </div>
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { AuthorisationService } from './authorisation.service'; @Injectable({ providedIn: 'root' }) export class ErrorInterceptorService { constructor(private authenticationService: AuthorisationService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).pipe(catchError(err => { if (err.status === 401) { // auto logout if 401 response returned from api this.authenticationService.logout(); location.reload(true); } const error = err.error.message || err.statusText; return throwError(error); })) } }
package com.jnv.common.accesslog.filter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.annotation.Resource; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import com.jnv.common.accesslog.service.AccessLoggerService; import com.jnv.common.accesslog.vo.AccessLogVO; import com.jnv.jncore.security.UserVO; import com.jnv.sm.vo.MenuManageVO; import org.egovframe.rte.fdl.security.userdetails.util.EgovUserDetailsHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Component; @Component("nexacroFormAccessLogFilter") public class NexacroFormAccessLogFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(NexacroFormAccessLogFilter.class); public static final String PARAM_MENU_ID = "__menuId__"; private final AntPathRequestMatcher matcher = new AntPathRequestMatcher("/nxui/**/*.xfdl.js"); @Resource(name = "accessLoggerService") private AccessLoggerService service; @Override public void init(FilterConfig filterConfig) throws ServletException { // no-op } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (!matcher.matches(req) || !req.getParameterMap().containsKey(PARAM_MENU_ID)) { chain.doFilter(request, response); return; } String menuId = req.getParameter(PARAM_MENU_ID); String requestUri = req.getRequestURI(); String contextPath = req.getContextPath(); String path = requestUri.startsWith(contextPath) ? requestUri.substring(contextPath.length()) : requestUri; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); AccessLogVO logVO = new AccessLogVO(); UserVO user = (UserVO) EgovUserDetailsHelper.getAuthenticatedUser(); LOG.debug("Form requested: {}", path); if (user != null) { MenuManageVO menuInfo = service.getMenuInfo(menuId, user.getSysId()); logVO.setUserId(user.getUserId()); logVO.setMemberId(user.getMemberId()); logVO.setUserNmKr(user.getUserNmKr()); logVO.setSysId(user.getSysId()); if (menuInfo != null) { logVO.setMenuNm(menuInfo.getMenuNm()); logVO.setProgId(menuInfo.getProgId()); logVO.setProgNm(menuInfo.getProgNm()); } } logVO.setAccessIp(req.getRemoteAddr()); logVO.setAccessTime(dateFormat.format(new Date())); logVO.setAccessUrl(path); logVO.setMenuId(menuId); chain.doFilter(req, response); logVO.setActionResult(""); logVO.setFinishTime(dateFormat.format(new Date())); service.insertAccessLog(logVO); } @Override public void destroy() { // no-op } }
<?php namespace App\Http\Controllers\backend; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\Category; use App\Model\Product; use App\Model\Supplier; use App\Model\Unit; use Auth; use App\Model\Purchase; use Illuminate\Support\Facades\DB; use App\Model\Invoice; use App\Model\InvoiceDetail; use App\Model\Payment; use App\Model\PaymentDetail; use App\Model\Customer; use PDF; class InvoiceController extends Controller { public function view(){ $allData = Invoice::orderBy('id','desc')->where('status','1')->get(); return view('backend.invoice.invoice-view',compact('allData')); } public function add(){ $data['categories'] = Category::all(); $invoice_data = Invoice::orderBy('id','desc')->first(); if ($invoice_data==null){ $firstReg = 0; $data['invoice_no'] = $firstReg+1; }else{ $invoice_data = Invoice::orderBy('id','desc')->first()->invoice_no; $data['invoice_no'] = $invoice_data + 1; } $data['customers'] = Customer::all(); $data['date'] = date('y-m-d'); return view('backend.invoice.invoice-add',$data); //return view('backend.product.product-add',compact('suppliers','units')); Alternetive system } public function store(Request $request){ //dd($request->all()); if($request->category_id == null){ return redirect()->back()->with('error','Sorry! you do not select any product'); }else{ if($request->paid_amount>$request->estimated_amount){ return redirect()->back()->with('error','Sorry! you entered overprice from the product price'); }else{ $invoice = new Invoice; $invoice->invoice_no = $request->invoice_no; $invoice->date = date('Y-m-d',strtotime($request->date)); $invoice->description = $request->description; $invoice->status = 0; $invoice->created_by = Auth::user()->id; //$invoice->save(); DB::transaction(function () use($request,$invoice){ if($invoice->save()){ $count_category = count($request->category_id); //dd($count_category); for ($i=0; $i <$count_category; $i++) { $invoice_details = new InvoiceDetail(); $invoice_details->date = date('Y-m-d',strtotime($request->date)); $invoice_details->invoice_id = $invoice->id; $invoice_details->category_id = $request->category_id[$i]; $invoice_details->product_id = $request->product_id[$i]; $invoice_details->selling_qty = $request->selling_qty[$i]; $invoice_details->unit_price = $request->unit_price[$i]; $invoice_details->selling_price = $request->selling_price[$i]; $invoice_details->status = '0'; $invoice_details->save(); } if ($request->customer_id == '0') { $customer = new Customer(); $customer->name = $request->name; $customer->mobile_no = $request->mobile_no; $customer->address = $request->address; $customer->save(); $customer_id = $customer->id; }else{ $customer_id = $request->customer_id; } $payment = new Payment(); $payment_details = new PaymentDetail(); $payment->invoice_id = $invoice->id; $payment->customer_id = $customer_id; $payment->paid_status = $request->paid_status; $payment->discount_amount = $request->discount_amount; $payment->total_amount = $request->estimated_amount; if ($request->paid_status=='full_paid') { $payment->paid_amount = $request->estimated_amount; $payment->due_amount = '0'; $payment_details->current_paid_amount = $request->estimated_amount; }elseif ($request->paid_status=='full_due') { $payment->paid_amount = '0'; $payment->due_amount = $request->estimated_amount; $payment_details->current_paid_amount = '0'; }elseif ($request->paid_status=='partial_paid') { $payment->paid_amount = $request->paid_amount; $payment->due_amount = $request->estimated_amount-$request->paid_amount; $payment_details->current_paid_amount = $request->paid_amount; } $payment->save(); $payment_details->invoice_id = $invoice->id; $payment_details->date = date('Y-m-d',strtotime($request->date)); $payment_details->save(); } }); } } return redirect()->route('invoice-pending-list')->with('success','Data Added successfully'); } public function delete($id){ $invoice = Invoice::find($id); $invoice->delete(); InvoiceDetail::where('invoice_id',$invoice->id)->delete(); Payment::where('invoice_id',$invoice->id)->delete(); PaymentDetail::where('invoice_id',$invoice->id)->delete(); return redirect()->route('invoice-pending-list')->with('success', 'Data deleted successfully'); } public function pendingList(){ $allData = Invoice::orderBy('id','desc')->where('status','0')->get(); return view('backend.invoice.invoice-pending-list',compact('allData')); } public function approve($id){ $invoice = Invoice::with(['invoice_details'])->find($id); return view('backend.invoice.invoice-approve',compact('invoice')); // dd('ok'); // $purchase = Purchase::find($id); // $product = Product::where('id',$purchase->product_id)->first(); // $purchase_qty = ((float)($purchase->buying_qty))+((float)($product->quantity)); // $product->quantity = $purchase_qty; // if ($product->save()){ // DB::table('invoice') // ->where('id',$id) // ->update(['status' => 1]); // } // return redirect()->route('invoice-pending-list')->with('success', 'Data approved successfully'); } public function approvalStore(Request $request,$id) { foreach ($request->selling_qty as $key => $val) { $invoice_details = InvoiceDetail::where('id', $key)->first(); $invoice_details->status = '1'; $invoice_details->save(); $product_name = Product::where('id', $invoice_details->product_id)->first(); if ($product_name->quantity < $request->selling_qty[$key]) { return redirect()->back()->with('error', 'Sorry! You given maximum value'); } } $invoice = Invoice::find($id); $invoice->approved_by = Auth::user()->id; $invoice->status = '1'; DB::transaction(function () use($request, $invoice, $id) { foreach ($request->selling_qty as $key => $val) { $invoice_details = InvoiceDetail::where('id', $key)->first(); // $invoice_details->status = '1'; // $invoice_details->save(); $product_name = Product::where('id', $invoice_details->product_id)->first(); $product_name->quantity = ((float)$product_name->quantity) - ((float)$request->selling_qty[$key]); $product_name->save(); } $invoice->save(); }); return redirect()->route('invoice-pending-list')->with('success', 'Successfully Invoice Approved'); } public function printInvoiceList(){ $allData = Invoice::orderBy('id','desc')->where('status','1')->get(); return view('backend.invoice.invoice-print-list',compact('allData')); } function printInvoice($id) { $data['invoice']= Invoice::with(['invoice_details'])->find($id); $pdf = PDF::loadView('backend.pdf.invoice-pdf', $data); $pdf->SetProtection(['copy', 'print'], '', 'pass'); return $pdf->stream('document.pdf'); } public function dailyReport(){ return view('backend.invoice.invoice-daily-report'); } public function dailyReportPdf(Request $request){ $sdate = date('Y-m-d', strtotime($request->start_date)); $edate = date('Y-m-d', strtotime($request->end_date)); $data['allData'] = Invoice::whereBetween('date',[$sdate,$edate])->where('status','1')->get(); $data['start_date'] = date('Y-m-d', strtotime($request->start_date)); $data['end_date'] = date('Y-m-d', strtotime($request->end_date)); $pdf = PDF::loadView('backend.pdf.invoice-daily-report-pdf', $data); $pdf->SetProtection(['copy', 'print'], '', 'pass'); return $pdf->stream('document.pdf'); } }
# -*- coding: utf-8 -*- """ Created on Tue Aug 30 20:02:42 2022 WNBA VIZZIES @author: ericd """ import pandas as pd import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox import matplotlib.ticker as mtick ########################### WNBA EFFICIENCY PLOT################################################# #read in team data #Source: https://www.basketball-reference.com/wnba/years/2022.html data = pd.read_csv('teamData.csv') data.head() #set image paths data['path'] = 'C:/Users/ericd/OneDrive - North Carolina State University/Desktop/WNBA Viz/LogosHeadshots/'+ data['Team'] + '.png' ### ORTG/DRTG PLOTS #create plot area fig, ax = plt.subplots() #set plot size fig.set_size_inches(7,5) #add images def getImage(path): return OffsetImage(plt.imread(path), zoom=0.03, alpha=1) #new plot fig, ax = plt.subplots(figsize=(6, 4), dpi=600) ax.scatter(data['ORtg'], data['DRtg'], color='white') ax.set_title('WNBA Team Offensive/Defensive Efficiencies, 2022 Season', size=10) ax.set_xlabel('Offensive Rating') ax.set_ylabel('Defensive Rating') plt.axhline(y=103.8, color = 'black', linestyle='dashed', alpha=.5) plt.axvline(x=103.8, color='black', linestyle='dashed', alpha=.5) plt.ylim(112,96) #average line labels fig.text(.715, .525, 'League Average DRtg', size=5, alpha=0.5) fig.text(.475,.14, 'League Average ORtg', size=5, alpha=0.5, rotation=90) #quadrant labels fig.text(.58, .85, 'Good Offense, Good Defense', size=7) fig.text(.2,.85, 'Bad Offense, Good Defense', size=7) fig.text(.58, .14, 'Good Offense, Bad Defense', size=7) fig.text(.2,.14, 'Bad Offense, Bad Defense', size=7) #source/name fig.text(0.03,.02, 'Source: https://www.basketball-reference.com/wnba/years/2022.html', size=4) fig.text(.03,.04, 'Created By: Eric Drew',size=4) for index, row in data.iterrows(): ab = AnnotationBbox(getImage(row['path']), (row['ORtg'], row['DRtg']), frameon=False) ax.add_artist(ab)
import { useMemo } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import styles from './index.scss'; interface Props { status: string; } const Index: React.FC<Props> = ({ status }) => { const result = useMemo<[string, JSX.Element, string]>(() => { if (status === 'ENABLE') { return [ 'hsl(120, 38%, 60%)', <FontAwesomeIcon key='running' icon={['fas', 'circle-check']} />, 'Running' ]; } if (status === 'PAUSE' || status === 'DISABLE') { return [ 'hsl(39, 38%, 60%)', <FontAwesomeIcon key='pause' icon={['fas', 'circle-pause']} />, 'Pause' ]; } return [ 'hsl(0, 38%, 60%)', <FontAwesomeIcon key='forbidden' icon={['fas', 'circle-xmark']} />, 'Forbidden' ]; }, [status]); return ( <div className={styles.status} style={{ borderColor: result[0] }}> <span className={styles.statusIcon} style={{ background: result[0] }}> {result[1]} </span> <span className={styles.statusText} style={{ color: result[0] }}> {result[2]} </span> </div> ); }; export default Index;
import { useEffect } from "react"; import { useDispatch } from "react-redux"; import { setLoading, setSnackbar } from "redux/features/layoutSlice"; const useLayout = (props: { isError: boolean; isLoading: boolean; errorMessage: string; }) => { const { isError, isLoading, errorMessage } = props; const dispatch = useDispatch(); useEffect(() => { if (isLoading) { dispatch(setLoading(true)); } else { dispatch(setLoading(false)); } if (isError) { dispatch( setSnackbar({ open: true, color: "error", message: errorMessage, }) ); } }, [isError, errorMessage, isLoading, dispatch]); }; export default useLayout;
use starknet::{ContractAddress, ClassHash, contract_address_const}; use starknet::testing::cheatcode; use super::_cheatcode::handle_cheatcode; mod events; mod l1_handler; mod contract_class; mod tx_info; mod fork; mod storage; #[derive(Drop, Serde, PartialEq, Clone, Debug, Display)] enum CheatTarget { All: (), One: ContractAddress, Multiple: Array<ContractAddress> } #[derive(Drop, Serde, PartialEq, Clone, Debug, Display)] enum CheatSpan { Indefinite: (), TargetCalls: usize, } fn test_selector() -> felt252 { selector!("TEST_CONTRACT_SELECTOR") } fn test_address() -> ContractAddress { contract_address_const::<469394814521890341860918960550914>() } /// Changes the block number for the given target and span. /// - `target` - instance of `CheatTarget` specifying which contracts to roll /// - `block_number` - block number to be set /// - `span` - instance of `CheatSpan` specifying the number of target calls with the cheat applied fn roll(target: CheatTarget, block_number: u64, span: CheatSpan) { validate_cheat_target_and_span(@target, @span); let mut inputs = array![]; target.serialize(ref inputs); span.serialize(ref inputs); inputs.append(block_number.into()); handle_cheatcode(cheatcode::<'roll'>(inputs.span())); } /// Changes the block number for the given target. /// - `target` - instance of `CheatTarget` specifying which contracts to roll /// - `block_number` - block number to be set fn start_roll(target: CheatTarget, block_number: u64) { roll(target, block_number, CheatSpan::Indefinite); } /// Cancels the `roll` / `start_roll` for the given target. /// - `target` - instance of `CheatTarget` specifying which contracts to stop rolling fn stop_roll(target: CheatTarget) { let mut inputs = array![]; target.serialize(ref inputs); handle_cheatcode(cheatcode::<'stop_roll'>(inputs.span())); } /// Changes the caller address for the given target and span. /// - `target` - instance of `CheatTarget` specifying which contracts to prank /// - `caller_address` - caller address to be set /// - `span` - instance of `CheatSpan` specifying the number of target calls with the cheat applied fn prank(target: CheatTarget, caller_address: ContractAddress, span: CheatSpan) { validate_cheat_target_and_span(@target, @span); let mut inputs = array![]; target.serialize(ref inputs); span.serialize(ref inputs); inputs.append(caller_address.into()); handle_cheatcode(cheatcode::<'prank'>(inputs.span())); } /// Changes the caller address for the given target. /// This change can be canceled with `stop_prank`. /// - `target` - instance of `CheatTarget` specifying which contracts to prank /// - `caller_address` - caller address to be set fn start_prank(target: CheatTarget, caller_address: ContractAddress) { prank(target, caller_address, CheatSpan::Indefinite); } /// Cancels the `prank` / `start_prank` for the given target. /// - `target` - instance of `CheatTarget` specifying which contracts to stop pranking fn stop_prank(target: CheatTarget) { let mut inputs = array![]; target.serialize(ref inputs); handle_cheatcode(cheatcode::<'stop_prank'>(inputs.span())); } /// Changes the block timestamp for the given target and span. /// - `target` - instance of `CheatTarget` specifying which contracts to warp /// - `block_timestamp` - block timestamp to be set /// - `span` - instance of `CheatSpan` specifying the number of target calls with the cheat applied fn warp(target: CheatTarget, block_timestamp: u64, span: CheatSpan) { validate_cheat_target_and_span(@target, @span); let mut inputs = array![]; target.serialize(ref inputs); span.serialize(ref inputs); inputs.append(block_timestamp.into()); handle_cheatcode(cheatcode::<'warp'>(inputs.span())); } /// Changes the block timestamp for the given target. /// - `target` - instance of `CheatTarget` specifying which contracts to warp /// - `block_timestamp` - block timestamp to be set fn start_warp(target: CheatTarget, block_timestamp: u64) { warp(target, block_timestamp, CheatSpan::Indefinite); } /// Cancels the `warp` / `start_warp` for the given target. /// - `target` - instance of `CheatTarget` specifying which contracts to stop warping fn stop_warp(target: CheatTarget) { let mut inputs = array![]; target.serialize(ref inputs); handle_cheatcode(cheatcode::<'stop_warp'>(inputs.span())); } /// Changes the sequencer address for the given target and span. /// `target` - instance of `CheatTarget` specifying which contracts to elect /// `sequencer_address` - sequencer address to be set /// `span` - instance of `CheatSpan` specifying the number of target calls with the cheat applied fn elect(target: CheatTarget, sequencer_address: ContractAddress, span: CheatSpan) { validate_cheat_target_and_span(@target, @span); let mut inputs = array![]; target.serialize(ref inputs); span.serialize(ref inputs); inputs.append(sequencer_address.into()); handle_cheatcode(cheatcode::<'elect'>(inputs.span())); } /// Changes the sequencer address for a given target. /// - `target` - instance of `CheatTarget` specifying which contracts to elect /// - `sequencer_address` - sequencer address to be set fn start_elect(target: CheatTarget, sequencer_address: ContractAddress) { elect(target, sequencer_address, CheatSpan::Indefinite); } /// Cancels the `elect` / `start_elect` for the given target. /// - `target` - instance of `CheatTarget` specifying which contracts to stop electing fn stop_elect(target: CheatTarget) { let mut inputs = array![]; target.serialize(ref inputs); handle_cheatcode(cheatcode::<'stop_elect'>(inputs.span())); } /// Mocks contract call to a `function_selector` of a contract at the given address, for `n_times` first calls that are made /// to the contract. /// A call to function `function_selector` will return data provided in `ret_data` argument. /// An address with no contract can be mocked as well. /// An entrypoint that is not present on the deployed contract is also possible to mock. /// Note that the function is not meant for mocking internal calls - it works only for contract entry points. /// - `contract_address` - target contract address /// - `function_selector` - hashed name of the target function (can be obtained with `selector!` macro) /// - `ret_data` - data to return by the function `function_selector` /// - `n_times` - number of calls to mock the function for fn mock_call<T, impl TSerde: core::serde::Serde<T>, impl TDestruct: Destruct<T>>( contract_address: ContractAddress, function_selector: felt252, ret_data: T, n_times: u32 ) { assert!(n_times > 0, "cannot mock_call 0 times, n_times argument must be greater than 0"); let contract_address_felt: felt252 = contract_address.into(); let mut inputs = array![contract_address_felt, function_selector]; CheatSpan::TargetCalls(n_times).serialize(ref inputs); let mut ret_data_arr = ArrayTrait::new(); ret_data.serialize(ref ret_data_arr); ret_data_arr.serialize(ref inputs); handle_cheatcode(cheatcode::<'mock_call'>(inputs.span())); } /// Mocks contract call to a function of a contract at the given address, indefinitely. /// See `mock_call` for comprehensive definition of how it can be used. /// - `contract_address` - targeted contracts' address /// - `function_selector` - hashed name of the target function (can be obtained with `selector!` macro) /// - `ret_data` - data to be returned by the function fn start_mock_call<T, impl TSerde: core::serde::Serde<T>, impl TDestruct: Destruct<T>>( contract_address: ContractAddress, function_selector: felt252, ret_data: T ) { let contract_address_felt: felt252 = contract_address.into(); let mut inputs = array![contract_address_felt, function_selector]; CheatSpan::Indefinite.serialize(ref inputs); let mut ret_data_arr = ArrayTrait::new(); ret_data.serialize(ref ret_data_arr); ret_data_arr.serialize(ref inputs); handle_cheatcode(cheatcode::<'mock_call'>(inputs.span())); } /// Cancels the `mock_call` / `start_mock_call` for the function with given name and contract address. /// - `contract_address` - targeted contracts' address /// - `function_selector` - hashed name of the target function (can be obtained with `selector!` macro) fn stop_mock_call(contract_address: ContractAddress, function_selector: felt252) { let contract_address_felt: felt252 = contract_address.into(); handle_cheatcode( cheatcode::<'stop_mock_call'>(array![contract_address_felt, function_selector].span()) ); } fn replace_bytecode(contract: ContractAddress, new_class: ClassHash) { handle_cheatcode( cheatcode::<'replace_bytecode'>(array![contract.into(), new_class.into()].span()) ); } fn validate_cheat_target_and_span(target: @CheatTarget, span: @CheatSpan) { validate_cheat_span(span); if target == @CheatTarget::All { assert!( span == @CheatSpan::Indefinite, "CheatTarget::All can only be used with CheatSpan::Indefinite" ); } } fn validate_cheat_span(span: @CheatSpan) { assert!(span != @CheatSpan::TargetCalls(0), "CheatSpan::TargetCalls must be greater than 0"); }
package ir.enigma.app.ui.main import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import ir.enigma.app.data.ApiResult import ir.enigma.app.model.Group import ir.enigma.app.repostitory.MainRepository import ir.enigma.app.ui.ApiViewModel import ir.enigma.app.ui.auth.AuthViewModel.Companion.me import ir.enigma.app.ui.auth.AuthViewModel.Companion.token import ir.enigma.app.util.LogType import ir.enigma.app.util.MyLog import ir.enigma.app.util.StructureLayer import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor(private val mainRepository: MainRepository) : ApiViewModel<Unit>() { private val _groupList = MutableStateFlow<List<Group>>(emptyList()) val groupList = _groupList.asStateFlow() val groupToAmount = hashMapOf<Int, MutableState<Double?>>() fun fetchGroups() { viewModelScope.launch { startLoading() when (val result = mainRepository.getGroups(token = token)) { is ApiResult.Success -> { state.value = ApiResult.Success(Unit) result.data!!.distinctUntilChanged().collect { groups -> _groupList.value = groups fetchGroupToAmountData(groups) } MyLog.log( StructureLayer.ViewModel, "MainViewModel", "fetchGroups", LogType.Info, "Groups Fetched: ${result.data}" ) } else -> { MyLog.log( StructureLayer.ViewModel, "MainViewModel", "fetchGroups", LogType.Error, "Error in fetching groups: ${result.message}" ) state.value = ApiResult.Error(result.message ?: "خطا در دریافت گروه ها") } } } } fun fetchGroupToAmountData(groupList: List<Group>) { groupList.forEach { groupToAmount[it.id] = mutableStateOf(null) } viewModelScope.launch { groupList.forEach { val result = mainRepository.getGroupToAmount( token = token, groupId = it.id, userID = me.id ) if (result.data != null) groupToAmount[it.id]?.value = result.data } MyLog.log( StructureLayer.ViewModel, "MainViewModel", "fetchGroupToAmountData", LogType.Info, "fetchGroupToAmountData: $groupToAmount" ) } } }
"use client"; import NoteDeleteModal from "@/components/Note/NoteDeleteModal"; import NoteEditModal from "@/components/Note/NoteEditModal"; import NoteShareModal from "@/components/Note/NoteShareModal"; import { AuthToken } from "@/features/auth/authSlice"; import { NoteData } from "@/services/notes"; import styles from "@/styles/components/Note/NoteCard.module.scss"; import { useState } from "react"; import { AiFillEdit } from "react-icons/ai"; import { BsLink45Deg } from "react-icons/bs"; import { RiDeleteBin2Fill } from "react-icons/ri"; import Modal from "react-modal"; import { QueryObserverResult, RefetchOptions, RefetchQueryFilters, } from "react-query"; import "react-toastify/dist/ReactToastify.css"; export default function NoteCard({ t, note, refetch, notify, authToken, }: { t: Messages["ProfilePage"]["note"]; note: NoteData; refetch: <TPageData>( options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined ) => Promise<QueryObserverResult<any, unknown>>; notify: (text: string, error?: boolean) => void; authToken: AuthToken | null; }) { const [editModalIsOpen, setEditModalIsOpen] = useState(false); const [deleteModalIsOpen, setDeleteModalIsOpen] = useState(false); const [shareModalIsOpen, setShareModalIsOpen] = useState(false); return ( <> <div className={styles.main}> <div className={styles.main__title}> <div> <h1>{note.title}</h1> </div> {note.sharedWithUsers.length !== Number(0) ? ( <div className={styles.main__title__shared}> <BsLink45Deg /> {note.owner_email === authToken?.email ? t.card.sharing : `(${t.card.sharedWithYou} ${note.owner_email})`} </div> ) : null} </div> <div className={styles.main__note}> <p>{note.text}</p> </div> <div className={styles.main__buttons}> {note.owner_email === authToken?.email && ( <button onClick={() => setEditModalIsOpen(true)} style={{ backgroundColor: "#90e0ef" }} > <AiFillEdit /> </button> )} {note.owner_email === authToken?.email && ( <button onClick={() => setShareModalIsOpen(true)} style={{ backgroundColor: "#90e0ef" }} > <BsLink45Deg /> {t.card.shareButton} </button> )} <button onClick={() => setDeleteModalIsOpen(true)} style={{ backgroundColor: "#ef233c" }} > <RiDeleteBin2Fill /> </button> </div> </div> <Modal isOpen={editModalIsOpen} onRequestClose={() => setEditModalIsOpen(false)} ariaHideApp={false} className={styles.main__modal} style={{ overlay: { position: "fixed", backgroundColor: "rgba(0, 0, 0, 0.8)", }, }} > <NoteEditModal t={t.editModal} note={note} setEditModalIsOpen={setEditModalIsOpen} notify={notify} refetch={refetch} /> </Modal> <Modal isOpen={deleteModalIsOpen} onRequestClose={() => setDeleteModalIsOpen(false)} ariaHideApp={false} className={styles.main__modal} style={{ overlay: { position: "fixed", backgroundColor: "rgba(0, 0, 0, 0.8)", }, }} > <NoteDeleteModal t={t.deleteModal} noteId={note.id} setDeleteModalIsOpen={setDeleteModalIsOpen} notify={notify} refetch={refetch} shared={note.owner_email !== authToken?.email} /> </Modal> <Modal isOpen={shareModalIsOpen} onRequestClose={() => setShareModalIsOpen(false)} ariaHideApp={false} className={styles.main__modal} style={{ overlay: { position: "fixed", backgroundColor: "rgba(0, 0, 0, 0.8)", }, }} > <NoteShareModal t={t.shareModal} note={note} setShareModalIsOpen={setShareModalIsOpen} refetch={refetch} /> </Modal> </> ); }
import React from 'react' import { render, fireEvent } from 'react-testing-library' import OfferButton from '../components/OfferButton' describe('OfferButton', () => { const props = { handleClick: jest.fn(), id: 1 } it('renders the OfferButton', () => { const { queryByText } = render(<OfferButton />) const button = queryByText('Offer?') expect(button.innerHTML).toBe('Offer?') }) it('accepts props', () => { const { container } = render(<OfferButton {...props} />) const button = container.querySelectorAll('button') expect(button.length).toBe(1) expect(button[0].id).toBe(props.id.toString()) }) it('fires the click handler function', () => { const { container } = render(<OfferButton {...props} />) const button = container.querySelector('button') fireEvent.click(button) expect(props.handleClick).toHaveBeenCalledTimes(1) }) })
#pragma once #include <iostream> #include <fstream> #include <string> #include <vector> #include <chrono> #include <thread> #include <queue> #include <boost/lockfree/queue.hpp> #include <boost/algorithm/string/join.hpp> namespace bulk { typedef struct { std::string _text; std::chrono::system_clock::time_point _inition_timestamp; } command, *pcommand; class ICommandProcessor { public: ICommandProcessor(std::shared_ptr<ICommandProcessor> next_command_processor = nullptr) : _next_command_processor(next_command_processor) {} virtual ~ICommandProcessor() = default; virtual void start_block() {} virtual void finish_block() {} virtual void command_handler(const command& command) = 0; protected: std::shared_ptr<ICommandProcessor> _next_command_processor; }; class ConsoleInput : public ICommandProcessor { public: ConsoleInput(std::shared_ptr<ICommandProcessor> next_command_processor = nullptr) : ICommandProcessor(next_command_processor), _block_depth(0) {} void command_handler(const command& command) override { if (_next_command_processor) { if (command._text == "{") { if (_block_depth++ == 0) _next_command_processor->start_block(); } else if (command._text == "}") { if (--_block_depth == 0) _next_command_processor->finish_block(); } else if (command._text == "EOF") { _block_depth = 0; _next_command_processor->command_handler(command); } else _next_command_processor->command_handler(command); } } private: size_t _block_depth; }; class ConsoleOutput : public ICommandProcessor { public: // standart queue std::queue<command> log_queue; ConsoleOutput(std::shared_ptr<ICommandProcessor> next_command_processor = nullptr) : ICommandProcessor(next_command_processor) {} void command_handler(const command& command) override { log_queue.push(command); if (_next_command_processor) _next_command_processor->command_handler(command); } }; class FileOutput : public ICommandProcessor { public: // lock-free queue boost::lockfree::queue<pcommand> file_queue{0}; FileOutput(std::shared_ptr<ICommandProcessor> next_command_processor = nullptr) : ICommandProcessor(next_command_processor) {} void command_handler(const command& command) override { if(!command._text.empty()) { file_queue.push(new bulk::command( { command._text, command._inition_timestamp } )); if (_next_command_processor) _next_command_processor->command_handler(command); } } }; class CommandProcessor : public ICommandProcessor { public: CommandProcessor(size_t bulk_max_depth, std::shared_ptr<ICommandProcessor> next_command_processor) : ICommandProcessor(next_command_processor), _bulk_max_depth(bulk_max_depth), _used_block_command(false) {} ~CommandProcessor() { if (!_used_block_command) dump_commands(); } void start_block() override { _used_block_command = true; dump_commands(); } void finish_block() override { _used_block_command = false; dump_commands(); } void command_handler(const command& command) override { _commands_pool.push_back(command); if (_used_block_command) { if (command._text == "EOF") { _used_block_command = false; _commands_pool.clear(); return; } } else { if (command._text == "EOF" || _commands_pool.size() >= _bulk_max_depth) { dump_commands(); return; } } } private: void clear_commands_pool() { _commands_pool.clear(); } void dump_commands() { if (_next_command_processor && !_commands_pool.empty()) { auto commands_concat = concatenate_commands_pool(); auto output = !commands_concat.empty() ? commands_concat : ""; _next_command_processor->command_handler(command{output, _commands_pool[0]._inition_timestamp}); } clear_commands_pool(); } std::string concatenate_commands_pool() { std::vector<std::string> command_vector; for(auto command: _commands_pool) { if (!command._text.empty()) command_vector.push_back(command._text); } return boost::algorithm::join(command_vector, ", "); } size_t _bulk_max_depth; bool _used_block_command; std::vector<command> _commands_pool; }; class ThreadManager { std::shared_ptr<FileOutput> file_stream{nullptr}; std::shared_ptr<ConsoleOutput> console_stream{nullptr}; size_t context{0}; std::atomic<uint8_t> num_terminate_threads {0}; bool keep_running {true}; std::unique_ptr<std::thread> log; std::unique_ptr<std::thread> file1; std::unique_ptr<std::thread> file2; std::string create_filename(pcommand command, int thread_id) { return "bulk_" + std::to_string(context) + "_" + std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(command->_inition_timestamp.time_since_epoch()).count()) + "_" + std::to_string(thread_id) + ".log"; } void file_write(int thread_id) { while (true) { if (keep_running) { pcommand current_command; if (file_stream->file_queue.pop(current_command)) { std::ofstream file(create_filename(current_command, thread_id), std::ofstream::out | std::ios::binary); file << current_command->_text; delete current_command; } std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(1000)); } else { num_terminate_threads += 1; return; } } } void console_write() { while (true) { if (keep_running) { if (!console_stream->log_queue.empty()) { auto commands = console_stream->log_queue.front()._text; auto output = !commands.empty() ? "bulk_" + std::to_string(context) + ": " + commands + "\n" : ""; std::cout << output; console_stream->log_queue.pop(); } std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(1000)); } else { num_terminate_threads += 1; return; } } } public: ThreadManager(std::shared_ptr<FileOutput> fo, std::shared_ptr<ConsoleOutput> co, size_t _context) : file_stream(fo), console_stream(co), context(_context) { log = std::make_unique<std::thread>([&] { console_write(); }); log->detach(); file1 = std::make_unique<std::thread>([&] { file_write(1); }); file1->detach(); file2 = std::make_unique<std::thread>([&] { file_write(2); }); file2->detach(); } ~ThreadManager() { // safe exit keep_running = false; while(num_terminate_threads != 3) std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(1000)); } }; };
<template> <div class="container"> <h2>{{this.post.title_post}}</h2> <h6 v-if="(this.post.content != '')" class="data">Creato il: {{ updateDate }}</h6> <h5 v-if="this.post.category" >Categoria: {{ this.post.category.name }}</h5> <div class="tags" v-for="(tag, index) in post.tags" :key="`tag${index}`"> <span>{{ tag.name }}</span></div> <div class="image"> <img :src="post.image" :alt="post.title"> </div> <p>{{ this.post.content }}</p> <router-link :to="{name: 'blog'}" class="back_to_link">Torna alla lista dei post</router-link> </div> </template> <script> export default { name: "SinglePostInfo", data(){ return{ post:{ title_post: '', category: '', tags: [], content: '', created_at: '', }, apiUrl: 'http://127.0.0.1:8000/api/posts/', slug: this.$route.params.slug, } }, mounted(){ console.log(this.slug); this.getApi() }, computed:{ updateDate(){ const d = new Date(this.post.created_at); let day = d.getDate(); let months = d.getMonth() + 1; const year = d.getFullYear(); if(day < 10) day = "0" + day; if(months < 10) months = "0" + months; return `${day} / ${months} / ${year}`; } }, methods:{ getApi(){ axios.get(this.apiUrl + this.slug) .then(response =>{ this.post = response.data; console.log(this.post); }) } } } </script> <style lang="scss" scoped> .container{ width: 65%; min-height: 70vh; margin: 100px auto; h5{ margin: 15px 0; } p{ margin: 20px 0; } h2{ margin-top: 15px; } .image img{ width: 250px; height: 400px; } .data{ font-style: italic; } .tags{ margin: 20px 0; display: inline-block; span{ margin-right: 10px; } } span{ padding: 8px; background-color: lightseagreen; border: 1px solid black; } .back_to_link{ color: red; text-decoration: underline; &:hover{ text-decoration: underline; } } } </style>
--- id: 62015a5da1c95c358f079ebb title: Passo 37 challengeType: 0 dashedName: step-37 --- # --description-- O pseudosseletor `:first-of-type` é utilizado para focar no primeiro elemento que corresponde ao seletor. Crie um seletor `h1 .flex span:first-of-type` para escolher o primeiro elemento `span` no contêiner `.flex`. Lembre-se de que os elementos `span` estão invertidos visualmente, então esse parecerá ser o segundo elemento na página. Dê ao novo seletor uma propriedade `font-size` de `0.7em` para que ele pareça com um subtítulo. # --hints-- Você deve ter um seletor `h1 .flex span:first-of-type`. ```js assert(new __helpers.CSSHelp(document).getStyle('h1 .flex span:first-of-type')); ``` O seletor `h1 .flex span:first-of-type` deve ter a propriedade `font-size` definida como `0.7em`. ```js assert(new __helpers.CSSHelp(document).getStyle('h1 .flex span:first-of-type')?.getPropertyValue('font-size') === '0.7em'); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Balance Sheet</title> <link rel="stylesheet" href="./styles.css"> </head> <body> <main> <section> <h1> <span class="flex"> <span>AcmeWidgetCorp</span> <span>Balance Sheet</span> </span> </h1> <div id="years" aria-hidden="true"> <span class="year">2019</span> <span class="year">2020</span> <span class="year">2021</span> </div> <div class="table-wrap"> <table> <caption>Assets</caption> <thead> <tr> <td></td> <th><span class="sr-only year">2019</span></th> <th><span class="sr-only year">2020</span></th> <th class="current"><span class="sr-only year">2021</span></th> </tr> </thead> <tbody> <tr class="data"> <th>Cash <span class="description">This is the cash we currently have on hand.</span></th> <td>$25</td> <td>$30</td> <td class="current">$28</td> </tr> <tr class="data"> <th>Checking <span class="description">Our primary transactional account.</span></th> <td>$54</td> <td>$56</td> <td class="current">$53</td> </tr> <tr class="data"> <th>Savings <span class="description">Funds set aside for emergencies.</span></th> <td>$500</td> <td>$650</td> <td class="current">$728</td> </tr> <tr class="total"> <th>Total <span class="sr-only">Assets</span></th> <td>$579</td> <td>$736</td> <td class="current">$809</td> </tr> </tbody> </table> <table> <caption>Liabilities</caption> <thead> <tr> <td></td> <th><span class="sr-only">2019</span></th> <th><span class="sr-only">2020</span></th> <th><span class="sr-only">2021</span></th> </tr> </thead> <tbody> <tr class="data"> <th>Loans <span class="description">The outstanding balance on our startup loan.</span></th> <td>$500</td> <td>$250</td> <td class="current">$0</td> </tr> <tr class="data"> <th>Expenses <span class="description">Annual anticipated expenses, such as payroll.</span></th> <td>$200</td> <td>$300</td> <td class="current">$400</td> </tr> <tr class="data"> <th>Credit <span class="description">The outstanding balance on our credit card.</span></th> <td>$50</td> <td>$50</td> <td class="current">$75</td> </tr> <tr class="total"> <th>Total <span class="sr-only">Liabilities</span></th> <td>$750</td> <td>$600</td> <td class="current">$475</td> </tr> </tbody> </table> <table> <caption>Net Worth</caption> <thead> <tr> <td></td> <th><span class="sr-only">2019</span></th> <th><span class="sr-only">2020</span></th> <th><span class="sr-only">2021</span></th> </tr> </thead> <tbody> <tr class="total"> <th>Total <span class="sr-only">Net Worth</span></th> <td>$-171</td> <td>$136</td> <td class="current">$334</td> </tr> </tbody> </table> </div> </section> </main> </body> </html> ``` ```css span[class~="sr-only"] { border: 0; clip: rect(1px, 1px, 1px, 1px); clip-path: inset(50%); height: 1px; width: 1px; position: absolute; overflow: hidden; white-space: nowrap; padding: 0; margin: -1px; } html { box-sizing: border-box; } body { font-family: sans-serif; color: #0a0a23; } h1 { max-width: 37.25rem; margin: 0 auto; padding: 1.5rem 1.25rem; } h1 .flex { display: flex; flex-direction: column-reverse; gap: 1rem; } --fcc-editable-region-- --fcc-editable-region-- ```
// Copyright 2022-2023 @Polkasafe/polkaSafe-ui authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { AutoComplete, Form, Input } from 'antd'; import { DefaultOptionType } from 'antd/es/select'; import React, { useEffect, useState } from 'react'; import LoadingLottie from 'src/assets/lottie-graphics/Loading'; import { useGlobalUserDetailsContext } from 'src/context/UserDetailsContext'; import AddressComponent from 'src/ui-components/AddressComponent'; import { CheckOutlined, OutlineCloseIcon } from 'src/ui-components/CustomIcons'; import styled from 'styled-components'; import Loader from '../../UserFlow/Loader'; interface Props { className?: string, multisigAddress: string, setMultisigAddress: React.Dispatch<React.SetStateAction<string>> multisigName: string setMultisigName: React.Dispatch<React.SetStateAction<string>> } const NameAddress = ({ className, multisigAddress, setMultisigAddress, multisigName, setMultisigName }: Props) => { const { address, gnosisSafe } = useGlobalUserDetailsContext(); const { multisigAddresses } = useGlobalUserDetailsContext(); const [allSafes, setAllSafes] = useState<DefaultOptionType[]>([]); const [loading, setLoading] = useState<boolean>(false); useEffect(() => { if(!gnosisSafe){ return; } const getAllSafes = async () => { setLoading(true); const safes = await gnosisSafe.getAllSafesByOwner(address); const multiSigs = multisigAddresses.map(item => item.address); const filteredSafes = safes?.safes.filter((item:any) => !multiSigs.includes(item)) || []; setMultisigAddress(filteredSafes[0]); if(filteredSafes?.length > 0){ setAllSafes(filteredSafes.map((address) => ({ label: <AddressComponent onlyAddress address={address} />, value: address }))); } setLoading(false); }; getAllSafes(); }, [address, multisigAddresses, gnosisSafe, setMultisigAddress]); return ( <div className={className}> <div className='flex flex-col items-center w-[800px] h-[400px]'> <div className="flex justify-around items-center mb-10 w-full"> <div className='flex flex-col items-center text-white justify-center'> <div className='rounded-lg bg-primary w-9 h-9 mb-2 flex items-center justify-center'><CheckOutlined /></div> <p>Select Network</p> </div> <Loader className='bg-primary h-[2px] w-[80px]' /> <div className='flex flex-col text-white items-center justify-center'> <div className='rounded-lg bg-primary w-9 h-9 mb-2 flex items-center justify-center'>2</div> <p>Name & Address</p> </div> <Loader className='bg-bg-secondary h-[2px] w-[80px]' /> <div className='flex flex-col text-white items-center justify-center'> <div className='rounded-lg bg-highlight text-primary w-9 h-9 mb-2 flex items-center justify-center'>3</div> <p>Owners</p> </div> <Loader className='bg-bg-secondary h-[2px] w-[80px]' /> <div className='flex flex-col text-white items-center justify-center'> <div className='rounded-lg bg-highlight text-primary w-9 h-9 mb-2 flex items-center justify-center'>4</div> <p>Review</p> </div> </div> <div> {loading ? <LoadingLottie message='Fetching Your Multisigs' width={250} /> : <Form className='my-0 w-[560px] mt-10' > <div className="flex flex-col gap-y-3"> <label className="text-primary text-xs leading-[13px] font-normal" htmlFor="name" > Safe Name </label> <Form.Item name="name" rules={[]} className='border-0 outline-0 my-0 p-0' > <Input placeholder="my-polka-safe" className="text-sm font-normal m-0 leading-[15px] border-0 outline-0 p-3 text-white placeholder:text-[#505050] bg-bg-secondary rounded-lg" id="name" value={multisigName} onChange={(e) => setMultisigName(e.target.value)} /> </Form.Item> </div> <div className="flex flex-col gap-y-3 mt-5"> <label className="text-primary text-xs leading-[13px] font-normal" htmlFor="address" > Safe Address* </label> <Form.Item name="Address" rules={[{ required: true }]} className='border-0 outline-0 my-0 p-0' help={!(multisigAddress) && 'Please enter a Valid Address'} validateStatus={!multisigAddress || !(multisigAddress) ? 'error' : 'success'} > <AutoComplete onChange={(value) => setMultisigAddress(value)} value={multisigAddress} allowClear clearIcon={<OutlineCloseIcon className='text-primary w-2 h-2' />} notFoundContent={!multisigAddress && <span className='text-white'>We can&apos;t find your multisigs, please enter multisig address.</span>} placeholder="Unique Safe Address" id="Address" options={allSafes} /> </Form.Item> </div> </Form> } </div> </div> </div> ); }; export default styled(NameAddress)` .ant-select input { font-size: 14px !important; font-style: normal !important; line-height: 15px !important; border: 0 !important; outline: 0 !important; background-color: #24272E !important; border-radius: 8px !important; color: white !important; padding: 12px !important; display: block !important; height: auto !important; } .ant-select-selector { border: none !important; height: 40px !important; box-shadow: none !important; } .ant-select { height: 40px !important; } .ant-select-selection-search { inset: 0 !important; } .ant-select-selection-placeholder{ color: #505050 !important; z-index: 100; display: flex !important; align-items: center !important; } `;
package com.bachlinh.order.web.dto.resp; import com.fasterxml.jackson.annotation.JsonProperty; public class AdminProductResp { @JsonProperty("id") private String id; @JsonProperty("name") private String name; @JsonProperty("price") private String price; @JsonProperty("size") private String size; @JsonProperty("color") private String color; @JsonProperty("taobao_url") private String taobaoUrl; @JsonProperty("description") private String description; @JsonProperty("orderPoint") private String orderPoint; @JsonProperty("enable") private String enable; @JsonProperty("pictures") private String[] pictures; @JsonProperty("categories") private String[] categories; public AdminProductResp() { } public String getId() { return this.id; } public String getName() { return this.name; } public String getPrice() { return this.price; } public String getSize() { return this.size; } public String getColor() { return this.color; } public String getTaobaoUrl() { return this.taobaoUrl; } public String getDescription() { return this.description; } public String getOrderPoint() { return this.orderPoint; } public String getEnable() { return this.enable; } public String[] getPictures() { return this.pictures; } public String[] getCategories() { return this.categories; } @JsonProperty("id") public void setId(String id) { this.id = id; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("price") public void setPrice(String price) { this.price = price; } @JsonProperty("size") public void setSize(String size) { this.size = size; } @JsonProperty("color") public void setColor(String color) { this.color = color; } @JsonProperty("taobao_url") public void setTaobaoUrl(String taobaoUrl) { this.taobaoUrl = taobaoUrl; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } @JsonProperty("orderPoint") public void setOrderPoint(String orderPoint) { this.orderPoint = orderPoint; } @JsonProperty("enable") public void setEnable(String enable) { this.enable = enable; } @JsonProperty("pictures") public void setPictures(String[] pictures) { this.pictures = pictures; } @JsonProperty("categories") public void setCategories(String[] categories) { this.categories = categories; } }
import { PaperBaseScene } from "./PaperBaseScene"; export default class Invaders extends PaperBaseScene { player: Phaser.Physics.Arcade.Sprite; keys: Phaser.Types.Input.Keyboard.CursorKeys; enemyVelocity: number = 65; enemyGroup: Phaser.Physics.Arcade.Group; bulletGroup: Phaser.Physics.Arcade.Group; constructor() { super("Invaders"); } create(data: any) { super.create(data); super.startTimer(); switch (this.difficulty) { case 2: this.enemyVelocity = 100; break; case 3: this.enemyVelocity = 175; break; default: this.enemyVelocity = 80; break; } this.physics.world.setBoundsCollision(true, true, true, false); this.enemyGroup = this.physics.add.group({ key: "invader", collideWorldBounds: true, frameQuantity: 24, velocityY: this.enemyVelocity, gridAlign: { width: 8, height: 3, cellHeight: 64, cellWidth: 64, }, setOrigin: { x: 0, y: 0 }, }); this.bulletGroup = this.physics.add.group({ maxSize: 10, velocityY: -400, setScale: { x: 0.2, y: 0.2 }, key: "projectile", frameQuantity: 0, }); this.physics.add.collider( this.bulletGroup, this.enemyGroup, (bullet, enemy) => { enemy.destroy(); bullet.destroy(); } ); this.player = this.physics.add .sprite(260, 690, "baphomet") .setScale(0.5) .setOrigin(0.5) .setRotation(Math.PI) .setCollideWorldBounds(false); if (this.input.keyboard) { this.keys = this.input.keyboard.createCursorKeys(); this.input.keyboard.on("keydown-SPACE", () => { this.player.play("baphomet-shoot"); if (this.bulletGroup.countActive() < 10) { this.bulletGroup.createFromConfig({ key: "projectile", setXY: { x: this.player.x, y: this.player.y - 32 }, setScale: { x: 0.2, y: 0.2 }, }); } }); } this.physics.add.collider(this.player, this.enemyGroup, () => super.onGameOver() ); } update() { //@ts-expect-error - not now TypeScript!! if (this.leftArrow.isDown && this.player.body?.velocity.x > -350 || this.keyA.isDown && this.player.body?.velocity.x > -350) { //@ts-expect-error - not now TypeScript!! if (this.player.body?.velocity.x > 0) this.player.setVelocityX(0); this.player.setAccelerationX(-250); //@ts-expect-error - not now TypeScript!! } else if (this.leftArrow.isDown && this.player.body?.velocity.x < 350 || this.keyD.isDown && this.player.body?.velocity.x < 350) { //@ts-expect-error - not now TypeScript!! if (this.player.body?.velocity.x < -0) this.player.setVelocityX(-0); this.player.setAccelerationX(250); } else { this.player.setAccelerationX(0); } if (this.player.x < 0) this.player.x = 650; if (this.player.x > 650) this.player.x = 0; if (this.enemyGroup.countActive() === 0) { super.onWin(); } this.bulletGroup.getChildren().forEach((bullet) => { if (bullet.body && bullet.body.position.y < 0) bullet.destroy(); }); this.enemyGroup.getChildren().forEach((enemy) => { if (enemy.body && enemy.body.position.y > 740) enemy.body.position.y = 0; }); } }
import json from datetime import timedelta, datetime, UTC from unittest.mock import patch from django.apps import apps from django.test import SimpleTestCase, TestCase from django.utils.timezone import now from freezegun import freeze_time from gcp_pilot.exceptions import DeletedRecently from gcp_pilot.mocker import patch_auth from django_cloud_tasks import exceptions from django_cloud_tasks.tasks import Task, TaskMetadata from django_cloud_tasks.tests import tests_base from django_cloud_tasks.tests.tests_base import eager_tasks from sample_app import tasks class TasksTest(SimpleTestCase): def setUp(self): super().setUp() Task._get_tasks_client.cache_clear() patch_output = patch("django_cloud_tasks.tasks.TaskMetadata.from_task_obj") patch_output.start() self.addCleanup(patch_output.stop) auth = patch_auth() auth.start() self.addCleanup(auth.stop) def tearDown(self): super().tearDown() Task._get_tasks_client.cache_clear() def patch_push(self, **kwargs): return patch("gcp_pilot.tasks.CloudTasks.push", **kwargs) @property def app_config(self): return apps.get_app_config("django_cloud_tasks") def test_registered_tasks(self): expected_tasks = { "CalculatePriceTask", "FailMiserablyTask", "OneBigDedicatedTask", "RoutineExecutorTask", "SayHelloTask", "SayHelloWithParamsTask", "DummyRoutineTask", "RoutineReverterTask", "ParentCallingChildTask", "ExposeCustomHeadersTask", "PublishPersonTask", "NonCompliantTask", } self.assertEqual(expected_tasks, set(self.app_config.on_demand_tasks)) expected_tasks = {"SaySomethingTask"} self.assertEqual(expected_tasks, set(self.app_config.periodic_tasks)) expected_tasks = {"PleaseNotifyMeTask", "ParentSubscriberTask"} self.assertEqual(expected_tasks, set(self.app_config.subscriber_tasks)) def test_get_task(self): received_task = self.app_config.get_task(name="SayHelloWithParamsTask") expected_task = tasks.SayHelloWithParamsTask self.assertEqual(expected_task, received_task) def test_get_tasks(self): from another_app import tasks as another_app_tasks from django_cloud_tasks import tasks as djc_tasks demand_tasks = [ djc_tasks.RoutineReverterTask, djc_tasks.RoutineExecutorTask, tasks.CalculatePriceTask, tasks.ParentCallingChildTask, tasks.ExposeCustomHeadersTask, tasks.FailMiserablyTask, tasks.SayHelloTask, tasks.SayHelloWithParamsTask, tasks.PublishPersonTask, tasks.DummyRoutineTask, another_app_tasks.deep_down_tasks.one_dedicated_task.OneBigDedicatedTask, another_app_tasks.deep_down_tasks.one_dedicated_task.NonCompliantTask, ] subscriber_tasks = [ tasks.PleaseNotifyMeTask, tasks.ParentSubscriberTask, ] periodic_tasks = [tasks.SaySomethingTask] expected_task = demand_tasks + subscriber_tasks + periodic_tasks received_task = self.app_config.get_tasks() self.assertEqual(expected_task, received_task) received_task = self.app_config.get_tasks(only_periodic=True) self.assertEqual(periodic_tasks, received_task) received_task = self.app_config.get_tasks(only_subscriber=True) self.assertEqual(subscriber_tasks, received_task) received_task = self.app_config.get_tasks(only_demand=True) self.assertEqual(demand_tasks, received_task) def test_get_abstract_task(self): with self.assertRaises(expected_exception=exceptions.TaskNotFound): self.app_config.get_task(name="PublisherTask") def test_get_task_not_found(self): with self.assertRaises(exceptions.TaskNotFound): self.app_config.get_task(name="PotatoTask") def test_task_async(self): with ( patch_auth(), self.patch_push() as push, ): tasks.CalculatePriceTask.asap(price=30, quantity=4, discount=0.2) expected_call = dict( queue_name="tasks", url="http://localhost:8080/tasks/CalculatePriceTask", payload=json.dumps({"price": 30, "quantity": 4, "discount": 0.2}), headers={"X-CloudTasks-Projectname": "potato-dev"}, ) push.assert_called_once_with(**expected_call) def test_task_async_only_once(self): with self.patch_push() as push: tasks.FailMiserablyTask.asap(magic_number=666) expected_call = dict( task_name="FailMiserablyTask", queue_name="tasks", url="http://localhost:8080/tasks/FailMiserablyTask", payload=json.dumps({"magic_number": 666}), unique=False, headers={"X-CloudTasks-Projectname": "potato-dev"}, ) push.assert_called_once_with(**expected_call) def test_task_async_reused_queue(self): effects = [DeletedRecently("Queue tasks"), None] with self.patch_push(side_effect=effects) as push: tasks.CalculatePriceTask.asap(price=30, quantity=4, discount=0.2) expected_call = dict( queue_name="tasks", url="http://localhost:8080/tasks/CalculatePriceTask", payload=json.dumps({"price": 30, "quantity": 4, "discount": 0.2}), headers={"X-CloudTasks-Projectname": "potato-dev"}, ) expected_backup_call = expected_call expected_backup_call["queue_name"] += "--temp" self.assertEqual(2, push.call_count) push.assert_any_call(**expected_call) push.assert_called_with(**expected_backup_call) def test_task_eager(self): with eager_tasks(): response = tasks.CalculatePriceTask.asap(price=30, quantity=4, discount=0.2) self.assertGreater(response, 0) def test_task_later_int(self): with self.patch_push() as push: task_kwargs = dict(price=30, quantity=4, discount=0.2) tasks.CalculatePriceTask.later(eta=1800, task_kwargs=task_kwargs) expected_call = dict( delay_in_seconds=1800, queue_name="tasks", url="http://localhost:8080/tasks/CalculatePriceTask", payload=json.dumps({"price": 30, "quantity": 4, "discount": 0.2}), headers={"X-CloudTasks-Projectname": "potato-dev"}, ) push.assert_called_once_with(**expected_call) def test_task_later_delta(self): delta = timedelta(minutes=42) with self.patch_push() as push: task_kwargs = dict(price=30, quantity=4, discount=0.2) tasks.CalculatePriceTask.later(eta=delta, task_kwargs=task_kwargs) expected_call = dict( delay_in_seconds=2520, queue_name="tasks", url="http://localhost:8080/tasks/CalculatePriceTask", payload=json.dumps({"price": 30, "quantity": 4, "discount": 0.2}), headers={"X-CloudTasks-Projectname": "potato-dev"}, ) push.assert_called_once_with(**expected_call) @freeze_time("2020-01-01T00:00:00") def test_task_later_time(self): some_time = now() + timedelta(minutes=100) with self.patch_push() as push: task_kwargs = dict(price=30, quantity=4, discount=0.2) tasks.CalculatePriceTask.later(eta=some_time, task_kwargs=task_kwargs) expected_call = dict( delay_in_seconds=60 * 100, queue_name="tasks", url="http://localhost:8080/tasks/CalculatePriceTask", payload=json.dumps({"price": 30, "quantity": 4, "discount": 0.2}), headers={"X-CloudTasks-Projectname": "potato-dev"}, ) push.assert_called_once_with(**expected_call) def test_task_later_error(self): with self.patch_push() as push: with self.assertRaisesRegex(expected_exception=ValueError, expected_regex="Unsupported schedule"): task_kwargs = dict(price=30, quantity=4, discount=0.2) tasks.CalculatePriceTask.later(eta="potato", task_kwargs=task_kwargs) push.assert_not_called() def test_singleton_client_on_task(self): # we have a singleton if it calls the same task twice with ( patch("django_cloud_tasks.tasks.TaskMetadata.from_task_obj"), patch("django_cloud_tasks.tasks.task.CloudTasks") as client, ): for _ in range(10): tasks.CalculatePriceTask.asap() client.assert_called_once_with() self.assertEqual(10, client().push.call_count) def test_singleton_client_creates_new_instance_on_new_task(self): with ( patch("django_cloud_tasks.tasks.TaskMetadata.from_task_obj"), patch("django_cloud_tasks.tasks.task.CloudTasks") as client, ): tasks.SayHelloTask.asap() tasks.CalculatePriceTask.asap() self.assertEqual(2, client.call_count) class SayHelloTaskTest(TestCase, tests_base.RoutineTaskTestMixin): @property def task(self): return tasks.SayHelloTask class SayHelloWithParamsTaskTest(TestCase, tests_base.RoutineTaskTestMixin): @property def task(self): return tasks.SayHelloWithParamsTask @property def task_run_params(self): return {"spell": "Obliviate"} class TestTaskMetadata(TestCase): some_date = datetime(1990, 7, 19, 15, 30, 42, tzinfo=UTC) @property def sample_headers(self) -> dict: return { "X-Cloudtasks-Taskexecutioncount": 7, "X-Cloudtasks-Taskretrycount": 1, "X-Cloudtasks-Tasketa": str(self.some_date.timestamp()), "X-Cloudtasks-Projectname": "wizard-project", "X-Cloudtasks-Queuename": "wizard-queue", "X-Cloudtasks-Taskname": "hp-1234567", } @property def sample_metadata(self) -> TaskMetadata: return TaskMetadata( project_id="wizard-project", queue_name="wizard-queue", task_id="hp-1234567", execution_number=7, dispatch_number=1, eta=self.some_date, is_cloud_scheduler=False, ) @property def sample_cloud_scheduler_metadata(self) -> TaskMetadata: return TaskMetadata( project_id="wizard-project", queue_name="wizard-queue", task_id="hp-1234567", execution_number=7, dispatch_number=1, eta=self.some_date, is_cloud_scheduler=True, cloud_scheduler_job_name="wizard-api--LevitationTask", cloud_scheduler_schedule_time=datetime(2023, 11, 3, 15, 27, 0, tzinfo=UTC), ) def test_create_from_headers(self): metadata = TaskMetadata.from_headers(headers=self.sample_headers) self.assertEqual(7, metadata.execution_number) self.assertEqual(1, metadata.dispatch_number) self.assertEqual(2, metadata.attempt_number) self.assertEqual(self.some_date, metadata.eta) self.assertEqual("wizard-project", metadata.project_id) self.assertEqual("wizard-queue", metadata.queue_name) self.assertEqual("hp-1234567", metadata.task_id) self.assertFalse(metadata.is_cloud_scheduler) self.assertIsNone(metadata.cloud_scheduler_job_name) self.assertIsNone(metadata.cloud_scheduler_schedule_time) def test_create_from_cloud_schedule_headers(self): metadata = TaskMetadata.from_headers( headers=self.sample_headers | { "X-Cloudscheduler": "true", "X-Cloudscheduler-Scheduletime": "2023-11-03T08:27:00-07:00", "X-Cloudscheduler-Jobname": "wizard-api--LevitationTask", } ) self.assertTrue(metadata.is_cloud_scheduler) self.assertEqual("wizard-api--LevitationTask", metadata.cloud_scheduler_job_name) self.assertEqual(datetime(2023, 11, 3, 15, 27, 0, tzinfo=UTC), metadata.cloud_scheduler_schedule_time) def test_build_headers(self): headers = self.sample_metadata.to_headers() self.assertEqual("7", headers["X-Cloudtasks-Taskexecutioncount"]) self.assertEqual("1", headers["X-Cloudtasks-Taskretrycount"]) self.assertEqual(str(int(self.some_date.timestamp())), headers["X-Cloudtasks-Tasketa"]) self.assertEqual("wizard-project", headers["X-Cloudtasks-Projectname"]) self.assertEqual("wizard-queue", headers["X-Cloudtasks-Queuename"]) self.assertEqual("hp-1234567", headers["X-Cloudtasks-Taskname"]) self.assertNotIn("X-Cloudscheduler", headers) self.assertNotIn("X-Cloudscheduler-Scheduletime", headers) self.assertNotIn("X-Cloudscheduler-Jobname", headers) def test_build_cloud_scheduler_headers(self): headers = self.sample_cloud_scheduler_metadata.to_headers() self.assertEqual("7", headers["X-Cloudtasks-Taskexecutioncount"]) self.assertEqual("1", headers["X-Cloudtasks-Taskretrycount"]) self.assertEqual(str(int(self.some_date.timestamp())), headers["X-Cloudtasks-Tasketa"]) self.assertEqual("wizard-project", headers["X-Cloudtasks-Projectname"]) self.assertEqual("wizard-queue", headers["X-Cloudtasks-Queuename"]) self.assertEqual("hp-1234567", headers["X-Cloudtasks-Taskname"]) self.assertEqual("true", headers["X-Cloudscheduler"]) self.assertEqual("2023-11-03T15:27:00+00:00", headers["X-Cloudscheduler-Scheduletime"]) self.assertEqual("wizard-api--LevitationTask", headers["X-Cloudscheduler-Jobname"]) def test_comparable(self): reference = self.sample_metadata metadata_a = TaskMetadata.from_headers(self.sample_headers) self.assertEqual(reference, metadata_a) metadata_b = TaskMetadata.from_headers(self.sample_headers) metadata_b.execution_number += 1 self.assertNotEqual(reference, metadata_b) not_metadata = True self.assertNotEqual(reference, not_metadata)
import { auth, firestore, storage } from "firebase-admin"; import { FieldValue } from "firebase-admin/firestore"; import * as functions from "firebase-functions"; const client = require("firebase-tools"); export const deleteAccountHandler = async (data, context) => { // Validate auth status and args if (!context || !context.auth || !context.auth.uid) { throw new functions.https.HttpsError( "unauthenticated", "deleteAccount must be called while authenticated." ); } const path = `users/${context.auth.uid}`; // Delete profile pic const bucket = storage().bucket(); await bucket.file(path).delete({ ignoreNotFound: true }); // Delete all user data await recursiveDelete(path); // Delete user authentication account await auth().deleteUser(context.auth.uid); }; export const deletePinHandler = async ({ pid }, context) => { // Validate auth status and args if (!context || !context.auth || !context.auth.uid) { throw new functions.https.HttpsError( "unauthenticated", "deletePin must be called while authenticated." ); } if (!pid) { throw new functions.https.HttpsError( "unauthenticated", "deletePin must be called with proper arguments." ); } const userRef = firestore().collection("users").doc(context.auth.uid); const droppedRef = userRef.collection("dropped").doc("dropped"); const pinRef = firestore().collection("pins").doc(pid); // Validate pin existence and author const pinData = await pinRef.get(); if (!pinData.exists || !pinData.get("authorUID") === context.auth.uid) { throw new functions.https.HttpsError( "unauthenticated", "deletePin must be called on a pin that you have dropped." ); } // Delete pin image if it exists if (pinData.get("type") === "IMAGE") { console.log("deleting image"); const bucket = storage().bucket(); await bucket.file(`pins/${pid}`).delete(); } // Delete all comments await recursiveDelete(`pins/${pid}/comments`); const batch = firestore().batch(); batch.update(droppedRef, { [pinRef.id]: FieldValue.delete() }); batch.update(userRef, { numPinsDropped: FieldValue.increment(-1) }); batch.delete(pinRef); await batch.commit(); }; // Run a recursive delete on the given document or collection path. const recursiveDelete = (path) => client.firestore.delete(path, { project: process.env.GCLOUD_PROJECT, recursive: true, force: true, });
package com.ticketmaster.example.commons.persistence.model; import java.util.Date; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; /** * * Acting as a entity listener to any type of model entity. * Annotated with PrePersist and PreUpdate. * It always being called before persisting and updating any model entity. * @see @EntityListeners,@PrePersist,@PreUpdate */ public class ModelListener { /** * Responsible for setting dates such as last update,created * @param modelBase represents model entity being persisted OR updated */ @PrePersist @PreUpdate public void setDates(IModelBase modelBase) { Date now = new Date(); if (modelBase.getDateTimeCreated() == null) { modelBase.setDateTimeCreated(now); } modelBase.setDateTimeUpdated(now); } }
<!-- INDEX É A PAGINA INICIAL--> <!DOCTYPE html> <!-- indica ao navegador para usar a versão recente--> <html> <!-- pai/raiz de todas as tags--> <head> <!-- Manter informações da pagina--> <meta charset="utf-8"/> <!-- Uso de caracteres especiais --> <title>Página Inicial</title> <!-- Meta tags--> <meta name="description" content="Uma página para estudar HTML" /> <meta name="author" content="rodrigo araujo" /> <meta name="keywords" content="html,estudo" /> </head> <body> <!-- Contém a parte visível da página--> <p>Olá coders</p> <p title="Boas vindas">Tudo bem?</p> <button title="Clique aqui para continuar">Clique</button> <p hidden>Ué, sumiu</p> <!-- hidden ocuta--> <p> Lorem ipsum dolor sit amet. <!-- lorem + o numero de palavras para criar um parágrafo fake--> </p> <h1>Introdução ao HTML</h1> <h2>Meta tags</h2> <h3>h3</h3> <h4>h4</h4> <h5>h5</h5> <h6>h6</h6> <img src="./img/venezaItalia.webp" width="300" height="300" alt="Rio de Veneza"/> <img src="https://cdn.pixabay.com/photo/2022/07/25/15/18/cat-7344042_960_720.jpg" width="300" height="300" alt="Um gatinho"/> <br> <a href="./ajuda.html">Ir para ajuda</a> </body> </html>
-- Created on: 1991-05-06 -- Created by: Laurent PAINNOT -- Copyright (c) 1991-1999 Matra Datavision -- Copyright (c) 1999-2014 OPEN CASCADE SAS -- -- This file is part of Open CASCADE Technology software library. -- -- This library is free software; you can redistribute it and/or modify it under -- the terms of the GNU Lesser General Public License version 2.1 as published -- by the Free Software Foundation, with special exception defined in the file -- OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT -- distribution for complete text of the license and disclaimer of any warranty. -- -- Alternatively, this file may be used under the terms of Open CASCADE -- commercial license or contractual agreement. deferred class Function from math ---Purpose: This abstract class describes the virtual functions -- associated with a Function of a single variable. is Value(me: in out; X: Real; F: out Real) ---Purpose: Computes the value of the function <F> for a given value of -- variable <X>. -- returns True if the computation was done successfully, -- False otherwise. returns Boolean is deferred; GetStateNumber(me: in out) ---Purpose: returns the state of the function corresponding to the -- latest call of any methods associated with the function. -- This function is called by each of the algorithms -- described later which defined the function Integer -- Algorithm::StateNumber(). The algorithm has the -- responsibility to call this function when it has found -- a solution (i.e. a root or a minimum) and has to maintain -- the association between the solution found and this -- StateNumber. -- Byu default, this method returns 0 (which means for the -- algorithm: no state has been saved). It is the -- responsibility of the programmer to decide if he needs -- to save the current state of the function and to return -- an Integer that allows retrieval of the state. returns Integer is virtual; end Function;
#ifndef ALARMTOQUEUE_H #define ALARMTOQUEUE_H /******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: AlarmToQueue.h,v 1.1 2011/06/22 20:56:15 acaproni Exp $" * * who when what * -------- -------- ---------------------------------------------- * acaproni 2011-06-18 created */ #include <string> #include "Properties.h" namespace acsalarm { /** * An alarm to put in the queue ready to be published */ class AlarmToQueue { private: // FaultFamily std::string m_FF; // FaultMember std::string m_FM; // FaultCode int m_FC; // user properties Properties m_alarmProps; // The state active/terminate bool m_active; public: /** * Constructor * * @param fF Fault family * @param fM Fault member * @param fC Fault code * @param activestate true means alarm to activate, false alarm to terminate */ AlarmToQueue(std::string fF, std::string fM, int fC, bool activestate); /** * Constructor * * @param fF Fault family * @param fM Fault member * @param fC Fault code * @param props The user properties * @param activestate true means alarm to activate, false alarm to terminate */ AlarmToQueue(std::string fF, std::string fM, int fC, Properties props, bool activestate); bool isActive() const { return m_active; } Properties getAlarmProps() const { return m_alarmProps; } int getFC() const { return m_FC; } std::string getFF() const { return m_FF; } std::string getFM() const { return m_FM; } }; }; #endif /*!ALARMTOQUEUE_H*/
import UnionFind from "./UnionFind"; const minCostToConnectCities = (n: number, connections: number[][]): number => { const uf = new UnionFind(n); // Sort connections by cost connections.sort((a,b) => a[2] - b[2]); let totalCost = 0; connections.forEach((connection) => { if(!uf.connected(connection[0]-1, connection[1]-1)){ uf.union(connection[0]-1, connection[1]-1) totalCost += connection[2]; } }) return totalCost; } const cities = 4; const connections = [ [1, 2, 5], // Connect city 1 and city 2 with cost 5 [1, 3, 8], // Connect city 1 and city 3 with cost 8 [2, 3, 6], // Connect city 2 and city 3 with cost 6 [2, 4, 7], // Connect city 2 and city 4 with cost 7 [3, 4, 9], // Connect city 3 and city 4 with cost 9 ]; const minimumCost = minCostToConnectCities(cities, connections); console.log("Minimum cost to connect all cities:", minimumCost);
import styles from "./Trending.module.css"; import Header from "../../components/Header/Header"; import Sidebar from "../../components/Sidebar/Sidebar"; import Post from "../../components/Post/Post"; import { useEffect, useState } from "react"; import { useGetTrending } from "../../hooks/useGetTrending.js"; import axios from "axios"; function Trending() { const [logged, setLogged] = useState(true); const { loading, trending, userDetails } = useGetTrending(); useEffect(() => { console.log("HERE"); console.log(document.cookie); if (!document.cookie.includes("token")) { setLogged(false); } }, []); useEffect(() => { console.log(trending); // console.log(userDetails); }, [trending]); return ( <div className={styles.Home}> <Header className={styles.navbar} loggedIn={logged} /> <div className={styles.body}> <Sidebar page={1} className={styles.Sidebar} loggedIn={logged} /> <div className={styles.content}> {trending.map((post) => ( <Post key={post.post.id} post={{ title: post.post && post.post.post.title ? post.post.post.title : "No Title", description: post.post && post.post.post.content ? post.post.post.content : "No Content", username: post.user.username, community: post.community.name, upvotes: post.post.upvotes, downvotes: post.post.downvotes, }} /> ))} </div> </div> </div> ); } export default Trending;
import { Field, InputType } from '@nestjs/graphql' import { IsEmail } from 'class-validator' import { IsExistingByUuid } from 'src/commons/validators/is-existing-by-uuid.validator' import { IsStrongPassword } from '../../commons/decorators/is-strong-password.decorator' @InputType() export class UserCreateInput { @Field(() => String) name: string @Field(() => String) @IsEmail() email: string @Field(() => String) @IsStrongPassword({ message: 'Your password should be between 8-20 characters long and should contain ' + 'at least one lowercase and uppercase letter, one special character and one digit.', }) password: string } @InputType() export class UserDeleteInput { @Field(() => String) @IsExistingByUuid() uuid: string }
import React, { useEffect, useMemo, useState } from 'react'; import { Formik, Form as FormikForm, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; import { Button, Form, Col, InputGroup, Modal } from 'react-bootstrap'; import { useLocalStorage } from '@uidotdev/usehooks'; import { useNavigate } from 'react-router-dom'; import { UnauthenticatedTemplate, useMsal } from '@azure/msal-react'; import { handleLogin, handleSignup } from '../../services/authService'; import WhiteLogo from '../../assets/images/C2Zero-white-Logo.png'; import FaqAccordian from './FaqAccordian'; import Closebtn from '../../assets/images/Close.png'; import { createPaymentIntent } from '../../services/stripeService'; import { calculateCarbonAmountPriceGivenWeight } from '../../services/eCertificateService'; import { useMediaQuery } from 'react-responsive'; import ForwardArrow from '../../assets/images/arrow-forward.png'; import warningIcon from '../../assets/images/warning.png'; import { toast } from 'react-toastify'; const BuyCarbonCertificateForm = () => { const { instance } = useMsal(); const navigate = useNavigate(); const [showLoginModal, setShowLoginModal] = useState(false); const [overlayWidth, setOverlayWidth] = useState(0); const [paymentIntentAPIError, setPaymentIntentAPIError] = useState(false); const [buyECertificateDetails, saveBuyECertificateDetails] = useLocalStorage('buyECertificateDetails', null); const [guestUserEmail, saveGuestUserEmail] = useLocalStorage('guestUserEmail', null); const [isECertificateGifting, setIsEcertificateGifting] = useState(false); const applicationUserEmail = guestUserEmail ? guestUserEmail : instance.getActiveAccount()?.idTokenClaims.email; const isTabletOrMobile = useMediaQuery({ query: '(max-width: 768px)' }); const [priceCalcAPIError, setPriceCalcAPIError] = useState(false); const validationSchema = useMemo(() => { if (!isECertificateGifting) { return Yup.object().shape({ carbonQuantity: Yup.number().min(0.001, 'Minimum quantity should be 0.001 Kg').required('Quantity is required'), acceptTerms: Yup.boolean().oneOf([true], 'You must accept the terms of service and privacy policy') }); } else { return Yup.object().shape({ carbonQuantity: Yup.number().min(0.001, 'Minimum quantity should be 0.001 Kg').required('Quantity is required'), email: Yup.string() .email('Invalid email') .required('Email is required') .test( 'isNotApplicationUserEmail', 'The email cannot be the same as that of the currently logged-in user.', function (value) { if (isECertificateGifting && value === applicationUserEmail) { return false; } return true; } ), confirmEmail: Yup.string() .email('Invalid email') .oneOf([Yup.ref('email')], 'Emails should match') .required('Email is required'), acceptTerms: Yup.boolean().oneOf([true], 'You must accept the terms of service and privacy policy') }); } }, [isECertificateGifting]); const handleJoinc2zero = () => { handleSignup(instance); }; const handleSignIn = () => { handleLogin(instance); }; const handleContineAsGuest = (formValues) => { const { email, confirmEmail, ...restFormValues } = formValues; saveBuyECertificateDetails(restFormValues); navigate('/OrderHistory'); }; const openOverlay = () => { setOverlayWidth(100); }; const openOverlayMobile = () => { setOverlayWidth(100); }; const closeOverlay = () => { setOverlayWidth(0); }; useEffect(() => { if (priceCalcAPIError) toast.error('Error in price calculation!', { onClose: () => setPriceCalcAPIError(null) }); if (paymentIntentAPIError) toast.error('Error receiving payment intent!', { onClose: () => setPaymentIntentAPIError(null) }); }, [priceCalcAPIError, paymentIntentAPIError]); const checkoutClickHandler = async (dirty, validateForm, setTouched) => { await setTouched({ carbonQuantity: true, email: true, confirmEmail: true }, true); const errors = await validateForm(); if (Object.keys(errors).filter((key) => key !== 'acceptTerms').length === 0) { setShowLoginModal(true); } }; return ( <div className="container-fluid"> <div className="row"> <div className="col-lg-6 col-md-12 col-sm-12 background-img"> <Button className="faq-btn" variant="primary" onClick={() => (isTabletOrMobile ? openOverlayMobile() : openOverlay())} > FAQ </Button> <div className="logo-wrapper"> <img src={WhiteLogo} alt="white-logo" className="logo-top" /> </div> <h1 className="form-name-green mt-4 mb-5 text-center"> Lock Away <span className="form-name-green-mobile">Carbon</span>{' '} </h1> <div id="myNav" className="col-lg-6 col-md-12 col-sm-12 overlay" style={{ width: `${overlayWidth}%` }}> <div className="btn close-btn" onClick={closeOverlay}> <img src={Closebtn} alt="close-btn" /> </div> <div className="logo-wrapper"> <img src={WhiteLogo} alt="white-logo" className="logo-top" /> </div> <div className="faq-modal-wrapper"> <Modal.Header> <Modal.Title className="faq-modal-title mt-5">Frequently Asked Questions</Modal.Title> </Modal.Header> <Modal.Body className="faq-modal-body mt-1 mb-5 px-5"> <div className="wr-faq-modal-body"> <FaqAccordian /> </div> </Modal.Body> </div> </div> </div> <div className="col-lg-6 col-md-12 col-sm-12 form-wrapper"> <div className="buy-certificate-form-wrapper"> <div className="buy-certificate-form"> <div className="wr-form-signin-btn"> <UnauthenticatedTemplate> <Button variant="dark" className="form-signin-btn mt-5" onClick={() => handleSignIn()}> Sign In </Button> </UnauthenticatedTemplate> </div> <h1 className="form-name mt-5 mb-5"> Lock Away <span className="form-name-green">Carbon</span>{' '} </h1> <Formik initialValues={{ carbonQuantity: buyECertificateDetails ? buyECertificateDetails?.carbonQuantity : '', currency: 'GBP', price: buyECertificateDetails ? buyECertificateDetails?.price : '', email: '', confirmEmail: '', newsletter: buyECertificateDetails ? buyECertificateDetails?.newsletter : false, acceptTerms: buyECertificateDetails ? buyECertificateDetails?.acceptTerms : false }} validationSchema={validationSchema} onSubmit={async (values, { setSubmitting }) => { saveBuyECertificateDetails(values); // If user is authenticated or guest user email is available if (instance.getActiveAccount() || guestUserEmail) { try { let clientSecret; let paymentIntentId; const paymentIntentResponse = await createPaymentIntent( applicationUserEmail, isECertificateGifting ? values.email : applicationUserEmail, values.carbonQuantity, values.newsletter ); if (paymentIntentResponse && paymentIntentResponse?.clientSecret) { clientSecret = paymentIntentResponse.clientSecret; paymentIntentId = paymentIntentResponse.paymentIntentId; } else { throw new Error('Payment intent response is undefined or missing result.'); } navigate('/checkout', { state: { clientSecret: clientSecret, carbonQuantity: values.carbonQuantity, price: values.price, paymentIntentId: paymentIntentId } }); } catch (error) { console.error('Error fetching payment intent:', error); setPaymentIntentAPIError(true); } } else { setShowLoginModal(true); } setSubmitting(false); }} > {({ setFieldValue, values, isSubmitting, validateForm, dirty, setTouched, submitForm, errors }) => ( <FormikForm> <Form.Group controlId="carbonQuantity" className="mb-3"> <Form.Label className="form-label">Carbon Quantity (Kg)</Form.Label> <Field type="text" name="carbonQuantity" placeholder="Enter quantity in Kg" className={`form-control certificate-form-input ${ errors?.carbonQuantity ? 'invalid-input-values' : '' }`} // onKeyPress={(e) => { // if (e.key !== 'Backspace' && (e.key < '0' || e.key > '9')) { // e.preventDefault(); // } // }} onChange={async (e, form) => { if (e.target.value === '') { setFieldValue('carbonQuantity', e.target.value); setFieldValue('price', ''); return; } else { let enteredValue = e.target.value; if (enteredValue === '.') { enteredValue = '0.'; } // Use a regular expression to restrict input to numeric values with up to 3 decimal places const regex = /^\d*\.?\d{0,3}$/; if (regex.test(enteredValue)) { setFieldValue('carbonQuantity', enteredValue); } try { const { price } = await calculateCarbonAmountPriceGivenWeight(enteredValue); setFieldValue('price', price.toFixed(2)); } catch (error) { setPriceCalcAPIError(true); setFieldValue('carbonQuantity', ''); } } }} /> <ErrorMessage name="carbonQuantity" component="div" className="text-danger" /> </Form.Group> <Form.Group controlId="currency" className="mb-3"> <Form.Label className="form-label">Currency</Form.Label> <InputGroup> <Field type="text" name="currency" className="form-control certificate-form-input disabled-input" disabled /> </InputGroup> </Form.Group> <Form.Group controlId="price" className="mb-3"> <Form.Label className="form-label">Price</Form.Label> <Field type="number" name="price" className="form-control certificate-form-input disabled-input" readOnly /> </Form.Group> <Form.Group controlId="newsletter" as={Col}> <Form.Check type="checkbox" label="Email me with Carbon News" name="newsletter" onChange={(event) => { setFieldValue('newsletter', event.target.checked); }} checked={values.newsletter} /> </Form.Group> <div className="gift-area-wrapper my-3"> <p className="form-label">Are you gifting this eCertificate?</p> <div className="gift-area-button-wrapper mt-1"> <Button className={`btn gift-area-button me-3 ${isECertificateGifting ? 'active' : ''}`} variant="light" onClick={() => setIsEcertificateGifting(true)} > Yes </Button> <Button className={`btn gift-area-button ${!isECertificateGifting ? 'active' : ''}`} variant="light" onClick={() => setIsEcertificateGifting(false)} > No </Button> </div> </div> {isECertificateGifting && ( <> <Form.Group controlId="email" className="mb-3"> <Form.Label className="form-label">Reciever Email</Form.Label> <Field type="email" name="email" className={`form-control certificate-form-input ${ errors?.email ? 'invalid-input-values' : '' }`} /> <ErrorMessage name="email" component="div" className="text-danger" /> </Form.Group> <Form.Group controlId="confirmEmail" className="mb-3"> <Form.Label className="form-label">Re-enter Reciever Email</Form.Label> <Field type="email" name="confirmEmail" className={`form-control certificate-form-input ${ errors?.confirmEmail ? 'invalid-input-values' : '' }`} /> <ErrorMessage name="confirmEmail" component="div" className="text-danger" /> </Form.Group> </> )} <div className="center-button-container my-5"> <Button variant="primary" className="submit-button" onClick={() => checkoutClickHandler(dirty, validateForm, setTouched)} > Checkout </Button> </div> <Modal show={showLoginModal} onHide={() => setShowLoginModal(false)} className="my-5"> <Modal.Body className="sign-in-modal"> <div className="sign-in-modal-wrapper my-5"> <div className="modal-text-wrapper"> <h1 className="modal-main-title pe-3">Proceeding to Checkout</h1> <img src={ForwardArrow} alt="arrow-forward" className="arrow-forward" /> </div> <div className="modal-text-box-wrapper my-3"> <p className="modal-text-box-para"> <span className="green-text">Disclaimer: </span> All sales final. By completing this purchase, you agree to our terms and conditions. For assistance, contact customer support. Thank you for choosing C2Zero. </p> <Form.Group controlId="acceptTerms" as={Col} className="mb-1"> <Form.Check name="acceptTerms"> <Form.Check.Input type="checkbox" onChange={(event) => { setFieldValue('acceptTerms', event.target.checked); }} checked={values.acceptTerms} /> <Form.Check.Label className="terms-text"> Accept the{' '} <a href="https://www.c2zero.net/terms" target="_blank" className="terms-link"> <span className="link-span">Terms of service</span> </a>{' '} and{' '} <a href="https://www.c2zero.net/privacy" target="_blank" className="terms-link"> <span className="link-span">privacy policy</span> </a> </Form.Check.Label> </Form.Check> <ErrorMessage name="acceptTerms" component="div" className="text-danger" /> </Form.Group> </div> {instance.getActiveAccount() || guestUserEmail ? ( <Button variant="primary" className="submit-button mt-3" disabled={isSubmitting || values?.acceptTerms === false} onClick={() => submitForm().then(() => { console.log('done'); }) } > Continue </Button> ) : ( <> <Button variant="primary" onClick={handleSignIn} className="modal-btn btn-black mt-3 mb-2" disabled={values?.acceptTerms === false} > Sign in </Button> <label className="sign-up-text"> New User? <Button variant="link" className="sign-up" onClick={() => handleJoinc2zero()} disabled={values?.acceptTerms === false} > Create Account </Button> </label> <div className="wr-vertical-lines"> <hr className="vertical-lines" /> <label className="px-3">or</label> <hr className="vertical-lines" /> </div> <Button variant="link" onClick={() => handleContineAsGuest(values)} className="guest-btn" disabled={values?.acceptTerms === false} > Continue as a guest </Button> <div className="modal-footer"> <p className="footer-text"> <img src={warningIcon} alt="warning-icon" className="pe-2" /> You will be able to sign in or create account after you check out </p> </div> </> )} </div> </Modal.Body> </Modal> </FormikForm> )} </Formik> <p className="text-center copyright-text">Copyright © {new Date().getFullYear()} C2Zero.</p> </div> </div> </div> </div> </div> ); }; export default BuyCarbonCertificateForm;
import 'package:firebase_flutter_app/provider/auth_provider.dart'; import 'package:firebase_flutter_app/screens/home_screen.dart'; import 'package:firebase_flutter_app/screens/register_screen.dart'; import 'package:firebase_flutter_app/widgets/custom_button.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class WelcomeScreen extends StatefulWidget { const WelcomeScreen({Key? key}) : super(key: key); @override State<WelcomeScreen> createState() => _WelcomeScreenState(); } class _WelcomeScreenState extends State<WelcomeScreen> { @override Widget build(BuildContext context) { final ap = Provider.of<AuthProvider>(context, listen: false); return Scaffold( body: SafeArea( child: Center( child: Padding( padding: const EdgeInsets.symmetric(vertical: 25, horizontal: 35), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( "assets/mb1.jpg", height: 300, ), const SizedBox( height: 20, ), const Text( "Let's get started", style: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold), ), const SizedBox( height: 10, ), const Text( "Never a better time than now to start", style: TextStyle( fontSize: 14.0, color: Colors.black38, fontWeight: FontWeight.bold), ), const SizedBox( height: 20, ), SizedBox( width: double.infinity, height: 50.0, child: CustomButton( onPressed: () async { if (ap.isSignedIn == true) { await ap.getDataFromSP().whenComplete( () => Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const HomeScreen()), ), ); } else { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const RegisterScreen(), )); } }, text: "Get Started", ), ) ], ), ), ), ), ); } }
import { createRouter, createWebHashHistory } from 'vue-router' import HomeView from '../views/HomeView.vue' const routes = [ { path: '/', name: 'home', component: HomeView }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue') }, { path: '/MyVueVieuw', name: 'MyVueVieuw', component: () => import('../views/MyVueVieuw.vue') } , { path: '/vue1', name: 'vue1', component: () => import('../views/vue1.vue') }, ] const router = createRouter({ history: createWebHashHistory(), routes }) export default router
Tutorial 32: Handling Events in React //App.js: import React from "react" function handleClick() { console.log("I was clicked") } // https://reactjs.org/docs/events.html#supported-events function App() { return ( <div> <img onMouseOver={() => console.log("Hovered!")} src="https://www.fillmurray.com/200/100"/> <br /> <br /> <button onClick={handleClick}>Click me</button> </div> ) } export default App //index.html: <html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div id="root"></div> <script src="index.pack.js"></script> </body> </html> //index.js: import React from "react" import ReactDOM from "react-dom" import App from "./App" ReactDOM.render(<App />, document.getElementById("root")) //style.css: body { }
package main import ( "bytes" "database/sql" "log" "net/http" "net/http/httptest" "testing" _ "github.com/denisenkom/go-mssqldb" ) func setupTest() { // Initialize db with a connection to your test database // Update the connection string with your test database details db, err := sql.Open("sqlserver", "server=DESKTOP-7CS9CM5//SQLEXPRESS;database=Items;integrated security=true") if err != nil { log.Fatalf("Error opening database connection: %v", err) } // Ping the database to check if the connection is successful err = db.Ping() if err != nil { log.Fatalf("Error connecting to database: %v", err) } } func TestAddItemHandler(t *testing.T) { // Set up test environment setupTest() // Create a request with JSON payload requestBody := []byte(`{"name": "Test Item"}`) req, err := http.NewRequest("POST", "/items", bytes.NewBuffer(requestBody)) if err != nil { t.Fatal(err) } // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() // Call the handler function directly, passing in the ResponseRecorder and Request addItemHandler(rr, req) // Check the status code if rr.Code != http.StatusOK { t.Errorf("Expected status code %d, got %d", http.StatusOK, rr.Code) } } func TestGetItemsHandler(t *testing.T) { // Set up test environment setupTest() // Create a request req, err := http.NewRequest("GET", "/items", nil) if err != nil { t.Fatal(err) } // Create a ResponseRecorder to record the response rr := httptest.NewRecorder() // Call the handler function directly, passing in the ResponseRecorder and Request getItemsHandler(rr, req) // Check the status code if rr.Code != http.StatusOK { t.Errorf("Expected status code %d, got %d", http.StatusOK, rr.Code) } }
package com.imtilab.bittracer.utils import groovy.util.logging.Slf4j import com.imtilab.bittracer.constant.Constants import net.sf.json.JSONArray import org.apache.commons.collections.CollectionUtils import org.apache.commons.lang3.time.DateFormatUtils import java.text.SimpleDateFormat import java.time.* import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit @Slf4j class DateUtil { /** * Format date into given format * @param date * @param pattern * @return formatted date */ static LocalDateTime getFormattedDateTime(String date, String pattern) { if (date == null) { return date } try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern) LocalDateTime.parse(CommonUtils.convertToPrimitive(date), formatter) } catch (Exception ex) { throw new Exception("Date paarse: The date($date) can't be format($pattern)") } } static List<LocalDateTime> getFormattedDateTime(List date, String pattern) { List localDateTimes = [] date.each { localDateTimes.add(getFormattedDateTime(it, pattern)) } localDateTimes } static LocalDate getFormattedDate(String date, String pattern) { if (date == null) { return date } try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern) LocalDate.parse(CommonUtils.convertToPrimitive(date), formatter) } catch (Exception ex) { throw new Exception("Date paarse: The date($date) can't be format($pattern)") } } static List<LocalDate> getFormattedDate(List date, String pattern) { List localDates = [] date.each { localDates.add(getFormattedDate(it, pattern)) } localDates } /** * * @return timestamp */ static def getTimestamp() { Date date = new Date() return DateFormatUtils.format(date, Constants.TIMESTAMP_FORMAT) } /** * localDateTime to String in specific pattern * * @param localDateTime * @param pattern * @return Date time in given pattern */ static String getDate(LocalDateTime localDateTime, String pattern) { localDateTime.format(DateTimeFormatter.ofPattern(pattern)) } /** * localDateTime to String in specific pattern * * @param localDateTimes * @param pattern * @return Date time in given pattern */ static List<String> getDate(List<LocalDateTime> localDateTimes, String pattern) { List<String> dateTimes = [] localDateTimes.each { dateTimes.add(getDate(it, pattern)) } dateTimes } static def getDateByFormat(def date, String format) { if ((date instanceof JSONArray) && CollectionUtils.isNotEmpty(date) && !(date.get(0) instanceof String)) { throw new Exception("$date is neither Date nor list of Date") } getFormattedDateTime(date, format) } /** * Convert date to given zone date * @param date * @param currentZone * @param toZone * @return */ static LocalDateTime convertDateToZone(LocalDateTime date, String currentZone, String toZone){ ZonedDateTime zonedDateTime = date.atZone(ZoneId.of(currentZone)) ZonedDateTime newZoneDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of(toZone)) newZoneDateTime.toLocalDateTime() } static List generateStartAndEndDate() { List list = new ArrayList() Instant startDateInstant = Instant.now() SimpleDateFormat sdf = new SimpleDateFormat(Constants.AUTO_GEN_START_DATE_DATE_FORMAT) sdf.setTimeZone(TimeZone.getTimeZone("GMT")) def arr = sdf.format(startDateInstant.toDate()).split("T|Z|:") arr[2] = String.format("%02d", Integer.parseInt(arr[2]) + 2) def startDate = arr[0] + "T" + arr[1] + ":" + arr [2] + ":" + arr[3] + "Z" list.add(startDate) int days = 1 Instant endDateInstant = startDateInstant.plus(days, ChronoUnit.DAYS) sdf = new SimpleDateFormat(Constants.AUTO_GEN_END_DATE_DATE_FORMAT) sdf.setTimeZone(TimeZone.getTimeZone("GMT")) list.add(sdf.format(endDateInstant.toDate())) list.add(getTimeDiffFromNextMinInSec(startDateInstant)) log.info("\nAUTO GEN START & END TIME: {}", list) list } static int getTimeDiffFromNextMinInSec(Instant instant) { SimpleDateFormat formatForSec = new SimpleDateFormat("ss") def sec = formatForSec.format(instant.toDate()) int timeDiffInSec = 120 - Integer.parseInt(sec) return timeDiffInSec } static List<String> getOldToNewFormattedDate(List date,String oldPattern,String newPattern){ List formattedDate = [] date.each { formattedDate.add(getOldToNewFormattedDate(it,oldPattern,newPattern)) } formattedDate } static String getOldToNewFormattedDate(String dateInput,String oldPattern,String newPattern){ SimpleDateFormat formatInput = new SimpleDateFormat(oldPattern) SimpleDateFormat formatOutput = new SimpleDateFormat(newPattern) Date date = formatInput.parse(dateInput) return formatOutput.format(date).toString() } }
## 题目描述 尽管奶牛们天生谨慎,她们仍然在住房抵押信贷市场中受到打击,现在她们开始着手于股市。 Bessie 很有先见之明,她不仅知道今天 $s$ 只股票的价格,还知道接下来一共 $d$ 天的(包括今天)。给定一个 $d$ 天的股票价格矩阵以及初始资金 $m$,求最优买卖策略使得总获利最大化。每次必须购买股票价格的整数倍,同时你不需要花光所有的钱(甚至可以不花)。考虑这个牛市的例子(这是 Bessie 最喜欢的)。在这个例子中,有 $2$ 只股票和 $3$ 天。奶牛有 $10$ 的钱来投资。 |股票 | 今天的价格 | 明天的价格 | 后天的价格 | | :----: | :----: | :----: | :----: | | $1$ | $10$ | $15$ | $15$ | | $2$ | $13$ | $11$ | $20$ | 以如上策略可以获得最大利润:第一天买入第一只股票。第二天把它卖掉并且迅速买入第二只,此时还剩下 $4$ 的钱。最后一天卖掉第二只股票,此时一共有 $4+20=24$ 的钱。 ## 输入格式 第一行:三个空格隔开的整数:$s,d,m$。 第 $2\sim s+1$ 行:第 $i+1$ 行包含了第 $i$ 只股票第 $1$ 至 $d$ 天的价格 $w_{i,{1\sim d}}$。 ## 输出格式 第一行:最后一天卖掉股票之后最多可能的钱数。 ```input1 2 3 10 10 15 15 13 11 20 ``` ```output1 24 ``` ## 数据规模与约定 对于 $100\%$ 的数据,$2 \leq s \leq 50$,$2 \leq d \leq 10$,$1 \leq m \leq 2\times10^5$,$1\leq w_{i,{1\sim d}}\leq 1000$。 约定你的获利不超过 $5\times10^5$。 ## 题目来源 Usaco 2009 Feb Gold
#include "3-calc.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /** * main - perform math operations * @argc: argument count * @argv: argument vector * Return: 98 on error, 99 on illegal op or 0 otheriwse */ int main(int argc, char *argv[]) { int (*func)(int, int); if (argc != 4) { printf("Error\n"); exit(98); } func = get_op_func(argv[2]); if (func == NULL) { printf("Error\n"); exit(99); } printf("%d\n", func(atoi(argv[1]), atoi(argv[3]))); return (0); }
import { Link as ScrollLink } from 'react-scroll'; import {Box, Button, Text, VStack} from '@chakra-ui/react'; import { motion } from "framer-motion"; import { ChevronDownIcon } from '@chakra-ui/icons'; import React from "react"; import './home.scss'; const MotionBox = motion(Box); type ScrollTextProps = { to: string; arrow: React.ReactNode; projectText: React.ReactNode; //...other props. }; const ScrollText = ({ to, arrow, projectText, ...rest }: ScrollTextProps) => ( <VStack as={ScrollLink} to={to} smooth={true} color="darkgrey" duration={500} _hover={{ cursor: "pointer", color: "black" }} align="center" // vertically align the content (Arrow and Text) {...rest} > <Text >{projectText}</Text> {arrow} </VStack> ); const Home = () => { return ( <Box className="home" width="100%" position="relative"> <MotionBox initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 1 }} display="flex" pr="50vw" alignItems="center" justifyContent="center" width="100%" height="100%" > <VStack spacing={4} className="hero-content" maxW="800px" alignItems="center"> <Text fontFamily="Orbitron" fontSize="3xl" fontWeight="bold" color="white">Hi, I'm Dev Ju</Text> <Text fontSize="xl" color="lightgray">Fullstack Developer specializing in Angular / React and .NET</Text> <Text fontSize="xl" color="white">Future IT-Security specialist</Text> <Box> <ScrollLink to="about" smooth={true} duration={500} > <Button colorScheme="blackAlpha" marginRight={4}> View About </Button> </ScrollLink> <ScrollLink to="contact" smooth={true} duration={500} > <Button colorScheme="gray"> Contact Me </Button> </ScrollLink> </Box> </VStack> </MotionBox> <MotionBox position="absolute" bottom="0" width="100%" display="flex" justifyContent="center" pb="3vh" initial={{ y: 0 }} animate={{ y: [0, -20, 0] }} transition={{ duration: 1.5, repeat: Infinity }} > <ScrollText to="projects" projectText="Projects" arrow={<ChevronDownIcon boxSize="5" />} /> </MotionBox> </Box> ); }; export default Home;
import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.util.Stack; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.WindowConstants; public class Calculator extends JFrame { JTextField tfEquation = new JTextField(26); JTextField tfResult = new JTextField(30); Stack<String> stack = new Stack<String>(); StringBuilder equationText; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js"); public Calculator() { setSize(400, 300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); setTitle("계산기프레임"); JPanel northPanel = new JPanel(); JPanel centerPanel = new JPanel(new GridLayout(4, 3, 5, 5)); JPanel southPanel = new JPanel(); JButton btnRemove = new JButton("◀"); northPanel.add(new JLabel("수식입력")); northPanel.add(tfEquation); northPanel.add(btnRemove); northPanel.setBackground(Color.gray); btnRemove.addActionListener(e -> removeText()); for (String element : new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "CE", "계산", "+", "-", "*", "/" }) { JButton button; centerPanel.add(button = new JButton(element)); if (element.equals("계산")) { button.addActionListener(this::calculate); } else if (element.equals("CE")) { button.addActionListener(e -> resetField()); } else { button.addActionListener(this::insertEquation); } } southPanel.add(new JLabel("계산결과")); southPanel.add(tfResult); southPanel.setBackground(Color.yellow); add(northPanel, BorderLayout.NORTH); add(centerPanel); add(southPanel, BorderLayout.SOUTH); } public static void main(String[] args) { new Calculator().setVisible(true); } public void insertEquation(ActionEvent e) { JButton button = (JButton) e.getSource(); stack.push(button.getText()); updateField(); } public void calculate(ActionEvent e) { try { tfResult.setText(engine.eval(equationText.toString()).toString()); // tfResult.setText(); } catch (ScriptException e1) { e1.printStackTrace(); } } public void resetField() { tfEquation.setText(""); stack.removeAllElements(); } public void removeText() { stack.pop(); updateField(); } public void updateField() { equationText = new StringBuilder(); for (String element : stack) { equationText.append(element); } tfEquation.setText(equationText.toString()); } }
import { RouteProps } from 'react-router-dom'; import MainPage from '@/pages/MainPage/ui/MainPage'; import { AboutPage } from '@/pages/AboutPage'; import { NotFound } from '@/pages/NotFoundPage/ui/NotFound'; import { ProfilePage } from '@/pages/ProfilePage'; import { RegistrationSuccess } from '@/pages/RegistrationSuccessPage'; type ApproutesProps = RouteProps & { authOnly?: boolean } export enum AppRoutes { MAIN = 'main', ABOUT = 'about', PROFILE = 'profile', REGISTRATION_SUCCESS = 'registrationSuccess', NOT_FOUND = 'not_found', } export const RouterPath: Record<AppRoutes, string> = { [AppRoutes.MAIN]: '/', [AppRoutes.ABOUT]: '/about', [AppRoutes.PROFILE]: '/profile', [AppRoutes.REGISTRATION_SUCCESS]: '/registration-success', [AppRoutes.NOT_FOUND]: '*', }; export const routeConfig: Record<AppRoutes, ApproutesProps> = { [AppRoutes.MAIN]: { path: RouterPath.main, element: <MainPage />, }, [AppRoutes.ABOUT]: { path: RouterPath.about, element: <AboutPage />, }, [AppRoutes.PROFILE]: { path: RouterPath.profile, element: <ProfilePage />, authOnly: true }, [AppRoutes.REGISTRATION_SUCCESS]: { path: RouterPath.registrationSuccess, element: <RegistrationSuccess />, }, [AppRoutes.NOT_FOUND]: { path: RouterPath.not_found, element: <NotFound />, }, };
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class BaseModel(models.Model): created_at = models.DateTimeField('Добавлено', auto_now_add=True) is_published = models.BooleanField( 'Опубликовано', default=True, help_text='Снимите галочку, чтобы скрыть публикацию.' ) class Meta: abstract = True class Category(BaseModel): title = models.CharField(max_length=256, verbose_name='Заголовок') description = models.TextField(verbose_name='Описание') slug = models.SlugField(unique=True, verbose_name='Идентификатор', help_text='Идентификатор страницы для URL; ' 'разрешены символы латиницы, цифры, дефис и ' 'подчёркивание.') class Meta: verbose_name = 'категория' verbose_name_plural = 'Категории' def __str__(self): return self.title class Location(BaseModel): name = models.CharField(max_length=256, verbose_name='Название места') class Meta: verbose_name = 'местоположение' verbose_name_plural = 'Местоположения' def __str__(self): return self.name class Post(BaseModel): title = models.CharField(max_length=256, verbose_name='Заголовлок') text = models.TextField(verbose_name='Текст') pub_date = models.DateTimeField(verbose_name='Дата и время публикации', help_text='Если установить дату ' 'и время в будущем — можно делать ' 'отложенные публикации.') author = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name='Автор публикации' ) location = models.ForeignKey( Location, on_delete=models.SET_NULL, null=True, verbose_name='Местоположение' ) category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, verbose_name='Категория' ) class Meta: verbose_name = 'публикация' verbose_name_plural = 'Публикации' def __str__(self): return self.title
package app.model; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.format.annotation.DateTimeFormat; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Table(name = "orders") public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "user_id") private Long userId; @DateTimeFormat(pattern = "yyyy-MM-dd") @Column(name = "order_date") private LocalDate orderDate; @Column(name = "total_amount") private double totalAmount; @Column(name = "delivery_status") private String deliveryStatus; @Column(name = "recipient_name") private String recipientName; @Column(name = "recipient_phone") private String recipientPhone; @Column(name = "recipient_address") private String recipientAddress; public Order() { } public Order(Long id, Long userId, LocalDate orderDate, double totalAmount, String deliveryStatus, String recipientName, String recipientPhone, String recipientAddress) { this.id = id; this.userId = userId; this.orderDate = orderDate; this.totalAmount = totalAmount; this.deliveryStatus = deliveryStatus; this.recipientName = recipientName; this.recipientPhone = recipientPhone; this.recipientAddress = recipientAddress; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public LocalDate getOrderDate() { return orderDate; } public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public double getTotalAmount() { return totalAmount; } public void setTotalAmount(double totalAmount) { this.totalAmount = totalAmount; } public String getDeliveryStatus() { return deliveryStatus; } public void setDeliveryStatus(String deliveryStatus) { this.deliveryStatus = deliveryStatus; } public String getRecipientName() { return recipientName; } public void setRecipientName(String recipientName) { this.recipientName = recipientName; } public String getRecipientPhone() { return recipientPhone; } public void setRecipientPhone(String recipientPhone) { this.recipientPhone = recipientPhone; } public String getRecipientAddress() { return recipientAddress; } public void setRecipientAddress(String recipientAddress) { this.recipientAddress = recipientAddress; } @Override public String toString() { return "Order{" + "id=" + id + ", userId=" + userId + ", orderDate=" + orderDate + ", totalAmount=" + totalAmount + ", deliveryStatus='" + deliveryStatus + '\'' + ", recipientName='" + recipientName + '\'' + ", recipientPhone='" + recipientPhone + '\'' + ", recipientAddress='" + recipientAddress + '\'' + '}'; } }
function init() { // Grab a reference to the dropdown select element let selector = d3.select("#selDataset"); // Use the list of sample names to populate the select options d3.json("static/js/samples.json").then((data) => { let sampleNames = data.names; sampleNames.forEach((sample) => { selector .append("option") .text(sample) .property("value", sample); }); // Use the first sample from the list to build the initial plots let firstSample = sampleNames[0]; buildCharts(firstSample); buildMetadata(firstSample); console.log(data); }); } // Initialize the dashboard init(); function optionChanged(newSample) { // Fetch new data each time a new sample is selected buildMetadata(newSample); buildCharts(newSample); } // Demographics Panel function buildMetadata(sample) { d3.json("static/js/samples.json").then((data) => { let metadata = data.metadata; // Filter the data for the object with the desired sample number let resultArray = metadata.filter(sampleObj => sampleObj.id == sample); let result = resultArray[0]; // Use d3 to select the panel with id of `#sample-metadata` let PANEL = d3.select("#sample-metadata"); // Use `.html("") to clear any existing metadata PANEL.html(""); // Use `Object.entries` to add each key and value pair to the panel // Hint: Inside the loop, you will need to use d3 to append new // tags for each key-value in the metadata. Object.entries(result).forEach(([key, value]) => { PANEL.append("h6").text(`${key.toUpperCase()}: ${value}`); }); }); } // 1. Create the buildCharts function. function buildCharts(sample) { // 2. Use d3.json to load and retrieve the samples.json file d3.json("static/js/samples.json").then((data) => { // 3. Create a variable that holds the samples array. let dataSamples = data.samples; // 4. Create a variable that filters the samples for the object with the desired sample number. let filteredSample = dataSamples.filter(sampleObj => sampleObj.id == sample); // 5. Create a variable that holds the first sample in the array. let result = filteredSample[0]; // 6. Create variables that hold the otu_ids, otu_labels, and sample_values. let otu_ids = result.otu_ids; let otu_labels = result.otu_labels; let sample_values = result.sample_values // 7. Create the yticks for the bar chart. // Hint: Get the the top 10 otu_ids and map them in descending order // so the otu_ids with the most bacteria are last. let yticks = otu_ids.slice(0,10).map(id => `OTU ${id}`).reverse(); let xticks = sample_values.slice(0,10).reverse(); let labels = otu_labels.slice(0,10).reverse() // 8. Create the trace for the bar chart. let barData = [{ x: xticks, y: yticks, text: labels, type: "bar", orientation: "h" }]; // 9. Create the layout for the bar chart. let barLayout = { title: "Top 10 Bacteria Cultures Found", paper_bgcolor: "rgba(0,0,0,0)", font: { size: 14, family: 'Courier New, monospace' } }; // 10. Use Plotly to plot the data with the layout. Plotly.newPlot("bar", barData, barLayout, {responsive: true}); // BUBBLE CHART // 1. Create the trace for the bubble chart. let bubbleData = [{ x: otu_ids, y: sample_values, text: otu_labels, mode: "markers", marker: { size: sample_values, sizeref: 1.25, color: otu_ids, colorscale: "Portland" } }]; // 2. Create the layout for the bubble chart. let bubbleLayout = { title: "Bacteria Cultures Per Sample", xaxis: {title: "OTU ID"}, yaxis: {title: "Culture Count"}, hovermode: "closest", paper_bgcolor: "rgba(0,0,0,0)", font: { size: 16, family: 'Courier New, monospace' } }; // 3. Use Plotly to plot the data with the layout. Plotly.newPlot("bubble", bubbleData, bubbleLayout, {responsive: true}); // GAUGE CHART let metaData = data.metadata; let filteredMetaData = metaData.filter(sampleObj => sampleObj.id == sample)[0]; let wfreq = filteredMetaData.wfreq; // 4. Create the trace for the gauge chart. let gaugeData = [{ domain: {x: [0,1], y: [0,1]}, value: wfreq, type: "indicator", mode: "gauge+number", title: {text: "<b>Belly Button Washing Frequency</b><br>Scrubs per Week"}, gauge: { axis: {range: [0, 10]}, bar: {color: "black"}, steps: [ {range: [0,2], color: "red"}, {range: [2,4], color: "orange"}, {range: [4,6], color: "yellow"}, {range: [6,8], color: "greenyellow"}, {range: [8,10], color: "green"} ] } }]; // 5. Create the layout for the gauge chart. let gaugeLayout = { width: 500, height: 500, margin: { t:0, b:0 }, paper_bgcolor: "rgba(0,0,0,0)", font: { size: 14, family: 'Courier New, monospace' } }; // 6. Use Plotly to plot the gauge data and layout. Plotly.newPlot("gauge", gaugeData, gaugeLayout, {responsive: true}); }); }