text
stringlengths
184
4.48M
import { Component, OnInit } from "@angular/core"; import { HttpClient, HttpParams } from "@angular/common/http"; import { Observable } from "rxjs"; import { map } from "rxjs/operators"; interface CityWeather { name: string; weather: string; status: string[]; } interface ApiResponse { page: number; per_page: number; total: number; total_pages: number; data: CityWeather[]; } @Component({ selector: "weather-finder", templateUrl: "./weatherFinder.component.html", styleUrls: ["./weatherFinder.component.scss"], }) export class WeatherFinder implements OnInit { resObj; cold = false; sunny = false; search = false; emptyData = false; cityName = ""; constructor(private http: HttpClient) {} ngOnInit(): void {} async getWeatherData(): Promise<ApiResponse> | null { this.cold = false; this.sunny = false; return this.http .get(`https://jsonmock.hackerrank.com/api/weather?name=${this.cityName}`) .pipe(map((res) => res as ApiResponse)) .toPromise(); } async getWeather() { this.search = true; this.emptyData = false; if(this.cityName !== '') { this.resObj = {}; await this.getWeatherData().then((res) => { this.resObj = res && res.data.length === 1 ? res : {}; }); if (Object.keys(this.resObj).length !== 0) { if(this.resObj.data[0].name.toUpperCase() === this.cityName.toUpperCase()){ this.resObj.data[0].weather.split(" ").forEach((element) => { if (!isNaN(element)) { if (element < 20) { this.cold = true; } if (element > 20) { this.sunny = true; } } }); } } else { this.emptyData = true; } } else { this.resObj = {}; this.emptyData = true; } } }
import { LoginComponent } from './Components/login/login.component'; import { HomeComponent } from './Components/home/home.component'; import { NgModule } from '@angular/core'; import { RouterModule, Routes, Router } from '@angular/router'; import { RegisterComponent } from './Components/register/register.component'; const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'register', component: RegisterComponent }, { path: 'login', component: LoginComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule { constructor(router: Router) { router.events.subscribe(() => { window.scrollTo(0, 0); }); } }
package com.holubek.trashhunter.ui.place import android.animation.ArgbEvaluator import android.annotation.SuppressLint import android.app.Activity.RESULT_OK import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Color import android.net.Uri import androidx.lifecycle.ViewModelProviders import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.RatingBar import android.widget.TextView import androidx.appcompat.widget.AppCompatButton import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatRatingBar import androidx.core.app.ShareCompat import androidx.core.net.toUri import androidx.core.widget.NestedScrollView import androidx.lifecycle.Observer import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.geometry.SpatialReference import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.Basemap import com.esri.arcgisruntime.mapping.view.Graphic import com.esri.arcgisruntime.mapping.view.GraphicsOverlay import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol import com.holubek.trashhunter.* import com.holubek.trashhunter.Map import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.GeoPoint import com.google.firebase.storage.FirebaseStorage import com.squareup.picasso.Picasso import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList import kotlin.concurrent.thread /** * Trieda na zobrazenie detailu o označenom mieste */ class PlaceFragment : Fragment() { companion object { fun newInstance() = PlaceFragment() } private var PICTURE_REQUEST_CODE = 1 private lateinit var viewPager:ViewPager private lateinit var viewPagerComments:ViewPager private lateinit var pictures : ArrayList<Picture> private lateinit var place: Place private var placeID:String?=null private lateinit var comments: List<Comment> private lateinit var placeViewModel: PlaceViewModel private lateinit var mapView:MapView private lateinit var uriPictureAfter:Uri private var pictureFile:File?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } /** * Inicializácia informácií o označenom mieste */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { placeViewModel = ViewModelProviders.of(this).get(PlaceViewModel::class.java) val root = inflater.inflate(R.layout.place_fragment, container, false) if (placeID == null){ placeID = arguments?.getString("POINT_ID") } viewPager = root.findViewById<ViewPager>(R.id.viewPager) viewPagerComments = root.findViewById(R.id.viewPagerComments) mapView = root.findViewById<MapView>(R.id.placeMap) mapView!!.map = ArcGISMap(Basemap.Type.STREETS_VECTOR, 49.201476197, 18.870735168, 11) var scrollView = root.findViewById<NestedScrollView>(R.id.placeScrollView) Map.setMove(root,mapView,scrollView) //Vyhladanie miesta podla ID placeViewModel.getPlace(placeID.toString()).observe(this, Observer { it -> place = it updatePlace(root) }) //Observer na naplnenie komentárov do pageViewera placeViewModel.getComments(placeID.toString()).observe(this, Observer { comments = it updateComments(root) }) var buttonRatePlace = root.findViewById<AppCompatButton>(R.id.buttonPlaceRate) buttonRatePlace.setOnClickListener(View.OnClickListener { var ratingbarPlace = root.findViewById<RatingBar>(R.id.placeRatingBar) var comment = root.findViewById<AppCompatEditText>(R.id.eventTextRating) var commentText = "" if (!comment.text.toString().equals(getString(R.string.Comment))){ commentText = comment.text.toString() } placeViewModel.saveRating(place.pointID.toString(), place.countOfRating!!,place.rating!!,ratingbarPlace.rating,commentText) }) var buttonTakePicture = root.findViewById<Button>(R.id.button_takeAftPicture) buttonTakePicture.setOnClickListener { dispatchTakePictureIntent(root) //dsPicture(root) } return root } /** * Spustí kameru na vytvorenie fotky po vyčistení */ private fun dispatchTakePictureIntent(root: View) { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> // Ensure that there's a camera activity to handle the intent takePictureIntent.resolveActivity(activity?.packageManager!!)?.also { // Create the File where the photo should go thread { pictureFile = try { createImageFile(root) } catch (ex: IOException) { // Chyba pri vytváraní súboru Log.e("PLACE_FRAGMENT", "Chyba pri vytváraní súboru") null } // Súbor bol úspešne vytvorený uriPictureAfter = Uri.fromFile(pictureFile) takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriPictureAfter) startActivityForResult(takePictureIntent, PICTURE_REQUEST_CODE) } } } } private fun setPic() { thread { var bitmap = Picasso.get().load(uriPictureAfter).get().let { pictures.add(Picture(it,"Fotka po")) val baos = ByteArrayOutputStream() it?.compress(Bitmap.CompressFormat.JPEG, 50, baos) val data = baos.toByteArray() placeViewModel.clearPlace(placeID.toString(),data) } } } /** * metodá, ktorá sa spustí po skončení aktivity a nastaví fotku po vyčistení */ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) //data su niekedy null niekedy nie, tak treba zistit cestu k suboru kde sa nachadza fotka if (resultCode== RESULT_OK){ if(requestCode== PICTURE_REQUEST_CODE){ if (pictures.size == 2){ pictures.removeAt(1) } view?.findViewById<TextView>(R.id.clearUserNameLabel)?.visibility = View.VISIBLE var userNameClear = view?.findViewById<TextView>(R.id.clearUsername) userNameClear?.visibility = View.VISIBLE userNameClear?.text = FirebaseAuth.getInstance().currentUser?.displayName setPic() } } } /** * Metoda vráti jedinečný názov súboru pre novú fotografiu s použitím časovej pečiatky */ @SuppressLint("SimpleDateFormat") @Throws(IOException::class) private fun createImageFile(v: View): File { // Create an image file name val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val storageDir: File = v.context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)!! return File.createTempFile( "JPEG_${timeStamp}_", /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ).apply { // Save a file: path for use with ACTION_VIEW intents uriPictureAfter = absolutePath.toUri() } } /** * Nastavenie zoznamu komentárov ku príspevku * @param view objekt View, ktorý reprezentuje obrazovku na zobrazenie detailu príspevku */ private fun updateComments(root: View) { var adapter = AdapterComments(comments,root.context) viewPagerComments.adapter = adapter viewPagerComments.setPadding(130,0,130,0) } /** * Nastaví údaje príspevku * @param root objekt View, ktorý reprezentuje obrazovku na zobrazenie detailu príspevku */ private fun updatePlace(root: View) { pictures = ArrayList<Picture>() downloadPictures() updateInfo(root,place) updateMap(mapView,place.coordinates!!) var mapLocation = root.findViewById<TextView>(R.id.placeLocation) mapLocation.text = place.placeName var mapCoordination = root.findViewById<TextView>(R.id.placeCoordination) mapCoordination.text = "${place.coordinates!!.latitude.toString()}, ${place.coordinates!!.longitude.toString()}" var ratingBar = root.findViewById<AppCompatRatingBar>(R.id.ratingPlace) var ratingCount = root.findViewById<TextView>(R.id.countRatingText) if (place.rating != 0F){ ratingBar.rating = place.rating!!.div(place.countOfRating!!) ratingCount.text = place.countOfRating.toString() } } /** * Nastaví grafické zobrazenie označeného miesta na mape */ private fun updateMap(map: MapView,point: GeoPoint) { val pt = Point(point.latitude,point.longitude, SpatialReference.create(4326)) val mySymbol = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 18.0F) val myGraphic = Graphic(pt, mySymbol) val myGraphicsOverlay = GraphicsOverlay() myGraphicsOverlay.graphics.add(myGraphic) map.graphicsOverlays.add(myGraphicsOverlay) } /** * Nastaví údaje označeného miesta na obrazovku * @param root objekt View, ktorý reprezentuje obrazovku na zobrazenie detailu označeného miesta * @param place objekt z ktorého sa nastavia údaje na obrazovke */ private fun updateInfo(view: View, place: Place) { var cleared = view.findViewById<TextView>(R.id.placeCleared) var userName = view.findViewById<TextView>(R.id.placeUsername) var date = view.findViewById<TextView>(R.id.placeDate) var text = view.findViewById<TextView>(R.id.placeText) var clearedUsername = view.findViewById<TextView>(R.id.clearUsername) var clearedUsernameLabel = view.findViewById<TextView>(R.id.clearUserNameLabel) if (place.cleared!!){ cleared.text = "Vyčistené" var button = view.findViewById<Button>(R.id.button_takeAftPicture) button.visibility = View.GONE clearedUsername.visibility = View.VISIBLE clearedUsernameLabel.visibility = View.VISIBLE if (place.clearedBy == null){ clearedUsername.text = place.userName }else{ clearedUsername.text = place.clearedBy } }else{ cleared.text = "Nevyčistené" clearedUsername.visibility = View.GONE clearedUsernameLabel.visibility = View.GONE } userName.text = place.userName date.text = DateFormat.getDateFormat(Date(place.date?.time!!)) text.text = place.ClearText } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) placeViewModel = ViewModelProviders.of(this).get(PlaceViewModel::class.java) } /** * Nastaví fotky pred a po vyčistení */ fun downloadPictures(){ //Referencia na obrázok v úložisku Firebase var photoBeforeRef = FirebaseStorage.getInstance() .reference .child(place.photoBefore.toString()) val ONE_MEGABYTE: Long = 1024 * 1024 photoBeforeRef.getBytes(ONE_MEGABYTE).addOnSuccessListener { // Konvertujeme byteArray na bitmap var bmp = BitmapFactory.decodeByteArray(it, 0, it.size) pictures.add(Picture(bmp,"Fotka pred")) updatePictures() }.addOnFailureListener { // Handle any errors } if (place.photoAfter != null){ var photoAfterRef = FirebaseStorage.getInstance() .reference .child(place.photoAfter.toString()) photoAfterRef.getBytes(ONE_MEGABYTE).addOnSuccessListener { // Konvertujeme byteArray na bitmap var bmp = BitmapFactory.decodeByteArray(it, 0, it.size) pictures.add(Picture(bmp,"Fotka po")) updatePictures() }.addOnFailureListener { // Handle any errors } } } /** * Nastavenie obrázkov do ViewPagera */ fun updatePictures(){ var adapterPictures = AdapterPictures(pictures,view!!.context) viewPager.adapter = adapterPictures viewPager.setPadding(130,0,130,0) } /** * trieda na naplnenie ViewPagera obrázkami pred a po vyčitení */ inner class AdapterPictures : PagerAdapter{ private lateinit var models:List<Picture> private lateinit var context: Context constructor(models: List<Picture>, context: Context) : super() { this.models = models this.context = context } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view.equals(`object`) } override fun getItemPosition(`object`: Any): Int { var i = 0 while (i < count){ if (`object` as Picture == models[i]){ return i } i++ } return POSITION_NONE } override fun getCount(): Int { return models.size } /** * Vytvorí View, v ktorom naplní údaje o príspevku */ override fun instantiateItem(container: ViewGroup, position: Int): Any { var view = layoutInflater.inflate(R.layout.ticket_picture,null) var currentPicture = models[position] var imageView:ImageView var title:TextView imageView = view.findViewById(R.id.imageTicketPlace) title = view.findViewById<TextView>(R.id.pictureTitle) imageView.setImageBitmap(currentPicture.image) imageView.setOnClickListener { var intent = Intent(view.context,FullScreenImageActivity::class.java) var bitmap = currentPicture.image val bytes = ByteArrayOutputStream() bitmap!!.compress(Bitmap.CompressFormat.JPEG, 50, bytes) val path = MediaStore.Images.Media.insertImage(context.contentResolver, bitmap, "Title", null) intent.setData(Uri.parse(path.toString())) startActivity(intent) } title.setText(currentPicture.title) container.addView(view,0) return view } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } } /** * trieda na naplnenie ViewPagera komentármi */ inner class AdapterComments : PagerAdapter{ private lateinit var models:List<Comment> private lateinit var context: Context constructor(models: List<Comment>, context: Context) : super() { this.models = models this.context = context } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view.equals(`object`) } override fun getItemPosition(`object`: Any): Int { var i = 0 while (i < count){ if (`object` as Comment == models[i]){ return i } i++ } return POSITION_NONE } override fun getCount(): Int { return models.size } /** * Vytvorí View, v ktorom naplní údaje o komentári */ override fun instantiateItem(container: ViewGroup, position: Int): Any { var view = layoutInflater.inflate(R.layout.ticket_comment,null) var currentComment = models[position] var text:TextView var textUserName:TextView var date: TextView var ratingBar:RatingBar text = view.findViewById<TextView>(R.id.commentText) textUserName = view.findViewById<TextView>(R.id.commentUsername) ratingBar = view.findViewById<RatingBar>(R.id.commentRating) date = view.findViewById<TextView>(R.id.commentDate) text.setText(currentComment.comment) textUserName.setText(currentComment.userName) ratingBar.rating = currentComment.rating!! var df = android.text.format.DateFormat.getDateFormat(view.context) date.text = df.format(currentComment.date) container.addView(view,0) return view } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } } }
import PropTypes from 'prop-types' import { TransactionWrap, TableHeader, TableBody } from './TransactionHistory.styled' export default function TransactionHistory({ items }) { return ( <TransactionWrap> <TableHeader> <tr> <th>Type</th> <th>Amount</th> <th>Currency</th> </tr> </TableHeader> <TableBody> {items.map(item => ( <tr key = {item.id}> <td>{item.type}</td> <td>{item.amount}</td> <td>{item.currency}</td> </tr> ))} </TableBody> </TransactionWrap> ); } TransactionHistory.propTypes = { items: PropTypes.arrayOf( PropTypes.exact({ id: PropTypes.string.isRequired, type: PropTypes.string.isRequired, amount: PropTypes.string.isRequired, currency: PropTypes.string.isRequired, }) ).isRequired, };
{% macro grant_select(schema = target.schema, role = target.role) %} -- Here we are defining the actual SQL statement that we want to run. -- To do so, we add a 'set' block. -- This operates the same as a single line 'set' statement {% set query %} grant usage on schema {{ schema }} to role {{ role }}; grant select on all tables in schema {{ schema }} to role {{ role }}; grant select on all views in schema {{ schema }} to role {{ role }}; {% endset %} -- If I specify 'info = True', I'm going to get the message out into the actual terminal output as wess as the detailed logs. -- If 'info = False', which is the default, it's only going to go into the rich logs. {{ log('Granting select on all tables and views in chema ' ~ schema ~ ' to role ' ~ role, info = True ) }} -- 'do' - it is a Jinja call that will execute some sort of code. It won't print anything, but it will do whatever sort of operation we define here {% do run_query(query) %} {{ log('Privileges granted', info = True)}} {% endmacro %}
import { Component } from "react"; import FeedbackOptions from "./components/FeedbackOptions"; import Statistics from "./components/Statistics/Statistics"; import "./App.css"; class App extends Component { state = { good: 0, neutral: 0, bad: 0, }; handleClick = (option) => { this.setState((prevState) => ({ [option]: prevState[option] + 1 })); }; countTotalFeedback = () => { const { good, neutral, bad } = this.state; return good + neutral + bad; }; countPositiveFeedbackPercentage = () => { const { good } = this.state; const totalFeedback = this.countTotalFeedback(); if (totalFeedback === 0) { return 0; } return Math.round((good / totalFeedback) * 100); }; render() { const { good, neutral, bad } = this.state; const totalFeedback = this.countTotalFeedback(); const positivePercentage = this.countPositiveFeedbackPercentage(); return ( <div> <h1>Please leave Feedback</h1> <FeedbackOptions options={Object.keys(this.state)} onLeaveFeedback={this.handleClick()} /> {totalFeedback ? ( <Statistics good={good} neutral={neutral} bad={bad} totalFeedback={totalFeedback} positivePercentage={positivePercentage} /> ) : ( <p>No feedback</p> )} </div> ); } } export default App;
/** * @author wsl * created on 2017-04-12 * updated on 2017-04-12 */ (function () { 'use strict'; angular.module('hAdmin.pages.ui.modal').controller('modalCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) { var $ctrl = this; $ctrl.items = ['item1', 'item2', 'item3']; $ctrl.animationsEnabled = true; $scope.open = function (size, parentSelector) { var parentElem = parentSelector ? angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined; var modalInstance = $uibModal.open({ animation: $ctrl.animationsEnabled, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'app/pages/ui/modal/modal/temp/myModalContent.html', controller: 'ModalInstanceCtrl', controllerAs: '$ctrl', size: size, appendTo: parentElem, resolve: { items: function () { return $ctrl.items; } } }); modalInstance.result.then(function (selectedItem) { $ctrl.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; }]); angular.module('hAdmin.pages.ui.modal').controller('ModalInstanceCtrl', ['$scope', '$uibModalInstance', 'items', function ($scope, $uibModalInstance, items) { var $ctrl = this; $ctrl.items = items; $ctrl.selected = { item: $ctrl.items[0] }; $ctrl.ok = function () { $uibModalInstance.close($ctrl.selected.item); }; $ctrl.cancel = function () { $uibModalInstance.dismiss('cancel'); }; }]); })();
import { create } from 'zustand'; import { maxProjectilesOnScreen, defaultGameObjectData, defaultGameSettings, defaultLevelData } from './constants'; import { GameObjectData, ProjectileData, PlayerObjectData, GameObjectType, GameSettings, LevelFlowType, LevelData, GameState, LevelState, LevelSettings, LevelResults, } from './interfaces'; // import { Projectile } from './objects' interface ZustandState { // data player: PlayerObjectData; playerUpdater: number; projectiles: Map<string, ProjectileData>; projectilesUpdater: number; gameObjectsMap: Map<string, GameObjectData>; colliderObjects: Map<string, GameObjectData>; gameSettings: GameSettings; // current level currentLevelData: LevelData; // inital settings allLevelSettings: Map<string, LevelSettings>; // what happened in each level? did player win? what was the score? allLevelResults: Map<string, LevelResults>; // for each levelId, save initial data of objects // used for restarts allLevelObjectInitData: Map<string, Map<string, GameObjectData>>; // functions // players setPlayer: (newPlayer: PlayerObjectData) => void; setPlayerPosition: (newPlayerPosition: number[]) => void; setPlayerLastShootTimeMs: (newShootTime: number) => void; // projectiles addProjectile: (newProjectile: ProjectileData) => void; updateProjectileByIndex: (newProjectile: ProjectileData, projectileIndex: number) => void; updateProjectileById: (newProjectile: ProjectileData, projectileId?: string) => void; removeProjectileById: (projectileId: string) => void; removeProjectileByIndex: (projectileIndex: number, projectileId: string) => void; // objects addObject: (newObject: GameObjectData) => void; // damage damageObjectById: (targetId: string, damage?: number, sourceId?: string) => void; // Game settings setGameSettings: (gameSettings: GameSettings) => void; updateGameSettings: (gameSettings: any) => void; goToNextLevel: () => void; resetLevel: (levelId: string) => void; // Level settings/data setCurrentLevelData: (levelData: LevelData) => void; updateCurrentLevelData: (levelData: any) => void; updateAllLevelSettings: (levelSettingsWithId: Map<string, LevelSettings>) => void; updateAllLevelResults: (levelResultsWithId: Map<string, LevelResults>) => void; // timer updateTimeLeft: (timeLeftMs?: number) => void; } const updateProjectileByIndex = ( oldProjectiles: Map<string, ProjectileData>, index: number, newProjectile: ProjectileData, ) => { if (!oldProjectiles) { // old projectiles not found throw new Error('old projectiles not found'); } const oldKey = Array.from(oldProjectiles.keys())[index]; if (!oldKey) { // old key not found throw new Error('old key not found'); } oldProjectiles.set(oldKey, newProjectile); return oldProjectiles; }; const removeProjectileByIndex = (oldProjectiles: Map<string, ProjectileData>, index: number, id?: string) => { if (!oldProjectiles) { // old projectiles not found throw new Error('old projectiles not found'); } // get oldkey let oldKey; if (index === 0) { oldKey = oldProjectiles.keys().next().value; } else { oldKey = Array.from(oldProjectiles.keys())[index]; } if (!oldKey) { // oldKey not found throw new Error('oldKey not found'); } if (id && oldKey !== id) { // id provided, but did not match projectile key console.warn('id mismatch (removeProjectileByIndex)'); } else { oldProjectiles.delete(oldKey); } return oldProjectiles; }; const getTimeLeftFromLevelData = (levelData: LevelData) => { const timeElapsedMs = Date.now() - (levelData.startTimeMs || 0) - (levelData.pauseOffsetMs || 0); let timeLeftSec = (levelData.timeLimitSec || 0) - Math.floor(timeElapsedMs / 1000); if (timeLeftSec < 0) { timeLeftSec = 0; } return timeLeftSec; }; const useZustandStore = create<ZustandState>()((set) => ({ // default state player: { ...defaultGameObjectData, id: 'player', type: GameObjectType.Player, position: [0, -5, 0], lastShootTimeMs: 0, shootDelayMs: 100, }, // change updater number whenever we change dict // this lets zustand know that there has been a change // and we should rerender playerUpdater: 0, projectiles: new Map<string, ProjectileData>(), projectilesUpdater: 0, gameObjectsMap: new Map<string, GameObjectData>(), // live game objects with colliders colliderObjects: new Map<string, GameObjectData>(), gameSettings: defaultGameSettings, currentLevelData: defaultLevelData, allLevelSettings: new Map<string, LevelSettings>(), allLevelResults: new Map<string, LevelResults>(), allLevelObjectInitData: new Map(), // functions // players setPlayer: (newPlayer: PlayerObjectData) => set(() => ({ player: newPlayer, playerUpdater: Date.now(), })), setPlayerPosition: (newPlayerPosition: number[]) => set((state: any) => ({ player: { ...state.player, position: newPlayerPosition, }, playerUpdater: Date.now(), })), setPlayerLastShootTimeMs: (newShootTime: number) => set((state: any) => ({ player: { ...state.player, lastShootTimeMs: newShootTime, }, playerUpdater: Date.now(), })), // projectiles addProjectile: (newProjectile: ProjectileData) => set((state: any) => { if (!newProjectile) { throw new Error('new projectile not found'); } if (!newProjectile.id) { throw new Error('new projectile id not found'); } const tempProjectiles: Map<string, ProjectileData> = state.projectiles || new Map(); if (tempProjectiles.size >= maxProjectilesOnScreen) { // too many projectiles on screen // remove the first projectile // get key of first projectile const keyOfFirstProjectile = tempProjectiles.keys().next().value; tempProjectiles.delete(keyOfFirstProjectile); } tempProjectiles.set(newProjectile.id, newProjectile); return { projectiles: tempProjectiles, projectilesUpdater: Date.now(), }; }), updateProjectileByIndex: (newProjectile: ProjectileData, projectileIndex: number) => set((state: ZustandState) => { let tempProjectiles = state.projectiles || new Map(); tempProjectiles = updateProjectileByIndex(tempProjectiles, projectileIndex, newProjectile); // console.log("setting projectiles to", JSON.stringify(tempProjectiles)); return { projectiles: tempProjectiles, projectilesUpdater: Date.now(), }; }), updateProjectileById: (newProjectile: ProjectileData, inProjectileId?: string) => set((state: ZustandState) => { const tempProjectiles = state.projectiles || new Map(); const projectileId = inProjectileId || newProjectile.id; tempProjectiles.set(projectileId, newProjectile); return { projectiles: tempProjectiles, projectilesUpdater: Date.now(), }; }), removeProjectileById: (id: string) => set((state: ZustandState) => { const tempProjectiles = state.projectiles || new Map(); tempProjectiles.delete(id); return { projectiles: tempProjectiles, projectilesUpdater: Date.now(), }; }), removeProjectileByIndex: (projectileIndex: number, projectileId: string) => set((state: ZustandState) => { let tempProjectiles = state.projectiles || []; tempProjectiles = removeProjectileByIndex(tempProjectiles, projectileIndex, projectileId); return { projectiles: tempProjectiles, projectilesUpdater: Date.now(), }; }), // objects addObject: (newObject: GameObjectData) => set((state: ZustandState) => { if (!newObject) { throw new Error('new object not found (addObject)'); } if (!newObject.id) { throw new Error('new object missing id (addObject)'); } const tempColliderObj = state.colliderObjects || new Map(); if (newObject.collider) { tempColliderObj.set(newObject.id, newObject); } if (!newObject.parentLevelId) { throw new Error('new object missing parentLevelId (addObject)'); } // save the initial data for this object // used in restarts const allLevelObjectInitData = state.allLevelObjectInitData || {}; const initObjectsForThisLevel = allLevelObjectInitData.get(newObject.parentLevelId) || new Map(); initObjectsForThisLevel.set(newObject.id, structuredClone(newObject)); allLevelObjectInitData.set(newObject.parentLevelId, initObjectsForThisLevel); // clone objects map const newGameObjectsMap = new Map(state.gameObjectsMap); newGameObjectsMap.set(newObject.id, structuredClone(newObject)); return { gameObjectsMap: newGameObjectsMap, colliderObjects: tempColliderObj, allLevelObjectInitData: allLevelObjectInitData, }; }), removeObjectById: (objectId: string) => set((state: ZustandState) => { const tempObjects = state.gameObjectsMap || new Map(); tempObjects.delete(objectId); return { gameObjectsMap: tempObjects, }; }), updateObjectById: (newObject: GameObjectData) => set((state: ZustandState) => { if (!newObject) { throw new Error('new object not found (addObject)'); } if (!newObject.id) { throw new Error('new object missing id (addObject)'); } const tempObjects = state.gameObjectsMap || new Map(); tempObjects.set(newObject.id, newObject); return { gameObjectsMap: tempObjects, }; }), // damage damageObjectById: (targetId: string, damage?: number, sourceId?: string) => set((state: ZustandState) => { if (!sourceId) { console.warn('source id not found in damageObjectById'); } let damageAmount = 1; if (typeof damage === 'number') { damageAmount = damage; } else { console.warn('damage amount not found, using default (1) in damageObjectById'); } if (!targetId) { throw new Error('invalid targetId in damageObjectById'); } const tempObjects = new Map(state.gameObjectsMap); if (!tempObjects) { // old objects not found throw new Error('old objects not found'); } const target = tempObjects.get(targetId); if (!target) { // target not found in list throw new Error('target not found in object dict. (damageObjectById)'); } if (target.destroyed) { console.warn('target already destroyed (damageObjectById)'); return {}; } // console.log('target health', target.health); if (target.health && target.health > damageAmount) { target.health -= damageAmount; } else { // destroy target target.destroyed = true; let tempPlayerScore = state.currentLevelData.score || 0; const tempColliderObj = state.colliderObjects; tempColliderObj.delete(target.id); // count how many enemies are still alive let numLivingEnemies = 0; state.gameObjectsMap.forEach((thisObject: GameObjectData) => { if (!thisObject.destroyed && thisObject.isEnemy) { numLivingEnemies++; } }); console.log('enemies remaining:', numLivingEnemies, 'objects', state.gameObjectsMap.values); if (target.scoreValue) { tempPlayerScore += target.scoreValue; console.log('setting new score to', tempPlayerScore); } return { gameObjectsMap: tempObjects, colliderObjects: tempColliderObj, currentLevelData: { ...state.currentLevelData, numLivingEnemies: numLivingEnemies, score: tempPlayerScore, }, }; } return {}; }), // Game settings setGameSettings: (gameSettings: GameSettings) => set(() => { if (!gameSettings) { throw new Error('gameSettings is empty'); } return { gameSettings: gameSettings, }; }), updateGameSettings: (gameSettings: any) => set((state: ZustandState) => { if (!gameSettings) { throw new Error('gameSettings is empty'); } const oldGameSettings = state.gameSettings; return { gameSettings: { ...oldGameSettings, ...gameSettings, }, }; }), goToNextLevel: () => set((state: ZustandState) => { const tempGameSettings = state.gameSettings; const currentLevel = tempGameSettings.currentLevel; const levelFlow = tempGameSettings.levelFlow; const levelFlowType = tempGameSettings.levelFlowType; if (levelFlowType === LevelFlowType.Linear) { if (!currentLevel) { throw new Error('no current level found'); } let currentLevelIndex = levelFlow.indexOf(currentLevel); if (currentLevelIndex === -1) { throw new Error('current level not in level flow'); } currentLevelIndex++; if (currentLevelIndex === levelFlow.length) { // we're out of levels. end game return { gameSettings: { ...tempGameSettings, gameState: GameState.EndScreen, }, }; } // move to next level const newLevel = levelFlow[currentLevelIndex]; return { gameSettings: { ...tempGameSettings, goToLevel: newLevel, }, }; } console.warn('cannot go to next level,', 'flow type is not linear (goToNextLevel)'); return {}; }), resetLevel: (levelId: string) => set((state: ZustandState) => { const newProjectiles: Map<string, ProjectileData> = new Map(); const tempGameObjectsMap = new Map(state.allLevelObjectInitData.get(levelId) || new Map()); const thisLevelSettings = state.allLevelSettings.get(levelId); console.log('all level settings', state.allLevelSettings); if (!thisLevelSettings) { throw new Error('level settings not found for this level ' + levelId + ' (resetLevel)'); } const newColliderObjs = new Map<string, GameObjectData>(); tempGameObjectsMap.forEach((thisGameObject, thisGameObjectId) => { // we need to clone every game object so that when we reset the level, // these objects are still in their initial states tempGameObjectsMap.set(thisGameObjectId, structuredClone(thisGameObject)); }); tempGameObjectsMap.forEach((thisObject) => { if (thisObject.collider && thisObject.id) { newColliderObjs.set(thisObject.id, thisObject); } }); const newLevelData: LevelData = { ...thisLevelSettings, timeLeftSec: thisLevelSettings.timeLimitSec || Infinity, levelState: LevelState.NormalPlay, startTimeMs: Date.now(), score: 0, }; return { gameObjectsMap: tempGameObjectsMap, projectiles: newProjectiles, currentLevelData: newLevelData, colliderObjects: newColliderObjs, }; }), // Level settings setCurrentLevelData: (levelData: LevelData) => set(() => { if (!levelData) { throw new Error('levelSettings is empty (setLevelSettings)'); } return { currentLevelData: levelData, }; }), updateCurrentLevelData: (levelData: any) => set((state: ZustandState) => { if (!levelData) { throw new Error('levelSettings is empty (updateCurrentLevelSettings)'); } const oldLevelData = state.currentLevelData; const newLevelData = { ...oldLevelData, ...levelData, }; const timeLeftSec = getTimeLeftFromLevelData(newLevelData); return { currentLevelData: { ...newLevelData, timeLeftSec: timeLeftSec, }, }; }), updateAllLevelSettings: (levelSettingsWithId: Map<string, LevelSettings>) => set((state: ZustandState) => { if (!levelSettingsWithId) { throw new Error('levelSettingsWithId is empty (updateAllLevelSettings)'); } const tempAllLevelSettings: Map<string, LevelSettings> = state.allLevelSettings || new Map(); levelSettingsWithId.forEach((thisLevelSettings, thisLevelId) => { tempAllLevelSettings.set(thisLevelId, thisLevelSettings); }); return { allLevelSettings: tempAllLevelSettings, }; }), updateAllLevelResults: (levelResultsWithId: Map<string, LevelResults>) => set((state: ZustandState) => { if (!levelResultsWithId) { throw new Error('levelResultsWithId is empty (updateAllLevelResults)'); } const tempAllLevelResults: Map<string, LevelResults> = state.allLevelResults || new Map(); levelResultsWithId.forEach((thisLevelResults, thisLevelId) => { tempAllLevelResults.set(thisLevelId, thisLevelResults); }); console.log('level results with id', levelResultsWithId); console.log('tempAllLevelresults', tempAllLevelResults); return { allLevelResults: tempAllLevelResults, }; }), // timer updateTimeLeft: (inTimeLeftSec?: number) => set((state: ZustandState) => { // if timeLeftMs is provided, use that. // if not, calculate time left from level settings if (typeof inTimeLeftSec !== 'undefined') { return { currentLevelData: { ...state.currentLevelData, timeLeftSec: inTimeLeftSec, }, }; } const timeLeftSec = getTimeLeftFromLevelData(state.currentLevelData); return { currentLevelData: { ...state.currentLevelData, timeLeftSec: timeLeftSec, }, }; }), })); export { useZustandStore, ZustandState };
package love.forte.simbot.component.kritor.core.actor.internal import io.grpc.Status import io.grpc.Status.Code import io.kritor.group.* import io.kritor.message.Contact import io.kritor.message.Scene import io.kritor.message.contact import love.forte.simbot.ability.DeleteFailureException import love.forte.simbot.ability.DeleteOption import love.forte.simbot.ability.StandardDeleteOption import love.forte.simbot.common.collectable.Collectable import love.forte.simbot.common.collectable.flowCollectable import love.forte.simbot.common.id.* import love.forte.simbot.common.id.LongID.Companion.ID import love.forte.simbot.common.id.StringID.Companion.ID import love.forte.simbot.common.id.ULongID.Companion.ID import love.forte.simbot.component.kritor.core.actor.KritorBasicGroupInfo import love.forte.simbot.component.kritor.core.actor.KritorGroup import love.forte.simbot.component.kritor.core.actor.KritorGroupMember import love.forte.simbot.component.kritor.core.actor.RemainCountAtAll import love.forte.simbot.component.kritor.core.bot.internal.KritorBotImpl import love.forte.simbot.component.kritor.core.bot.internal.sendMessage import love.forte.simbot.component.kritor.core.message.KritorMessageReceipt import love.forte.simbot.component.kritor.core.message.internal.toReceipt import love.forte.simbot.component.kritor.core.message.resolve import love.forte.simbot.message.Message import love.forte.simbot.message.MessageContent import kotlin.coroutines.CoroutineContext internal abstract class AbstractKritorBasicGroupInfoImpl : KritorBasicGroupInfo { internal abstract val bot: KritorBotImpl internal abstract val contact: Contact internal abstract val groupId: Long override val subPeer: ID? get() = null override suspend fun send(messageContent: MessageContent): KritorMessageReceipt { val contact = contact return bot.sendMessage( contact = contact, messageContent = messageContent, ).toReceipt(bot, contact) } override suspend fun send(message: Message): KritorMessageReceipt { val contact = contact return bot.sendMessage(contact, message).toReceipt(bot, contact) } override suspend fun send(text: String): KritorMessageReceipt { val contact = contact return bot.sendMessage(contact, text).toReceipt(bot, contact) } override suspend fun delete(vararg options: DeleteOption) { runCatching { bot.services.groupService.leaveGroup( leaveGroupRequest { this.groupId = [email protected] } ) }.onFailure { e -> if (StandardDeleteOption.IGNORE_ON_FAILURE !in options) { throw DeleteFailureException(e) } } } } internal class KritorBasicGroupInfoImpl( override val bot: KritorBotImpl, val source: GroupInfo ) : AbstractKritorBasicGroupInfoImpl() { override val groupId: Long get() = source.groupId override val contact: Contact get() = contact { this.scene = Scene.GROUP this.peer = groupId.toString() } override val peer: ULongID get() = source.groupId.toULong().ID } internal class KritorBasicGroupEventInfoImpl( override val bot: KritorBotImpl, val source: io.kritor.event.Contact ) : AbstractKritorBasicGroupInfoImpl() { override val peer: StringID get() = source.peer.ID override val groupId: Long get() = source.peer.toULong().toLong() override val contact: Contact get() = source.resolve() } internal fun GroupInfo.toGroupInfo(bot: KritorBotImpl): KritorBasicGroupInfoImpl = KritorBasicGroupInfoImpl(bot, this) internal fun io.kritor.event.Contact.toGroupInfo(bot: KritorBotImpl): KritorBasicGroupEventInfoImpl = KritorBasicGroupEventInfoImpl(bot, this) /** * * @author ForteScarlet */ internal class KritorGroupInfoImpl( private val bot: KritorBotImpl, private val source: GroupInfo, private val sourceGroupInfo: AbstractKritorBasicGroupInfoImpl, ) : KritorGroup { override val id: ULongID get() = source.groupId.toULong().ID override val ownerId: ULongID get() = source.owner.toULong().ID override var name: String = source.groupName override var remark: String = source.groupRemark override val coroutineContext: CoroutineContext = bot.subCoroutineContext override suspend fun modifyName(name: String) { bot.services.groupService.modifyGroupName( modifyGroupNameRequest { this.groupId = source.groupId this.groupName = name } ) this.name = name } override suspend fun modifyRemark(remark: String) { bot.services.groupService.modifyGroupRemark( modifyGroupRemarkRequest { this.groupId = source.groupId this.remark = remark } ) this.remark = remark } override fun members(refresh: Boolean): Collectable<KritorGroupMember> = flowCollectable { val resp = bot.services.groupService.getGroupMemberList( getGroupMemberListRequest { this.groupId = source.groupId this.refresh = refresh } ) if (resp.groupMemberInfoCount == 0) { return@flowCollectable } for (memberInfo in resp.groupMemberInfoList) { emit(memberInfo.toMember(bot, source.groupId)) } } override suspend fun member(id: ID, refresh: Boolean): KritorGroupMember? { val memberInfo = runCatching { bot.services.groupService.getGroupMemberInfo( getGroupMemberInfoRequest { this.groupId = source.groupId this.refresh = refresh if (id is NumericalID) { this.uin = id.toLong() } else { this.uid = id.literal } } ) }.getOrElse { e -> val status = Status.fromThrowable(e) if (status.code == Code.NOT_FOUND) null else throw e } return memberInfo?.groupMemberInfo?.toMember(bot, source.groupId) } override suspend fun botAsMember(): KritorGroupMember = with(bot.currentAccount.accountUin.ID) { member(this, false) ?: member(this, true) // refresh and try again.? ?: error("Bot info not found in group(id=${source.groupId}, name=${source.groupName})") } override suspend fun delete(vararg options: DeleteOption) { sourceGroupInfo.delete(options = options) } override suspend fun send(messageContent: MessageContent): KritorMessageReceipt = sourceGroupInfo.send(messageContent) override suspend fun send(message: Message): KritorMessageReceipt = sourceGroupInfo.send(message) override suspend fun send(text: String): KritorMessageReceipt = sourceGroupInfo.send(text) override suspend fun getRemainCountAtAll(): RemainCountAtAll { val result = bot.services.groupService.getRemainCountAtAll( getRemainCountAtAllRequest { this.groupId = source.groupId } ) return RemainCountAtAllImpl( accessAtAll = result.accessAtAll, forGroup = result.remainCountForGroup, forSelf = result.remainCountForSelf, ) } } private data class RemainCountAtAllImpl( override val accessAtAll: Boolean, override val forGroup: Int, override val forSelf: Int ) : RemainCountAtAll { override fun toString(): String { return "RemainCountAtAll(accessAtAll=$accessAtAll, forGroup=$forGroup, forSelf=$forSelf)" } } internal fun GroupInfo.toGroup( bot: KritorBotImpl, groupInfoImpl: AbstractKritorBasicGroupInfoImpl = toGroupInfo(bot) ): KritorGroupInfoImpl = KritorGroupInfoImpl(bot, this, groupInfoImpl)
package com.piterrus.dagger2.presentation.binds_instance.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.piterrus.dagger2.App import com.piterrus.dagger2.presentation.binds_instance.di.DaggerBindsInstanceComponent @Composable fun BindsInstanceScreen() { val component = remember { DaggerBindsInstanceComponent.builder() .appComponent(App.appComponent) .string(string = "bindsInstanceString") .buildBindsInstanceComponent() } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = component.stringByBindsInstance(), style = MaterialTheme.typography.headlineSmall, color = Color.Black ) Spacer(modifier = Modifier.height(20.dp)) Text( text = component.stringByModule(), style = MaterialTheme.typography.headlineSmall, color = Color.Black ) } }
***************************************************************** * OHMS LAW CALCULATIONS * * * * A simple program that calculates the relationship between * * voltage, current, and resistance in an electric circuit. * * * ***************************************************************** identification division. program-id. ohmslaw. author. Chipman. data division. working-storage section. ***************************************************************** * * * Ohm's Laws * * * * ^ * * / \ * * / E \ * * /_____\ * * / | \ * * / I | R \ * * /_____|_____\ * * * * E = I * R I = E / R R = E / I * * * ***************************************************************** * Data-entry-fields. 01 quantity1-in pic x(20). 01 quantity2-in pic x(20). 01 law pic 9. 01 law-in pic x. *01 power-factor-in pic x(8). *01 yes-no pic x. * 88 affirm value "Y". * 88 neg value "N". *01 three-phase-flag pic x. * 88 three-phase value "Y". * 88 single-phase value "N". * Calculated-fields. 01 quantity1 pic 9(9)v9(9). 01 quantity2 pic 9(9)v9(9). 01 voltage pic 9(9)v9(9). 01 current pic 9(9)v9(9). 01 resistance pic 9(9)v9(9). *01 power-factor pic 99v99 value 1. *01 square-root3 pic 99v99 value 1. *01 old-watts pic 9(6)v99. *01 old-kilowatts pic 999v9. * Displayed-fields. 01 description1 pic x(10). 01 description2 pic x(10). 01 description3 pic x(10). 01 unit1 pic x(10) value " ohms". 01 unit2 pic x(10) value " amps". 01 unit3 pic x(10) value " volts". 01 voltage-out pic zzz,zzz,zz9.999 usage display. 01 current-out pic zzz,zzz,zz9.9(6) usage display. 01 resistance-out pic zzz,zzz,zz9.999 usage display. *01 old-kw-out pic zz,zz9.9 usage display. *01 new-kw-out pic zz,zz9.9 usage display. * Optional-display-fields can be commented out after debugging *01 power-factor-out pic 9.99 usage display. *01 squareroot3-out pic 9.99 usage display. * Constant-text. * 01 quantity-too-much pic x(26) * value "Quantity must be <= 9999.9". 01 not-numeric pic x(16) value " is NOT numeric.". procedure division. main-paragraph. perform opening-screen-data-entry perform quantity1-data-entry perform quantity2-data-entry perform calculate-it perform end-program. * Display opening screen & commence data entry opening-screen-data-entry. display spaces display "***** OHM'S LAW CALCULATOR UTILITY BEGINS *****" display "Written by, Clifford A. Chipman, EMIT" display "October 4, 2020" display spaces display "in Enterprise COBOL v6.3 for z/OS" display spaces display "Enter zero for any parameter to end the program." display spaces display " #1 - Calculate R" display " #2 - Calculate I" display " #3 - Calculate E" display spaces display "Select a law (1, 2, 3, or 0 to exit): " with no advancing accept law-in evaluate true when law-in = "0" perform end-program when law-in = "1" or "R" or "r" move "voltage" to description1 move "current" to description2 move "resistance" to description3 move 1 to law when law-in = "2" or "I" or "i" move "voltage" to description1 move "resistance" to description2 move "current" to description3 move 2 to law when law-in = "3" or "E" or "e" move "current" to description1 move "resistance" to description2 move "voltage" to description3 move 3 to law when other display spaces display "Enter 0 through 3 ONLY" go to opening-screen-data-entry end-evaluate. quantity1-data-entry. * display spaces display "Enter " description1 ": " with no advancing accept quantity1-in * Did the user enter a valid numeric value? if function test-numval(quantity1-in) IS NOT EQUAL ZERO then display description1 not-numeric go to quantity1-data-entry else compute quantity1 = function numval(quantity1-in) end-if evaluate true when quantity1 IS EQUAL ZERO perform end-program * when quantity1 IS GREATER THAN 9999.9 * display quantity-too-much * go to quantity1-data-entry end-evaluate. quantity2-data-entry. * display spaces display "Enter " description2 ": " with no advancing accept quantity2-in * Did the user enter a valid numeric value? if function test-numval(quantity2-in) IS NOT EQUAL ZERO then display description2 not-numeric go to quantity2-data-entry else compute quantity2 = function numval(quantity2-in) end-if evaluate true when quantity2 IS EQUAL ZERO perform end-program * when quantity2 IS GREATER THAN 9999.9 * display quantity-too-much * go to quantity1-data-entry end-evaluate. calculate-it. ***************************************************************** * * * Ohm's Laws * * * * ^ * * / \ * * / E \ * * /_____\ * * / | \ * * / I | R \ * * /_____|_____\ * * * * E = I * R I = E / R R = E / I * * * ***************************************************************** evaluate law when 1 move quantity1 to voltage move quantity2 to current divide voltage by current giving resistance rounded evaluate true when resistance IS LESS THAN 1 multiply 1000 by resistance move " milliohms" to unit1 when resistance IS GREATER THAN OR EQUAL TO 1000 divide 1000 into resistance move " kilohms" to unit1 when resistance IS GREATER THAN OR EQUAL TO 1000000 divide 1000000 into resistance move " megohms" to unit1 end-evaluate move resistance to resistance-out display resistance-out unit1 when 2 move quantity1 to voltage move quantity2 to resistance divide voltage by resistance giving current rounded evaluate true when current IS LESS THAN 1 multiply 1000 by current move " milliamps" to unit2 when resistance IS GREATER THAN OR EQUAL TO 1000 divide 1000 into current move " kiloamps" to unit2 when resistance IS GREATER THAN OR EQUAL TO 1000000 divide 1000000 into current move " megaamps" to unit2 end-evaluate move current to current-out display current-out unit2 when 3 move quantity1 to current move quantity2 to resistance multiply current by resistance giving voltage rounded evaluate true when voltage IS LESS THAN 1 multiply 1000 by voltage move " millivolts" to unit3 when voltage IS GREATER THAN OR EQUAL TO 1000 divide 1000 into voltage move " kilovolts" to unit3 when voltage IS GREATER THAN OR EQUAL TO 1000000 divide 1000000 into voltage move " megavolts" to unit3 end-evaluate move voltage to voltage-out display voltage-out unit3 * when other * display spaces * display "Enter 0 through 3 ONLY" * go to opening-screen-data-entry end-evaluate. end-program. display spaces display "***** OHM'S LAW CALCULATOR UTILITY ENDS *****" display spaces stop run.
import { createAsyncThunk } from "@reduxjs/toolkit" import { extname } from "@tauri-apps/api/path" import { SourceType } from "@/types" import { open } from "@tauri-apps/api/dialog" import { addFromUrl } from "./addFromUrl" export const addFromFiles = createAsyncThunk("source/addFromFiles", async (paths: string[], thunkAPI) => { if (paths.length === 0) { const selected = await open({ multiple: true, filters: [{ name: "Geospatial file", extensions: ["csv", "geojson", "gpx", "mbtiles", "shp"], }], }) if (!selected) { return } if (Array.isArray(selected)) { paths = selected } else { paths = [selected] } } for (const path of paths) { let ext = await extname(path) if (ext) { ext = ext.toLowerCase() } switch (ext) { case "mbtiles": { const url = `sphere://mbtiles${path}` thunkAPI.dispatch(addFromUrl({ url, type: SourceType.MVT, // type: SourceType.Raster, })) break } default: { const url = `sphere://source${path}` thunkAPI.dispatch(addFromUrl({ url, type: SourceType.Geojson, })) break } } } // this is true side effects // thunkAPI.dispatch(actions.app.showLeftSidebar()) // await listenerApi.delay(1000) // const state = listenerApi.getState() as RootState // const id = state.source.lastAdded // if (!id) { // return // } // const geom = state.source.items[id].data // const bbox = turf.bbox(geom); // listenerApi.dispatch(fitBounds({ // mapId: "spheremap", // bounds: bbox as mapboxgl.LngLatBoundsLike // })) })
import { InputTypes, Literal } from '../RlpEncoder'; import { isValueBetween } from './isBetween'; import { DecodingResults, EncodingResults, SimpleTypes, TypeEncoderDecoder, } from './TypeEncoderDecoder'; export class ArrayEncoderDecoder implements TypeEncoderDecoder<Array<Literal>> { public encode({ input, encoder, }: { input: Array<Literal>; encoder: ({ input }: { input: InputTypes }) => EncodingResults; }): EncodingResults { let output = ''; let length = 0; input.forEach((inputElement) => { const { encoding: encoded, length: encodingLength } = encoder({ input: inputElement, }); if (Array.isArray(inputElement)) { length += 1; } output += encoded; length += encodingLength; }); if (length < 55) { const encoding = Buffer.from([0xc0 + length]).toString('hex') + output; return { encoding, length, }; } else { const lengthInHex = length.toString(16); const paddingLength = lengthInHex.padStart(lengthInHex.length % 2); const encoding = Buffer.from([ 0xf7 + Math.ceil(parseFloat(paddingLength.length.toString()) / 2), parseInt(paddingLength, 16), ]).toString('hex') + output; return { encoding, length: 3, }; } } public decode({ input, fromIndex, decoder, }: { input: Buffer; fromIndex: number; decoder: ({ input, index, }: { input: Buffer; index: number; }) => DecodingResults; }): DecodingResults { if (input[fromIndex] === 0xc0) { return { decoding: [], newIndex: fromIndex + 1, }; } else if (0xf7 < input[fromIndex]) { const lengthOfLengthBuffer = input[fromIndex++] - 0xf7; const actualLength = Number.parseInt( input .slice(fromIndex, fromIndex + lengthOfLengthBuffer) .toString('hex'), 16 ); const arrayResults: SimpleTypes[] = []; let currentIndex = fromIndex + lengthOfLengthBuffer; while (currentIndex <= fromIndex + actualLength) { const results = decoder({ input, index: currentIndex }); currentIndex = results.newIndex; arrayResults.push(results.decoding); } return { decoding: arrayResults, newIndex: currentIndex, }; } else { const length = input[fromIndex] - 0xc0; const arrayResults: SimpleTypes[] = []; let currentIndex = fromIndex + 1; while (currentIndex <= fromIndex + length) { const results = decoder({ input, index: currentIndex }); currentIndex = results.newIndex; arrayResults.push(results.decoding); } return { decoding: arrayResults, newIndex: currentIndex, }; } } public isDecodeType({ input }: { input: number }): boolean { const isLongArray = isValueBetween({ value: input, min: 0xc1, max: 0xff, }); const isSingleElement = input === 0xc0; return isLongArray || isSingleElement; } public isEncodeType({ input }: { input: unknown }): boolean { return Array.isArray(input); } }
package com.mastercoding.firestoreapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private Button saveBtn; private Button updateBtn; private Button deleteBtn; private Button readBtn; private TextView textView; private EditText nameET; private EditText emailET; // Firebase Firestore: private FirebaseFirestore db = FirebaseFirestore.getInstance(); private DocumentReference friendsRef = db.collection("Users") .document("Ndh6rrPiQq3qeg15gXtZ"); private CollectionReference collectionReference = db.collection("Users"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); nameET = findViewById(R.id.nameET); emailET = findViewById(R.id.emailET); textView = findViewById(R.id.text); saveBtn = findViewById(R.id.SaveBTN); deleteBtn = findViewById(R.id.deleteBTN); updateBtn = findViewById(R.id.updateBTN); readBtn = findViewById(R.id.readBTN); saveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SaveDataToNewDocument(); } }); readBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GetAllDocumentsInCollection(); } }); updateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UpdateSpecificDocument(); } }); deleteBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DeleteAll(); } }); } private void SaveDataToNewDocument(){ String name = nameET.getText().toString(); String email = emailET.getText().toString(); Friend friend = new Friend(name, email); collectionReference.add(friend).addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { String docId = documentReference.getId(); } }); } private void GetAllDocumentsInCollection(){ collectionReference.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { String data = ""; // This code is executed when data retrieval is successful // the queryDocumentSnapshot contains the documents in the collection // Each queryDocumentSnapshot ---> represents a document in the collection for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots){ // Transforming snapshots into objects Friend friend = snapshot.toObject(Friend.class); data += "Name: "+friend.getName() + " Email: "+friend.getEmail()+"\n"; } textView.setText(data); } }); } private void UpdateSpecificDocument(){ String name = nameET.getText().toString(); String email = emailET.getText().toString(); friendsRef.update("name" , name); friendsRef.update("email" , email); } private void DeleteAll(){ friendsRef.delete(); } }
import { useState } from 'react'; import { Card, Button, Input } from "@nextui-org/react"; import CloudUploadIcon from '@mui/icons-material/CloudUpload'; import { useSelector, useDispatch } from 'react-redux'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; import { caption, description } from "../store/slices/PostSlice"; import { extractUserIdFromToken } from '../utils/extractUserIdFromToken'; let formData; const Post = () => { const navigate = useNavigate(); const [selectedImage, setSelectedImage] = useState(null); const captionValue = useSelector(state => state.posts.caption); const descriptionValue = useSelector(state => state.posts.description); const [file, setFile] = useState(null); const dispatch = useDispatch(); const handleImageChange = (event) => { const selectedFile = event.target.files[0]; if (selectedFile) { const reader = new FileReader(); reader.onloadend = () => { setSelectedImage(reader.result); }; reader.readAsDataURL(selectedFile); setFile(selectedFile); } }; const captionChangeHandler = (e) => { dispatch(caption(e.target.value)) } const descriptionChangehandler = (e) => { dispatch(description(e.target.value)) } const handleSubmit = async (e) => { e.preventDefault(); const token = localStorage.getItem("token"); console.log(token); const userId = extractUserIdFromToken(token) console.log(userId); formData = new FormData(); formData.append("myImage", file, "image.png"); formData.append("caption", captionValue); formData.append("description", descriptionValue); formData.append("userId", userId); console.log(formData); const res = await axios.post("https://wandrlust-server.fly.dev/uploadPhoto", formData, { headers: { 'Content-Type': 'multipart/form-data' } }) console.log(res); navigate("/feeds"); } return ( <div> <div style={{ display: 'flex', justifyContent: 'center' }}> <Card className="py-4" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '800px', gap: '2rem' }}> <div className="pb-0 pt-2 px-4 flex-col items-start" style={{ display: 'flex', alignItems: 'center' }}> <div> <h1 style={{ color: 'gray', fontSize: '40px', fontWeight: 'bold' }}>What's in your mind?</h1> </div> </div> <div style={{ display: 'flex', flexDirection: 'row', width: '100%', justifyContent: 'space-around' }} > <div style={{ width: '50%', border: '3px solid black' }} > {selectedImage && ( <img src={selectedImage} alt="Selected" style={{ width: '100%', height: '200px', objectFit: 'cover' }} /> )} </div> <div style={{ width: '40%', display: 'flex', flexDirection: 'column', gap: '2rem' }} > <Input onChange={captionChangeHandler} type="text" label="Caption" radius="full" /> <Input onChange={descriptionChangehandler} type="text" label="Description" radius="full" /> </div> </div> <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', width: '100%' }}> <div> <div> Choose an Image to Post: </div> <input style={{ border: '1px solid black' }} type="file" name="myImage" onChange={handleImageChange} /> </div> </div> <div> <Button style={{ backgroundColor: '#f94566', color: 'white', width: '100%', height: '3rem', fontSize: '25px', fontWeight: 'bold' }} startContent={<CloudUploadIcon />} variant="shadow" onClick={handleSubmit} > Create Post </Button> </div> </Card> </div> </div> ); }; export default Post;
import { CommonModule } from '@angular/common'; import { Component, OnInit, OnDestroy } from '@angular/core'; import { UserSidemenuComponent } from '../user-sidemenu/user-sidemenu.component'; import { UserService } from '../../services/user.service'; import { CommonService } from '../../services/common.service'; import { Subscription } from 'rxjs'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-leaderboard', standalone: true, imports: [CommonModule, UserSidemenuComponent], templateUrl: './leaderboard.component.html', styleUrl: './leaderboard.component.scss' }) export class LeaderboardComponent implements OnInit, OnDestroy { players: any[] = []; user: any; data: any[] = []; games: any[] = []; tab: string = 'all-time'; data_ready:boolean = false; userServiceSubscription!: Subscription; daily_start_time: number = this.commonService.getEpochTimeForTodayAtMidnight(); monthly_start_time: number = this.commonService.getFirstDayOfMonthEpoch(); constructor( public userService: UserService, public commonService: CommonService, public router: Router ) { } ngOnInit(): void { this.userServiceSubscription = this.userService._getUser.subscribe((currentUser) => { if (!currentUser){ this.router.navigate(['login']); return; } this.user = currentUser; //console.log('this.user', this.user); this.loadData(); }); } ngOnDestroy(): void { if (this.userServiceSubscription) this.userServiceSubscription.unsubscribe(); } loadData() { this.userService.getAllGames().subscribe((data: any) => { this.games = data; //console.log('games', this.games, this.user.venue_id); this.filterPlayers(); }) } filterPlayers() { this.data_ready =false; var games:any = []; if (this.tab == 'all-time') games = this.games; else if (this.tab == 'monthly') games = this.games.filter((x: any) => { return x.timestamp >= this.monthly_start_time }); else if (this.tab == 'daily') games = this.games.filter((x: any) => { return x.timestamp >= this.daily_start_time }); this.players = []; games.forEach((x: any) => { //x.date = this.commonService.getDateString(x.timestamp); var record = this.players.find((n: any) => { return n.user_id == x.user_id }); if (!record) this.players.push({ user_id: x.user_id, username: x.username, image: x.user_image }); }); this.players.forEach((x: any) => { var player_games = games.filter((n: any) => { return n.user_id == x.user_id }); x.games = player_games.length; var points = 0; var max_score = 0; player_games.forEach((n: any) => { points += (n.score ? n.score : 0); if (n.score > max_score) max_score = n.score; }); x.points = points; x.max_score = max_score; }); //sort by points this.players = this.players.sort((a:any,b:any) => { return b.points - a.points}); this.data_ready =true; console.log('this.games', this.games); console.log('this.players', this.players); } }
declare class ApiResponse { code: number; message: string; constructor(code: number, message: string); } declare class PackageManager { private messageBuffer; private messageLength; private msgPointer; private decodedMsg; private amountOfBytes; private messageReaded; private lengthBytes; private subArrayLengthBytes; private lengthReaded; constructor(); /** * Handles the received data, either in string or buffer format. * If a string is received, it converts it to Buffer in UTF-8 format. * Reads the received data to determine the message length and the message itself. * * @param data The received data, can be a string or a buffer. * @returns An array with the decoded messages. */ manageData(data: string | Buffer): Buffer[]; /** * Reads the length of the message from the data buffer. * * @param data The buffer containing the data. */ private readMessageLength; /** * Reads the message from the data buffer. * * @param data The buffer containing the message. */ private readMessage; /** * Resets the variables to start reading a new message. */ private startNewMessage; /** * Handles the received message data. * * @param messageData The buffer containing the message data. * @returns The complete message bytes if available, otherwise null. */ private handleMessageData; /** * Translates an array of message bytes into an array of parsed messages. * * @param messagesBytes An array containing the message bytes to translate. * @returns An array of parsed messages. */ translateMessages(messagesBytes: Buffer[]): any[]; /** * Sends a message over the provided socket. * * @param socket The socket to send the message through. * @param message The message to send. * @returns A Promise that resolves with an ApiResponse if the message is successfully sent, or rejects with an ApiResponse if there is an error. */ sendMessage(socket: any, message: string): Promise<ApiResponse>; } export { PackageManager };
using System; namespace Foundation2 { class Program { static void Main(string[] args) { Address usaAddress = new Address("123 Main St", "Idaho", "ID", "USA"); Customer usCustomer = new Customer("Jack Jones", usaAddress); Address intlAddress = new Address("456 World Ave", "Spain", "ESP", "EU"); Customer intlCustomer = new Customer("Amy Smith", intlAddress); Product product1 = new Product("Product A", 1, 10.0m, 2); Product product2 = new Product("Product B", 2, 15.0m, 3); Order order1 = new Order(usCustomer); order1.AddProduct(product1); order1.AddProduct(product2); Order order2 = new Order(intlCustomer); order2.AddProduct(product1); // Displaying information for order 1 Console.WriteLine("Order 1 - Packing Label:"); Console.WriteLine(order1.GetPackingLabel()); Console.WriteLine("\nOrder 1 - Shipping Label:"); Console.WriteLine(order1.GetShippingLabel()); Console.WriteLine("\nOrder 1 - Total Cost:"); Console.WriteLine($"Total Cost: ${order1.CalculateTotalCost()}"); // Displaying information for order 2 Console.WriteLine("\nOrder 2 - Packing Label:"); Console.WriteLine(order2.GetPackingLabel()); Console.WriteLine("\nOrder 2 - Shipping Label:"); Console.WriteLine(order2.GetShippingLabel()); Console.WriteLine("\nOrder 2 - Total Cost:"); Console.WriteLine($"Total Cost: ${order2.CalculateTotalCost()}"); } } }
package com.car_equipment.Service; import com.car_equipment.DTO.CategoryDTO; import com.car_equipment.Model.Category; import com.car_equipment.Repository.CategoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class CategoryService { @Autowired private CategoryRepository categoryRepository; // Lấy danh sách Category public List<CategoryDTO> getAllCategories() { List<Category> categories = categoryRepository.findAll(); return categories.stream().map(CategoryDTO::transferToDTO).collect(Collectors.toList()); } // Xem chi tiết Category public CategoryDTO getCategoryById(String id) { Optional<Category> category = categoryRepository.findById(id); return category.map(CategoryDTO::transferToDTO).orElse(null); } // Thêm Category public CategoryDTO addCategory(CategoryDTO categoryDTO) { Category category = new Category(); category.setName(categoryDTO.getName()); category.setImageCategory(categoryDTO.getImageCategory()); Category savedCategory = categoryRepository.save(category); return CategoryDTO.transferToDTO(savedCategory); } // Sửa Category public CategoryDTO updateCategory(String id, CategoryDTO categoryDTO) { Optional<Category> categoryOptional = categoryRepository.findById(id); if (categoryOptional.isPresent()) { Category category = categoryOptional.get(); category.setName(categoryDTO.getName()); category.setImageCategory(categoryDTO.getImageCategory()); Category updatedCategory = categoryRepository.save(category); return CategoryDTO.transferToDTO(updatedCategory); } return null; } // Xoá Category public boolean deleteCategory(String id) { Optional<Category> categoryOptional = categoryRepository.findById(id); if (categoryOptional.isPresent()) { categoryRepository.deleteById(id); return true; } return false; } }
import { Request, Response, NextFunction } from 'express'; import httpStatus from '../enums/httpStatus'; import Conflict from '../errors/Conflict'; import Invalid from '../errors/Invalid'; import NotFound from '../errors/NotFound'; import ITest from '../protocols/ITest'; import { createTestSchema } from '../schemas/testsSchemas'; import * as testsService from '../services/testsService'; export async function createTest(req: Request, res: Response, next: NextFunction) { try { const testBody: ITest = req.body; const { error: invalidBody } = createTestSchema.validate(testBody); if (invalidBody) { throw new Invalid(invalidBody.message); } await testsService.create(testBody); return res.status(httpStatus.CREATED).send({ message: 'Test created successfully!', }); } catch (error) { if (error instanceof Invalid) return res.status(httpStatus.BAD_REQUEST).send(error.message); if (error instanceof Conflict) return res.status(httpStatus.CONFLICT).send(error.message); if (error instanceof NotFound) return res.status(httpStatus.NOT_FOUND).send(error.message); return next(); } } export async function getTests(req: Request, res: Response, next: NextFunction) { try { const result = await testsService.get(); return res.status(httpStatus.OK).send(result); } catch (error) { if (error instanceof NotFound) return res.status(httpStatus.NOT_FOUND).send(error.message); return next(); } }
import pandas as pd import numpy as np from itertools import product import argparse import random import chemoUtils import sys class ligandSetSimilarity(object): """ Object returns the bootstrap p-value of two given drugs """ def __init__(self, drugs_to_vec, targets_df, proteinA, proteinB, n, r): """ Initialize object with drug => fingerprint dictionary, targets dataframe, protein A, protein B, and the number of sampling iterations (n) """ # Store number of iterations and random seed generator self.n = n # Initialize random number generator random.seed(r) # Store targets dataframe and drugs => fingerprint dictionary self.targets_df = targets_df self.drugs_to_vec = drugs_to_vec # Get set of ligands which bind to proteins A and B self.setA = set(self.targets_df.loc[self.targets_df['uniprot_accession'] == str(proteinA)]['db_id']) self.setB = set(self.targets_df.loc[self.targets_df['uniprot_accession'] == str(proteinB)]['db_id']) # Store length of set self.nA = len(self.setA) self.nB = len(self.setB) def compute_T_sum(self, setA, setB): """ Function computes T_summary of two sets Inputs: Set A, Set B """ # Get all combinations drug_combos = chemoUtils.generate_combos(setA, setB) # Store T_summary total = 0 # For each combination, compute the Tanimoto coefficient; # only store (i.e., add to total) if value > 0.5 for combo in drug_combos: drugA = combo[0] drugB = combo[1] T = chemoUtils.calculate_tanimoto(self.drugs_to_vec, drugA, drugB) if T > 0.5: total += T return total def sample(self): """ Function samples from drugs.csv; returns two random sets of size nA and nB """ # Initialize new ligand set newSetA = set() newSetB = set() # Get list all unique drugs; get length of this list # (use for upper bound of random int generator) drugs = list(self.drugs_to_vec.keys()) num_drugs = len(drugs) # Fill newSetA with random drugs until it is the same size as nA while len(newSetA) < self.nA: intA = random.randint(0,num_drugs-1) newSetA.add(drugs[intA]) # Fill newSetB with random drugs until it is the same size as nB while len(newSetB) < self.nB: intB = random.randint(0,num_drugs-1) newSetB.add(drugs[intB]) # Return new sets return newSetA, newSetB def compute_pval(self): """ Function computes the bootstrap p-value """ # Compute T_summary for the original ligand sets of protein A and B T = self.compute_T_sum(self.setA, self.setB) total = 0 # Sample n times for i in range(self.n): # Get new sets with the same number of binding ligands newSetA, newSetB = self.sample() # Compute T_i, i.e. T_summary for these new sets Ti = self.compute_T_sum(newSetA, newSetB) # Add +1 to numerator of p_bootstrapp if T_i >= T_summary if Ti >= T: total += 1 # Compute p_boostrap p_bootstrap = total / self.n # Return p_bootstrap return p_bootstrap def main(): """ Function is called when the file is called in the terminal """ # Define Parser parser = argparse.ArgumentParser(prog = 'p-value calculator', description = 'Generate a bootstrap p-value for the comparison of two proteins') parser.add_argument('-n', default = 500, type = int, help = 'number of iterations') parser.add_argument('-r', default = 214, type = int, help = 'parameter that sets the state of the pseudo-random number generator in Python') parser.add_argument('drugs_file', type=str) parser.add_argument('targets_file', type=str) parser.add_argument('proteinA', type=str) parser.add_argument('proteinB', type=str) args = parser.parse_args() # Store variables from shell n = args.n r = args.r drugs_file = args.drugs_file targets_file = args.targets_file proteinA = args.proteinA proteinB = args.proteinB # Get drug => fingerprint dictionary and targets dataframe from chemoUtils file drugs_to_vec = chemoUtils.drugs_to_vec(drugs_file) targets_df = chemoUtils.targets_df(targets_file) # Run ligandSetSimilarity ligandSetSim = ligandSetSimilarity(drugs_to_vec, targets_df, proteinA, proteinB, n, r) print(ligandSetSim.compute_pval()) if __name__=="__main__": main()
import PropTypes from 'prop-types' import { useLocation } from 'react-router-dom' // look at the route that we are currently on import Button from './Button' const Header = ({title, onAdd, showAdd}) => { const location = useLocation() return ( <header className= 'header'> <h1>{title}</h1> {location.pathname === '/' && <Button color={showAdd ? 'red' : 'green'} text={showAdd ? 'Close' : 'Add'} onClick={onAdd}/>} </header> ) } Header.defaultProps = { title: 'Task Tracker', } Header.propTypes = { title: PropTypes.string.isRequired, } export default Header //CSS in JS // const headingStyle = { // color: 'red', // backgroundColor: 'black' // }
import { createSlice } from "@reduxjs/toolkit"; /* todoList: [] => Item<Array> Item: { id title isCompleted } */ const todoSlice = createSlice({ name: "todo", initialState: { todoList: [ { id: "1", text: "Learn React Native", isCompleted: false, }, { id: "2", text: "Learn Redux", isCompleted: false, }, { id: "3", text: "Learn Redux Toolkit", isCompleted: false, }, { id: "4", text: "Learn Redux Saga", isCompleted: false, }, { id: "5", text: "Learn React Navigation", isCompleted: false, }, { id: "6", text: "Learn React Native Paper", isCompleted: false, } ], }, reducers: { addTodo: (state, action) => { state.todoList.push(action.payload); }, removeTodo: (state, action) => { state.todoList = state.todoList.filter((todo) => todo.id !== action.payload); }, toggleComplete: (state, action) => { state.todoList = state.todoList.map((todo) => { if (todo.id === action.payload) { return { ...todo, completed: !todo.completed, }; } return todo; }); }, }, }); export const { addTodo, removeTodo, toggleComplete } = todoSlice.actions; export default todoSlice.reducer;
<?php namespace App\Livewire; use App\Models\serves; use Livewire\Component; use Livewire\Attributes\On; use Livewire\Attributes\Url; use Livewire\WithPagination; use Livewire\Attributes\Rule; use Livewire\WithFileUploads; use Livewire\Attributes\Layout; use Livewire\Attributes\Computed; use Livewire\Attributes\Validate; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; class Hndelserveies extends Component { use WithFileUploads; use WithPagination; #[Layout('layouts.app')] public $sumnail_status= false; public $getlocal; public $imgsumnail_temp; public $sortdir = 'desc'; public $getimgpath ; public $serveies_id; #[Validate('nullable|url')] public $youtube_url; #[Validate([ 'images' => 'sometimes:image|max:1024', 'images.*' => [ 'sometimes:image|max:1024', ], ])] public $images = []; #[Rule('required|image|max:1024')] public $imgsumnail; #[Validate([ 'name' => 'required', 'name.*' => [ 'required', 'min:5', 'max:65' ], ])] public $name = []; #[Validate([ 'shortdes' => 'required', 'shortdes.*' => [ 'required', 'min:20', 'max:255' ], ])] public $shortdes = []; #[Validate([ 'des' => 'required', 'des.*' => [ 'required', 'min:20', ], ])] public $des = []; public $paginate = 5; #[Url(except: ' ',keep: true,history: true)] public $search = ''; public function updatingSearch() { $this->resetPage(); } public function changstatus(){ $this->sumnail_status = true; } public function render() { return view('livewire.hndelserveies'); } #[Computed] public function getserveies(){ return serves::where('name', 'like', '%'.$this->search.'%') -> orderBy('id', $this->sortdir)->paginate($this->paginate); } public function addserveies() { $validated = $this->validate(); $this->getlocal = app()->getLocale() == "en" ? $this->name['en']: $this->name['ar']; if(!empty($this->images)) { foreach ($this->images as $key => $photos) { $this->images[$key] = $photos->store('images/'.$this->getlocal,'public'); } } $this->images = json_encode($this->images); serves::create([ 'name' => [ 'en' => $this->name['en'], 'ar' => $this->name['ar'], ], 'shortdes' => [ 'en' => $this->shortdes['en'], 'ar' => $this->shortdes['ar'] ], 'des' => [ 'en' => $this->des['en'], 'ar' => $this->des['ar'] ], 'youtube_url' => $this->youtube_url, 'imgsumnail'=> $this->imgsumnail->store('imgsumnail/'.$this->getlocal,'public'), 'images'=> $this->images, ]); $this->resetvalue(); $this->dispatch('close-modal','add-serveies'); $this->dispatch('serv-aadded'); // Emit an event for closing the modal } public function removeimg($key ,$path) { Storage::deleteDirectory('public/'.$path); $getpath = serves::where('id', $this->serveies_id)->value('images'); // Decode the JSON data (assuming it's stored as JSON) $imagesArray = json_decode($getpath, true); // Check if the desired path exists in the array if (in_array($path, $imagesArray)) { // Remove the path from the array $updatedArray = array_diff($imagesArray, [$path]); // Update the database record with the modified array serves::where('id', $this->serveies_id)->update(['images' => json_encode($updatedArray)]); unset($this->images[$key]); } // $this->images = json_encode($this->images); //array_splice($this->screenshots,$key); //unset($this->images[$key]) } #[On('editserv')] public function editserv($proj_id) { $this->serveies_id = $proj_id; $getproj = serves::find($proj_id); $this->name['ar'] =$getproj->getTranslation('name','ar'); $this->name['en'] = $getproj->getTranslation('name', 'en'); $this->des['en'] = $getproj->getTranslation('des', 'en'); $this->des['ar'] = $getproj->getTranslation('des', 'ar') ; $this->shortdes['en'] = $getproj->getTranslation('shortdes', 'en'); $this->shortdes['ar'] = $getproj->getTranslation('shortdes', 'ar') ; $this->youtube_url = $getproj->youtube_url; $this->imgsumnail_temp = $getproj->imgsumnail; $this->images = json_decode($getproj->images,true); $this->dispatch('edit-des'); } public function updateserv () { $this->validate([ 'imgsumnail'=> 'sometimes:image|max:1024', ]); $getres= serves::findOrFail($this->serveies_id); // $this->getlocal = app()->getLocale() == "en" ? $this->name['en']: $this->name['ar']; if( !empty($this->imgsumnail) && $this->imgsumnail !== $getres->imgsumnail){ Storage::deleteDirectory('public/imgsumnail/'.$getres->name); $this->getimgpath = $this->imgsumnail->store('imgsumnail/'.$getres->name,'public'); }else{ $this->getimgpath = $this->imgsumnail_temp; } if( $this->images !== json_decode($getres->images,true)) { Storage::deleteDirectory('public/images/'.$getres->name); foreach ($this->images as $key => $photos) { $this->images[$key] = $photos->store('images/'.$getres->name,'public'); } } $this->images = json_encode($this->images); $getres->update([ 'name' => [ 'en' => $this->name['en'], 'ar' => $this->name['ar'], ], 'shortdes' => [ 'en' => $this->shortdes['en'], 'ar' => $this->shortdes['ar'] ], 'des' => [ 'en' => $this->des['en'], 'ar' => $this->des['ar'] ], 'youtube_url' => $this->youtube_url, 'imgsumnail'=> $this->getimgpath == null ? $this->imgsumnail_temp: $this->getimgpath, 'images'=> $this->images, ]); $this->dispatch('close-modal','update-serveies'); $this->dispatch('serv-updated'); $this->resetvalue(); $this->sumnail_status = false; } #[On('confirmdel')] public function confirmdel($data) { $serv = serves::find($data['servid']); Storage::deleteDirectory('public/images/'.$data['proname']); Storage::deleteDirectory('public/imgsumnail/'.$data['proname']); $serv->delete(); $this->dispatch('servdeleted'); } public function deleteconfirm($serv_id, $servname) { $this->dispatch('deleteserv',servid : $serv_id ,servname: $servname); } #[On('resetvalue')] public function resetvalue() { $this->name = []; $this->shortdes = []; $this->des = []; $this->imgsumnail = null; $this->images = []; $this->youtube_url = ''; $this->resetValidation(); $this->resetErrorBag(); } }
import AssignmentList from "./AssignmentList.js"; import AssignmentCreate from "./AssignmentCreate.js"; export default { template: ` <section class="space-y-10"> <assignment-create @add="add"></assignment-create> <assignment-list :assignments="filters.inProgress" title="In Progress"></assignment-list> <assignment-list :assignments="filters.completed" title="Completed"></assignment-list> </section> `, components:{ AssignmentList, AssignmentCreate }, data() { return { assignments: [ { name: "Finish Project", complete: false, id:1, tag:'Math'}, { name: "Another task", complete: false, id:2, tag: 'Science'}, { name: "Something else", complete: false, id:3, tag: 'Reading'}, ], } }, computed: { filters(){ return{ inProgress: this.assignments.filter(assignment => ! assignment.complete), completed: this.assignments.filter(assignment => assignment.complete) } } }, methods: { add(name){ this.assignments.push({ name: name, completed: false, id: this.assignments + 1, }); } } }
import Combine import XCTest @testable import SubVTData final class ValidatorListServiceTests: XCTestCase { private var cancellables: Set<AnyCancellable>! override func setUp() { cancellables = [] } private func validatorListSubscriptionTest(active: Bool) { var error: Error? = nil let subscribeExpectation = self.expectation(description: "Subscribed.") let updateExpectation = self.expectation(description: "Validator list updates received.") let unsubscribeExpectation = self.expectation(description: "Unsubscribed.") let finishExpectation = self.expectation(description: "Finished.") let service = ValidatorListService(active: active) var updateCount = 0 service .subscribe() .sink { (completion) in switch completion { case .finished: print("Finished.") finishExpectation.fulfill() case .failure(let rpcError): print("Finished with error: \(rpcError)") error = rpcError finishExpectation.fulfill() } } receiveValue: { (event) in switch event { case .subscribed(_): subscribeExpectation.fulfill() case .update(let listUpdate): updateCount += 1 if updateCount == 1 { XCTAssertTrue(listUpdate.insert.count > 0) XCTAssertEqual(0, listUpdate.update.count) XCTAssertEqual(0, listUpdate.removeIds.count) print("Initial list received.") } else { print("List diff received.") if updateCount == 3 { updateExpectation.fulfill() service.unsubscribe() } } case .unsubscribed: unsubscribeExpectation.fulfill() } }.store(in: &cancellables) waitForExpectations(timeout: 100) XCTAssertNil(error) } func testActiveValidatorListSubscription() { validatorListSubscriptionTest(active: true) } func testInactiveValidatorListSubscription() { validatorListSubscriptionTest(active: false) } static var allTests = [ ("testActiveValidatorListSubscription", testActiveValidatorListSubscription), ] }
import CONFIG from '../../global/config'; const restoCard = (resto) => ` <div tabindex="0" class="card"> <a href="#/resto/${resto.id}" class="card-a-tag"> <div class="img-container"> <img tabindex="0" class="card-image" crossorigin="anonymous" alt="${resto.name}" src="${CONFIG.BASE_IMAGE_URL + resto.pictureId}"/> <div tabindex="0" class="card-content"> <h2 class="card-content-title">${resto.name} - ${resto.rating}</h2> <h2 class="card-content-title">${resto.city}</h2> </div> </a> </div> `; const restoDetail = (resto) => ` <div class="detail"> <div class="img-container"> <img class="detail-img" alt="${resto.name}" src="${ CONFIG.BASE_IMAGE_URL + resto.pictureId }"/> </div> <ul class="detail-info"> <li> <i title="restaurant" class="fas fa-utensils"></i> <p class="detail-name-address-rating">${resto.name}</p> </li> <li> <i title="address" <i class="fas fa-map-marker"></i> <p class="detail-name-address-rating">${resto.address}, ${resto.city}</p> </li> <li> <i title="ratings" class="fas fa-star"></i> <p class="detail-name-address-rating">${resto.rating}</p> </li> <li><p class="detail-desc class="fas fa-newspaper">${resto.description}</p></li> </ul> <h3>Menu</h3> <div class="detail-menu"> <div class="detail-food"> <h4>Makanan</h4> <ul> ${resto.menus.foods .map( (food, i) => ` <li><p>${i + 1}) ${food.name}</p></li> `, ) .join('')} <ul> </div> <div class="detail-drink"> <h4>Minuman</h4> <ul> ${resto.menus.drinks .map( (drink, i) => ` <li><p>${i + 1}) ${drink.name}</p></li> `, ) .join('')} <ul> </div> </div> <h3 class="title-review">Customer Reviews</h3> <div class="detail-review"> ${resto.customerReviews .map( (review) => ` <div class="testimonial-box-container"> <div class="testimonial-box"> <div class="box-top"> <div> <div class="name-user"> <strong>${review.name}</strong> </div> </div> </div> <div class="client-comment" tabindex="0"> <p>${review.date}</p> </div> <div class="client-comment" tabindex="0"> <p>${review.review}</p> </div> </div> </div> `, ) .join('')} </div> </div> `; const createLikeButtonTemplate = () => ` <button aria-label="like this resto" id="likeButton" class="like"> <i class="far fa-heart" aria-hidden="true"></i> </button> `; const createLikedButtonTemplate = () => ` <button aria-label="unlike this resto" id="likeButton" class="like"> <i class="fas fa-heart" aria-hidden="true"></i> </button> `; export default { restoDetail, restoCard, createLikeButtonTemplate, createLikedButtonTemplate, };
/* A component that is using the `useSelector` hook to get the coins from the store. */ import React, {FunctionComponent} from 'react'; import {StyleSheet, View} from 'react-native'; import {List, Text} from 'react-native-paper'; import {useSelector} from 'react-redux'; import {AppState} from '../../core/store'; import {LIGTH_THEME} from '../../theme/colors'; const CardOfCoins: FunctionComponent = () => { const coins = useSelector((state: AppState) => state.coins?.coins); return ( <View style={BaseCardStyles.cardContainer}> <List.Section> <List.Subheader>Monedas soportadas</List.Subheader> {coins.map((coin: any) => ( <List.Item key={coin.key} title={coin.name} right={() => ( <Text style={BaseCardStyles.price}>${coin.price.usd}</Text> )} /> ))} </List.Section> </View> ); }; /* A constant that is creating a style sheet. */ const BaseCardStyles = StyleSheet.create({ cardContainer: { borderRadius: 14, marginTop: 50, overflow: 'hidden', backgroundColor: 'white', }, price: { justifyContent: 'center', color: LIGTH_THEME.titleInput, fontSize: 14, fontWeight: '600', }, }); export default CardOfCoins;
Tool: ncbi-blast+ Perform: Local database construction and retrieval >Installation $ sudo apt-get install ncbi-blast+ >Usage (database construction) # DNA/RNA Sequences $ makeblastdb -in multi.fasta -out mydatabase -parse_seqids -dbtype nucl # Protein Sequences $ makeblastdb -in multi.fasta -out mydatabase -parse_seqids -dbtype prot >Usage (database retrieval/searching) # Blastn $ blastn -db mydatabase -query query.fasta -outfmt 6 -out result.txt $ blastn -db mydatabase -query query.fasta -outfmt "6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send score qcovs evalue bitscore" -out result.txt $ blastn -db mydatabase -query query.fasta -outfmt "7 std length qcovs qcovhsp" -out result.txt # Different commands for different output format Other useful parameters: -task blastn-short [for short query sequences e.g. kmers] -num_threads 2 [2 cores] -ungapped [hits with ungapped alignment] -max_target_seqs 500 [maximum number of hits] -perc_identity 100 [hits with 100% identity] -qcov_hsp_perc 100 [hits with 100% query coverage] # Blastp $ blastp -db mydatabase -query query.fasta -outfmt "7 std length qcovs qcovhsp" -out result.txt Other useful parameters: -task blastp-short [for short query sequences e.g. kmers] -num_threads 2 [2 cores] -ungapped [hits with ungapped alignment] -max_target_seqs 500 [maximum number of hits] -qcov_hsp_perc 100 [hits with 100% query coverage] # Psi-Blast
package ch14.bookshop.shopping; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class CustomerDBBean { private static CustomerDBBean instance = new CustomerDBBean(); public static CustomerDBBean getInstance() { return instance; } private CustomerDBBean() {} private Connection getConnection() throws Exception{ Context initCtx = new InitialContext(); Context envCtx = (Context)initCtx.lookup("java:comp/env"); DataSource ds = (DataSource)envCtx.lookup("jdbc/basicjsp"); return ds.getConnection(); } /* 회원가입 */ public void insertMember(CustomerDataBean member) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); pstmt = conn.prepareStatement("insert into member values(?, ?, ?, ?, ?, ?)"); pstmt.setString(1, member.getId()); pstmt.setString(2, member.getPasswd()); pstmt.setString(3, member.getName()); pstmt.setTimestamp(4, member.getReg_date()); pstmt.setString(5, member.getTel()); pstmt.setString(6, member.getAddress()); pstmt.executeUpdate(); }catch(Exception ex){ ex.printStackTrace(); }finally { if(pstmt!=null) try {pstmt.close();}catch(SQLException sqle){} if(conn!=null) try {conn.close();}catch(SQLException sqle){} } } /* 사용자 인증처리 */ public int userCheck(String id, String passwd) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String dbpasswd = ""; int x = -1; try { conn = getConnection(); pstmt = conn.prepareStatement("select passwd from member where id = ?"); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(rs.next()) { dbpasswd = rs.getString("passwd"); if(dbpasswd.equals(passwd)) x = 1; else x = 0; }else x = -1; }catch(Exception ex) { ex.printStackTrace(); }finally { if(rs!=null) try {rs.close();}catch(SQLException sqle) {} if(pstmt!=null) try {pstmt.close();}catch(SQLException sqle) {} if(conn!=null) try {conn.close();}catch(SQLException sqle) {} } return x; } /* 중복아이디 체크 */ public int confirmId(String id) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; int x = -1; try { conn = getConnection(); pstmt = conn.prepareStatement("select id from member where id = ?"); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(rs.next()) x = 1; else x = -1; }catch(Exception ex) { ex.printStackTrace(); }finally { if(rs!=null) try {rs.close();}catch(SQLException sqle) {} if(pstmt!=null) try {pstmt.close();}catch(SQLException sqle) {} if(conn!=null) try {conn.close();}catch(SQLException sqle) {} } return x; } /* 회원정보를 수정하기 위해 기존의 정보를 표시 */ public CustomerDataBean getMember(String id) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; CustomerDataBean member = null; try { conn = getConnection(); pstmt = conn.prepareStatement("select * from member where id = ?"); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(rs.next()) { member = new CustomerDataBean(); member.setId(rs.getString("id")); member.setPasswd(rs.getString("passwd")); member.setName(rs.getString("name")); member.setReg_date(rs.getTimestamp("reg_date")); member.setTel(rs.getString("tel")); member.setAddress(rs.getString("address")); } }catch(Exception ex) { ex.printStackTrace(); }finally { if(rs!=null) try {rs.close();}catch(SQLException sqle) {} if(pstmt!=null) try {pstmt.close();}catch(SQLException sqle) {} if(conn!=null) try {conn.close();}catch(SQLException sqle) {} } return member; } /* 회원의 정보 수정 */ public void updateMember(CustomerDataBean member) throws Exception { Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); pstmt = conn.prepareStatement("update member set passwd = ?, name = ?, tel = ?, address = ?, where id = ?"); pstmt.setString(1, member.getPasswd()); pstmt.setString(2, member.getName()); pstmt.setString(3, member.getTel()); pstmt.setString(4, member.getAddress()); pstmt.setString(5, member.getId()); pstmt.executeUpdate(); }catch(Exception ex) { ex.printStackTrace(); }finally { if(pstmt!=null) try {pstmt.close();}catch(SQLException sqle) {} if(conn!=null) try {conn.close();}catch(SQLException sqle) {} } } /* 회원 탈퇴 */ public int deleteMember(String id, String passwd) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String dbpasswd = null; int x = -1; try { conn = getConnection(); pstmt = conn.prepareStatement("select passwd from member where id = ?"); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(rs.next()) { dbpasswd = rs.getString("passwd"); if(dbpasswd.equals(passwd)) { pstmt = conn.prepareStatement("delete from member where id = ?"); pstmt.setString(1, id); pstmt.executeUpdate(); x = 1; } else x = 0; } }catch(Exception ex) { ex.printStackTrace(); }finally { if(rs!=null) try {rs.close();}catch(SQLException sqle) {} if(pstmt!=null) try {pstmt.close();}catch(SQLException sqle) {} if(conn!=null) try {conn.close();}catch(SQLException sqle) {} } return x; } }
import React, { Component } from 'react' import { Table } from 'react-bootstrap' import TicketService from '../Service/TicketService' import TicketRecord from './TicketRecord'; export default class ListTickets extends Component { constructor(props) { super(props); this.state = { tickets: [], errors: '' } } componentDidMount() { TicketService.getTickets() .then((res) => { this.setState({ tickets: res.data }) }).catch((err) => { console.log(err); this.setState({ errors: "Some Error Occurred" }) }) } DataTable() { return this.state.tickets.map((res, i) => { return <TicketRecord obj={res} key={i} /> }) } render() { if (this.state.tickets != null) { return ( <div> <Table hover bordered striped> <thead> <tr style={{ textAlign: 'center' }}> <th>Ticket ID</th> <th>Employee ID</th> <th>Problem Case</th> <th>Resolved</th> </tr> </thead> <tbody> {this.DataTable()} </tbody> </Table> </div> ) } else { return <h1>{this.state.errors}</h1> } } }
//jshint esversion:6 require('dotenv').config(); const express =require("express"); const bodyPArser=require("body-parser"); const ejs =require("ejs"); const mongoose=require("mongoose"); // const md5=require("md5"); const bcrypt=require("bcrypt"); const saltRounds=8; const app=express(); app.use(bodyPArser.urlencoded({extended:true})); app.use(express.static("public")); app.set('view engine','ejs'); const DB='mongodb+srv://itsadityasharma7124:[email protected]/Secrets?retryWrites=true&w=majority' mongoose.connect(DB); const userSchema=new mongoose.Schema({ email:String, password:String }); const secret=process.env.SECRET; const userData=mongoose.model("userdata",userSchema); const user1=new userData({ email:"[email protected]", password:"mainbhadwahu" }); // user1.save(); app.get("/",function(req,res){ res.render("home"); }); app.get("/login",function(req,res){ res.render("login"); }); app.post("/login",function(req,res){ const userName=req.body.username; const pass=req.body.password; // const pass=md5(req.body.password); //hash the password userData.findOne({email:userName}) .then((foundUser)=>{ if(foundUser){ console.log(foundUser); bcrypt.compare(pass, foundUser.password, function(err, result) { if(result){ console.log("user found"); res.render("secrets"); } else{ console.log("password incorrect"); } }); } else{ console.log("user not registered with us"); } }) .catch((err) => { //When there are errors We handle them here console.log(err); res.status(400).send("Bad Request"); }); }); app.get("/register",function(req,res){ res.render("register"); }); app.post("/register",function(req,res){ const userName=req.body.username; bcrypt.hash(req.body.password, saltRounds, function(err, hash) { const newUser=new userData({ email:userName, password:hash }); newUser.save().then(res.render("secrets")); }); // const pass=md5(req.body.password); //hash the password // userData.find({email:userName}) // .then((foundUser)=>{ // if(foundUser){ // console.log(foundUser); // } // else{ // } // }) }); app.get("/secrets",function(req,res){ res.render("secrets"); }); app.listen("3000",function(req,res){ console.log("server started at 3000"); });
import { useSelector, useDispatch } from "react-redux"; import * as actions from "../../redux/counter/counter-actions"; import { getValue, getStep } from "../../redux/counter/counter-selector"; export default function Counter() { const value = useSelector(getValue); const step = useSelector(getStep); const dispatch = useDispatch(); return ( <div> <p>{value}</p> <button type="button" onClick={() => dispatch(actions.increment(step))}> Increment on {step} </button> <button type="button" onClick={() => dispatch(actions.decrement(step))}> Decrement on {step} </button> </div> ); } // const mapStateToProps = (state) => ({ // value: state.counter.value, // step: state.counter.step, // }); // const mapDispatchToProps = (dispatch) => ({ // onIncrement: (value) => dispatch(actions.increment(value)), // onDecrement: (value) => dispatch(actions.decrement(value)), // }); // export default connect(mapStateToProps, mapDispatchToProps)(Counter);
package CourseWork.Select; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Random; public class ArraySel { private long[] array; // Ссылка на массив a private int length; // Количество элементов данных public ArraySel(int max) // Конструктор { array = new long[max]; // Создание массива length = 0; // Пока нет ни одного элемента } public void randomInsert(int value, ArraySel arr){ // Метод, позволяющий заполнить массив случайными значениями Random random = new Random(); length=value; for (int i=0;i<value;i++){ array[i]=random.nextInt(value); } } public void insert(long value) // Вставка элемента в массив { array[length] = value; // Собственно вставка length++; // Увеличение размера } public void display() // Вывод содержимого массива { for(int j=0; j<length; j++) // Для каждого элемента System.out.print(array[j] + " "); // Вывод System.out.println(""); } public void selectionSort() { int out, in, min; for(out=0; out<length-1; out++) // Внешний цикл { min = out; // Минимум for(in=out+1; in<length; in++) // Внутренний цикл if(array[in] < array[min] ) // Если значение min больше, min = in; // значит, найден новый минимум swap(out, min); // swap them } } private void swap(int one, int two) { long temp = array[one]; array[one] = array[two]; array[two] = temp; } public void WriteToTxtUnsorted() { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\ekb-l\\IdeaProjects\\Laboratory Work\\src\\CourseWork\\FinalSorting\\Result",false)))) { writer.write("Массив до сортировки:"); writer.write("\n"); for (int i = 0; i < length; i++) { writer.write(String.valueOf(array[i])); writer.write(" "); } } catch (IOException e) { System.out.println(e.getMessage()); } } public void WriteToTxtSorted(){ try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\ekb-l\\IdeaProjects\\Laboratory Work\\src\\CourseWork\\FinalSorting\\Result",true)))){ writer.write("\nМассив после сортировки:"); writer.write("\n"); for (int i =0;i<length;i++){ writer.write(String.valueOf(array[i])); writer.write(" "); } } catch (IOException e){ System.out.println(e.getMessage()); } } }
package com.graalvm; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; public class CreateTable { public static void main(String[] args) { try { Class.forName("org.sqlite.JDBC"); // Load the SQLite JDBC driver // Get the database file as a resource ClassLoader classLoader = CreateTable.class.getClassLoader(); // Replace YourClass with your class name URL resource = classLoader.getResource("/config.db"); String url = "jdbc:sqlite:config.db"; try (Connection connection = DriverManager.getConnection(url); Statement statement = connection.createStatement()) { String tableSQL = "DROP TABLE IF EXISTS Config;"; statement.execute(tableSQL); // SQL statement to create the table String createTableSQL = "CREATE TABLE IF NOT EXISTS Config (" + " id INTEGER PRIMARY KEY DEFAULT 1," + " username VARCHAR(250) default 'Testing'," + " email VARCHAR(250) default '[email protected]'" + ");"; // Execute the SQL statement statement.execute(createTableSQL); System.out.println("Table 'Config' created successfully."); String insertRecordSQL = "INSERT INTO Config DEFAULT VALUES;"; // Create a PreparedStatement PreparedStatement preparedStatement = connection.prepareStatement(insertRecordSQL); int rowsAffected = preparedStatement.executeUpdate(); preparedStatement.close(); System.out.println("Record inserted successfully. Rows affected: " + rowsAffected); } catch (Exception e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>All Movies</title> <link rel="stylesheet" type="text/css" href="common.css" /> </head> <body> <div class='topnav'> <a href='/'><span>Homepage</span></a> <a href='PageMission.html'><span>Our Mission</span></a> <a href='PageST21.html'><span>Sub Task 2.1</span></a> <a href='PageST22.html'><span>Sub Task 2.2</span></a> <a href='PageST31.html'><span>Sub Task 3.1</span></a> <a href='PageST32.html'><span>Sub Task 3.2</span></a> </div> <div class = "ContentLevel2"> <span Style="display: inline-block"> <form action="/PageST21.html" method="post"> <label for="state_drop">Pick a State: </label> <select name="state_drop" id="state_drop"> <!-- The options on the webpage, it also saves what is selected when a user submits data --> <option>Select a State</option> <option th:selected="${selected == 'VIC'}" value="VIC">Victoria</option> <option th:selected="${selected == 'ACT'}" value="ACT">Australian Capital Territory</option> <option type= "submit" th:selected="${selected == 'QLD'}" value="QLD">Queensland</option> <option th:selected="${selected == 'NT'}" value="NT">Northern Territory</option> <option th:selected="${selected == 'WA'}" value="WA">Western Australia</option> <option th:selected="${selected == 'TAS'}" value="TAS">Tasmania</option> <option th:selected="${selected == 'SA'}" value="SA">South Australia</option> </select> <label for="lga_drop">Pick a LGA: </label> <select name="lga_drop" id="lga_drop"> <option th:if="${selected == 'null'}">Select a LGA</option> <option th:unless='${selected == 'null'}' th:each='lga : ${lga}' th:text='${lga.name}'' th:value='${lga.code}' th:selected='${lga.name == name}'></option> </select> <button type="submit" class="btn btn-primary">Submit</button> </form> </span> </div> <!-- <div class='content'> <form action='/moviestype.html' method='post'> <div class='form-group'> <label for='movietype_drop'>Select the type Movie Type (Dropdown):</label> <select id='movietype_drop' name='movietype_drop'> <option th:each="type : ${types}" th:text="${type}"></option> </select> </div> <div class='form-group'> <label for='movietype_textbox'>Select the type Movie Type (Textbox)</label> <input class='form-control' id='movietype_textbox' name='movietype_textbox'> </div> <button type='submit' class='btn btn-primary'>Submit</button> </form> <div th:if="${#lists.size(movies_drop) > 0}"> <h2 th:text="${title_drop}"></h2> <ul> <li th:each="movie : ${movies_drop}" th:text="${movie}"></li> </ul> </div> <div th:if="${#lists.size(movies_text) > 0}"> <h2 th:text="${title_text}"></h2> <ul> <li th:each="movie : ${movies_text}" th:text="${movie}"></li> </ul> </div> </div> --> </body>
import { PullRequestSummary } from "@/models/pulls/PullRequestSummary"; /** * Generate a mock PullRequestSummary * @param pull_number * @param repository * @param title * @param user * @param status * @param milestone * @param comments * @param review_comments * @param commits * @param firstReviewedAt * @param additions * @param deletions * @param change_files * @param draft * @param created_at * @param updated_at * @param closed_at * @param merged_at * @param firstReviewRequestedAt * @param timeToFirstReview * @param timeToClose */ export const generateMockPullRequestSummary = ({ pull_number = 1, repository = "repository", title = "title", user = "user", status = "open", milestone = "milestone", comments = 10, review_comments = 5, commits = 2, firstReviewedAt = "2022-01-01T00 =00 =00Z", additions = 150, deletions = 75, change_files = 4, draft = "false", created_at = "2022-01-01T00 =00 =00Z", updated_at = "2022-01-01T00 =00 =00Z", closed_at = "2022-01-01T00 =00 =00Z", merged_at = "2022-01-01T00 =00 =00Z", firstReviewRequestedAt = "2022-01-01T00 =00 =00Z", timeToFirstReview = 2000, timeToClose = 4000, }): PullRequestSummary => { return PullRequestSummary.from({ pull_number: pull_number.toString(), repository: repository, title: title, user: user, status: status, milestone: milestone, comments: comments.toString(), review_comments: review_comments.toString(), commits: commits.toString(), additions: additions.toString(), deletions: deletions.toString(), change_files: change_files.toString(), draft: draft, created_at: created_at, updated_at: updated_at, closed_at: closed_at, merged_at: merged_at, firstReviewedAt: firstReviewedAt, timeToFirstReview: timeToFirstReview.toString(), timeToClose: timeToClose.toString(), }); };
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AuthModule } from './Modules/auth/auth.module'; import { SharedModule } from './Modules/shared/shared.module'; import { PublicModule } from './Modules/public/public.module'; import { PageNotFoundComponent } from './Modules/shared/page-not-found/page-not-found.component'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http' import { HeaderInterceptor } from './Interceptor/header.interceptor'; import { RoleGuard } from './Guards/role.guard'; import { StudentModule } from './Modules/student/student.module'; import { AuthGuard } from './Guards/auth.guard'; import { ToastrModule } from 'ngx-toastr'; import { StudentService } from './Services/api-services/students/student.service'; import { LoginService } from './Services/api-services/user-auth/login.service'; import { SignupService } from './Services/api-services/user-auth/signup.service'; import { InstructorModule } from './Modules/instructor/instructor.module'; import { InstructorService } from './Services/api-services/instructor/instructor.service'; import { TransferdataService } from './Services/other/transferdata.service'; import { ErrorCatchingInterceptor } from './Interceptor/error-catching.interceptor'; import { AdminModule } from './Modules/admin/admin.module'; import { AdminService } from './Services/api-services/admin/admin.service'; import { CourseService } from './Services/api-services/course/course.service'; @NgModule({ declarations: [ AppComponent, PageNotFoundComponent, ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule, SharedModule, AuthModule, StudentModule, InstructorModule, AdminModule, PublicModule, HttpClientModule, ToastrModule.forRoot({ positionClass: "toast-bottom-right", preventDuplicates: true, timeOut: 2500, easing: "ease-in", easeTime: 1000 }), ], providers: [ TransferdataService, InstructorService, StudentService, CourseService, LoginService, SignupService, AdminService, RoleGuard, AuthGuard, { provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorCatchingInterceptor, multi: true} ], bootstrap: [AppComponent] }) export class AppModule { }
/* import NextAuth from "next-auth"; import { authConfig } from "./auth.config"; import Credentials from "next-auth/providers/credentials"; import {z} from "zod"; import { PrismaClient } from "@prisma/client"; import { User } from "@prisma/client"; */ /* const prisma = new PrismaClient(); async function getUser(username: string): Promise<User| null> { const user = await prisma.user.findUnique({ where: { username: username } }) return user; } export const {auth, signIn, signOut} = NextAuth({ ...authConfig, providers: [Credentials({ async authorize(credentials): Promise<any> { const parsedCredentials = z.object({email: z.string().email(), password: z.string().min(6)}) .safeParse(credentials); if (parsedCredentials.success) { const {email, password} = parsedCredentials.data; const user = await getUser(email); if (!user) return null; const match = await bcrypt.compare(password, user.password); if (match) { console.log(email) return { id: user.id, email: user.username }; } } console.log("invalid credentials"); return null; }, })] }); */ /* const prisma = new PrismaClient(); async function getUser(username: string): Promise<User| null> { const user = await prisma.user.findUnique({ where: { username: username } }) return user; } export const {handlers, auth, signIn, signOut } = NextAuth({ providers: [Credentials({ credentials: { username: {label: "Username"}, password: {label: "Password", type: "password"} }, async authorize(credentials) : Promise<any> { const parsedCredentials = z.object({email: z.string().email(), password: z.string().min(6)}) .safeParse(credentials); if (parsedCredentials.success) { const {email, password} = parsedCredentials.data; const user = await getUser(email); if (!user) return null; const bcrypt = require("bcrypt"); const match = await bcrypt.compare(password, user.password); if (match) { return { id: user.id, email: user.username }; } } console.log("invalid credentials"); return null; } })], callbacks: { authorized({request, auth}) { const {pathname} = request.nextUrl; if (pathname === "/view") return !!auth; return true; } } }) */ import NextAuth from "next-auth" import Google from "next-auth/providers/google" import type { NextAuthOptions } from "next-auth" import prisma from "./lib/prisma"; export const config = { secret: process.env.AUTH_SECRET, session: { strategy: "jwt", }, providers: [ Google({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! }), ], callbacks: { async signIn({account, profile}) { if (!profile?.email) { throw new Error("No email"); } await prisma.user.upsert({ where: { username: profile.email }, create: { username: profile.email, }, update: { username: profile.email } }) return true; }, async session({session, token, user}) { //@ts-expect-error session.user.id = token.id; //return session; return { ...session, user: { ...session.user, id: token.id } } }, async jwt({token, user, account, profile}) { if (profile && profile.email) { const user = await prisma.user.findUnique({ where: { username: profile.email } }) if (!user) { throw Error("No user found!") } token.id = user.id } return token; } }, } satisfies NextAuthOptions export default NextAuth(config)
//[204]计数质数 //给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。 // // // // 示例 1: // // //输入:n = 10 //输出:4 //解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 // // // 示例 2: // // //输入:n = 0 //输出:0 // // // 示例 3: // // //输入:n = 1 //输出:0 // // // // // 提示: // // // 0 <= n <= 5 * 10⁶ // // // Related Topics 数组 数学 枚举 数论 👍 986 👎 0 //leetcode submit region begin(Prohibit modification and deletion) package main func countPrimes(n int) int { flags := make([]bool, n, n) count := 0 for i := 2; i < n; i++ { if !flags[i] { count++ if i*i < n { //i是质数,那边i的整倍数一定是合数 for j := i * i; j < n; j += i { flags[j] = true } } } } return count } func main() { println(countPrimes(10)) } //leetcode submit region end(Prohibit modification and deletion)
import java.util.*; public class MethodPractice2 { private Scanner keyboard = new Scanner(System.in); // Implement methods below this line public void greeting(String firstName, int num){ for(int i = 0; i < num; i++){ System.out.println(firstName + ", have a nice day."); } } public void range(int begin, int end){ for(int i = begin; i <= end; i++){ System.out.println(i); } } public boolean compare(String str){ String firstLetter = str.substring(0,1); String lastLetter = str.substring(str.length()-1,str.length()); if(firstLetter.equalsIgnoreCase(lastLetter)){ return true; } else { return false; } } public String reverse(String str){ String reversed = ""; for(int i = str.length(); i > 0; i--){ reversed += str.substring(i-1,i); } return reversed; } public int numOccurrences(String word, String letter){ int count = 0; for(int i = 0; i < word.length(); i++){ if(word.substring(i,i+1).equalsIgnoreCase(letter)){ count++; } } return count; } public static void main(String[] args) { MethodPractice2 app = new MethodPractice2(); System.out.println("******************"); System.out.println(" Test greeting"); System.out.println("******************"); app.greeting("Kendall", 6); System.out.println("\n\n******************"); System.out.println(" Test range"); System.out.println("******************"); app.range(10, 15); System.out.println("\n\n******************"); System.out.println(" Test compare"); System.out.println("******************"); System.out.println(app.compare("demand")); System.out.println(app.compare("football")); System.out.println(app.compare("bulb")); System.out.println("\n\n******************"); System.out.println(" Test reverse"); System.out.println("******************"); System.out.println(app.reverse("ball")); System.out.println(app.reverse("courage")); System.out.println(app.reverse("hamburger")); System.out.println("\n\n******************"); System.out.println(" Test numOccurrences"); System.out.println("******************"); System.out.println(app.numOccurrences("MISSISSIPPI", "I")); System.out.println(app.numOccurrences("AUTOMOBILE", "O")); System.out.println(app.numOccurrences("TEXAS", "R")); System.out.println(); } }
import datetime from dataclasses import dataclass from neomodel import db from clinical_mdr_api.domain_repositories._utils import helpers from clinical_mdr_api.domain_repositories.generic_repository import ( manage_previous_connected_study_selection_relationships, ) from clinical_mdr_api.domain_repositories.models._utils import convert_to_datetime from clinical_mdr_api.domain_repositories.models.controlled_terminology import ( CTTermRoot, ) from clinical_mdr_api.domain_repositories.models.study import StudyRoot, StudyValue from clinical_mdr_api.domain_repositories.models.study_audit_trail import ( Create, Delete, Edit, StudyAction, ) from clinical_mdr_api.domain_repositories.models.study_selections import StudyObjective from clinical_mdr_api.domain_repositories.models.syntax import ( ObjectiveRoot, ObjectiveTemplateRoot, ) from clinical_mdr_api.domains.study_selections.study_selection_objective import ( StudySelectionObjectivesAR, StudySelectionObjectiveVO, ) from clinical_mdr_api.domains.versioned_object_aggregate import VersioningException # from clinical_mdr_api.models.study_selections.study_selection @dataclass class SelectionHistory: """Class for selection history items""" study_selection_uid: str objective_uid: str | None objective_level_uid: str | None start_date: datetime.datetime status: str | None user_initials: str change_type: str end_date: datetime.datetime | None order: int objective_version: str | None class StudySelectionObjectiveRepository: @staticmethod def _acquire_write_lock_study_value(uid: str) -> None: db.cypher_query( """ MATCH (sr:StudyRoot {uid: $uid}) REMOVE sr.__WRITE_LOCK__ RETURN true """, {"uid": uid}, ) def _retrieves_all_data( self, study_uid: str | None = None, project_name: str | None = None, project_number: str | None = None, study_value_version: str | None = None, ) -> tuple[StudySelectionObjectiveVO]: query = "" query_parameters = {} if study_uid: if study_value_version: query = "MATCH (sr:StudyRoot { uid: $uid})-[l:HAS_VERSION{status:'RELEASED', version:$study_value_version}]->(sv:StudyValue)" query_parameters["study_value_version"] = study_value_version query_parameters["uid"] = study_uid else: query = "MATCH (sr:StudyRoot { uid: $uid})-[l:LATEST]->(sv:StudyValue)" query_parameters["uid"] = study_uid else: if study_value_version: query = "MATCH (sr:StudyRoot)-[l:HAS_VERSION{status:'RELEASED', version:$study_value_version}]->(sv:StudyValue)" query_parameters["study_value_version"] = study_value_version else: query = "MATCH (sr:StudyRoot)-[l:LATEST]->(sv:StudyValue)" if project_name is not None or project_number is not None: query += ( "-[:HAS_PROJECT]->(:StudyProjectField)<-[:HAS_FIELD]-(proj:Project)" ) filter_list = [] if project_name is not None: filter_list.append("proj.name=$project_name") query_parameters["project_name"] = project_name if project_number is not None: filter_list.append("proj.project_number=$project_number") query_parameters["project_number"] = project_number query += " WHERE " query += " AND ".join(filter_list) query += """ WITH sr, sv MATCH (sv)-[:HAS_STUDY_OBJECTIVE]->(so:StudyObjective) CALL { WITH so MATCH (so)-[:HAS_SELECTED_OBJECTIVE]->(:ObjectiveValue)<-[ver]-(or:ObjectiveRoot) WHERE ver.status = "Final" RETURN ver as ver, or as obj, true as is_instance ORDER BY ver.start_date DESC LIMIT 1 UNION WITH so MATCH (so)-[:HAS_SELECTED_OBJECTIVE_TEMPLATE]->(:ObjectiveTemplateValue)<-[ver]-(otr:ObjectiveTemplateRoot) WHERE ver.status = "Final" RETURN ver as ver, otr as obj, false as is_instance ORDER BY ver.start_date DESC LIMIT 1 } WITH DISTINCT sr, so, obj, ver, is_instance OPTIONAL MATCH (so)-[:HAS_OBJECTIVE_LEVEL]->(olr:CTTermRoot)<-[has_term:HAS_TERM]-(:CTCodelistRoot) -[:HAS_NAME_ROOT]->(:CTCodelistNameRoot)-[:LATEST_FINAL]->(:CTCodelistNameValue {name: "Objective Level"}) WITH sr, so, obj, ver, olr, has_term, is_instance ORDER BY has_term.order, so.order ASC MATCH (so)<-[:AFTER]-(sa:StudyAction) RETURN sr.uid AS study_uid, so.uid AS study_selection_uid, so.accepted_version AS accepted_version, obj.uid AS objective_uid, olr.uid AS objective_level_uid, has_term.order as objective_level_order, sa.date AS start_date, sa.user_initials AS user_initials, is_instance AS is_instance, ver.version AS objective_version """ all_objective_selections = db.cypher_query(query, query_parameters) all_selections = [] for selection in helpers.db_result_to_list(all_objective_selections): acv = selection.get("accepted_version", False) if acv is None: acv = False selection_vo = StudySelectionObjectiveVO.from_input_values( study_uid=selection["study_uid"], study_selection_uid=selection["study_selection_uid"], objective_uid=selection["objective_uid"], objective_version=selection["objective_version"], objective_level_uid=selection["objective_level_uid"], objective_level_order=selection["objective_level_order"], is_instance=selection["is_instance"], start_date=convert_to_datetime(value=selection["start_date"]), user_initials=selection["user_initials"], accepted_version=acv, ) all_selections.append(selection_vo) return tuple(all_selections) def find_all( self, project_name: str | None = None, project_number: str | None = None, ) -> list[StudySelectionObjectivesAR]: """ Finds all the selected study objectives for all studies, and create the aggregate :return: List of StudySelectionObjectivesAR, potentially empty """ all_selections = self._retrieves_all_data( project_name=project_name, project_number=project_number, ) # Create a dictionary, with study_uid as key, and list of selections as value selection_aggregate_dict = {} selection_aggregates = [] for selection in all_selections: if selection.study_uid in selection_aggregate_dict: selection_aggregate_dict[selection.study_uid].append(selection) else: selection_aggregate_dict[selection.study_uid] = [selection] # Then, create the list of VO from the dictionary for study_uid, selections in selection_aggregate_dict.items(): selection_aggregates.append( StudySelectionObjectivesAR.from_repository_values( study_uid=study_uid, study_objectives_selection=selections ) ) return selection_aggregates def find_by_study( self, study_uid: str, for_update: bool = False, study_value_version: str | None = None, ) -> StudySelectionObjectivesAR | None: """ Finds all the selected study objectives for a given study, and creates the aggregate :param study_uid: :param for_update: :return: """ if for_update: self._acquire_write_lock_study_value(study_uid) all_selections = self._retrieves_all_data( study_uid, study_value_version=study_value_version ) selection_aggregate = StudySelectionObjectivesAR.from_repository_values( study_uid=study_uid, study_objectives_selection=all_selections ) if for_update: selection_aggregate.repository_closure_data = all_selections return selection_aggregate def _get_audit_node( self, study_selection: StudySelectionObjectivesAR, study_selection_uid: str ): all_current_ids = [] for item in study_selection.study_objectives_selection: all_current_ids.append(item.study_selection_uid) all_closure_ids = [] for item in study_selection.repository_closure_data: all_closure_ids.append(item.study_selection_uid) # if uid is in current data if study_selection_uid in all_current_ids: # if uid is in closure data if study_selection_uid in all_closure_ids: return Edit() return Create() return Delete() def save(self, study_selection: StudySelectionObjectivesAR, author: str) -> None: """ Persist the set of selected study objectives from the aggregate to the database :param study_selection: :param author: """ assert study_selection.repository_closure_data is not None # get the closure_data closure_data = study_selection.repository_closure_data closure_data_length = len(closure_data) # getting the latest study value node study_root_node = StudyRoot.nodes.get(uid=study_selection.study_uid) latest_study_value_node = study_root_node.latest_value.single() if study_root_node.latest_locked.get_or_none() == latest_study_value_node: raise VersioningException( "You cannot add or reorder a study selection when the study is in a locked state." ) selections_to_remove = [] selections_to_add = [] # check if object is removed from the selection list - delete have been called if len(closure_data) > len(study_selection.study_objectives_selection): # remove the last item from old list, as there will no longer be any study objective with that high order selections_to_remove.append((len(closure_data), closure_data[-1])) # loop through new data - start=1 as order starts at 1 not at 0 and find what needs to be removed and added for order, selection in enumerate( study_selection.study_objectives_selection, start=1 ): # check whether something new is added if closure_data_length > order - 1: # check if anything has changed if selection is not closure_data[order - 1]: # update the selection by removing the old if the old exists, and adding new selection selections_to_remove.append((order, closure_data[order - 1])) selections_to_add.append((order, selection)) else: # else something new have been added selections_to_add.append((order, selection)) # audit trail nodes dictionary, holds the new nodes created for the audit trail audit_trail_nodes = {} # loop through and remove selections for order, study_objective in selections_to_remove: last_study_selection_node = latest_study_value_node.has_study_objective.get( uid=study_objective.study_selection_uid ) audit_node = self._get_audit_node( study_selection, study_objective.study_selection_uid ) audit_node = self._set_before_audit_info( audit_node=audit_node, study_objective_selection_node=last_study_selection_node, study_root_node=study_root_node, author=author, ) audit_trail_nodes[study_objective.study_selection_uid] = ( audit_node, last_study_selection_node, ) if isinstance(audit_node, Delete): self._add_new_selection( latest_study_value_node, order, study_objective, audit_node, last_study_selection_node, True, ) # loop through and add selections for order, selection in selections_to_add: last_study_selection_node = None if selection.study_selection_uid in audit_trail_nodes: audit_node, last_study_selection_node = audit_trail_nodes[ selection.study_selection_uid ] else: audit_node = Create() audit_node.user_initials = selection.user_initials audit_node.date = selection.start_date audit_node.save() study_root_node.audit_trail.connect(audit_node) self._add_new_selection( latest_study_value_node, order, selection, audit_node, last_study_selection_node, False, ) @staticmethod def _set_before_audit_info( audit_node: StudyAction, study_objective_selection_node: StudyObjective, study_root_node: StudyRoot, author: str, ) -> StudyAction: audit_node.user_initials = author audit_node.date = datetime.datetime.now(datetime.timezone.utc) audit_node.save() audit_node.has_before.connect(study_objective_selection_node) study_root_node.audit_trail.connect(audit_node) return audit_node def _add_new_selection( self, latest_study_value_node: StudyValue, order: int, selection: StudySelectionObjectiveVO, audit_node: StudyAction, last_study_selection_node: StudyObjective, for_deletion: bool = False, ): # Create new objective selection study_objective_selection_node = StudyObjective(order=order) study_objective_selection_node.uid = selection.study_selection_uid study_objective_selection_node.accepted_version = selection.accepted_version study_objective_selection_node.save() if not for_deletion: # Connect new node with study value latest_study_value_node.has_study_objective.connect( study_objective_selection_node ) # Connect new node with audit trail audit_node.has_after.connect(study_objective_selection_node) # check if objective is set if selection.objective_uid: if selection.is_instance: # Get the objective value and connect new node with objective value objective_root_node: ObjectiveRoot = ObjectiveRoot.nodes.get( uid=selection.objective_uid ) latest_objective_value_node = objective_root_node.get_value_for_version( selection.objective_version ) study_objective_selection_node.has_selected_objective.connect( latest_objective_value_node ) else: # Get the objective template value objective_template_root_node: ObjectiveTemplateRoot = ( ObjectiveTemplateRoot.nodes.get(uid=selection.objective_uid) ) latest_objective_template_value_node = ( objective_template_root_node.get_value_for_version( selection.objective_version ) ) study_objective_selection_node.has_selected_objective_template.connect( latest_objective_template_value_node ) # Set objective level if exists if selection.objective_level_uid: ct_term_root = CTTermRoot.nodes.get(uid=selection.objective_level_uid) study_objective_selection_node.has_objective_level.connect(ct_term_root) if last_study_selection_node: manage_previous_connected_study_selection_relationships( previous_item=last_study_selection_node, study_value_node=latest_study_value_node, new_item=study_objective_selection_node, exclude_study_selection_relationships=[], ) def study_objective_exists(self, study_objective_uid: str) -> bool: """ Simple function checking whether a study objective exist for a uid :return: boolean value """ study_objective_node = StudyObjective.nodes.first_or_none( uid=study_objective_uid ) if study_objective_node is None: return False return True def generate_uid(self) -> str: return StudyObjective.get_next_free_uid_and_increment_counter() def _get_selection_with_history( self, study_uid: str, study_selection_uid: str | None = None ): """ returns the audit trail for study objectives either for a specific selection or for all study objectives for the study """ if study_selection_uid: cypher = """ MATCH (sr:StudyRoot { uid: $study_uid})-[:AUDIT_TRAIL]->(:StudyAction)-[:BEFORE|AFTER]->(so:StudyObjective { uid: $study_selection_uid}) WITH so MATCH (so)-[:AFTER|BEFORE*0..]-(all_so:StudyObjective) WITH distinct(all_so) """ else: cypher = """ MATCH (sr:StudyRoot { uid: $study_uid})-[:AUDIT_TRAIL]->(:StudyAction)-[:BEFORE|AFTER]->(all_so:StudyObjective) WITH DISTINCT all_so """ specific_objective_selections_audit_trail = db.cypher_query( cypher + """ MATCH (all_so)-[:HAS_SELECTED_OBJECTIVE]->(ov:ObjectiveValue) CALL { WITH ov MATCH (ov) <-[ver]-(or:ObjectiveRoot) WHERE ver.status = "Final" RETURN ver as ver, or as or ORDER BY ver.start_date DESC LIMIT 1 } WITH DISTINCT all_so, or, ver OPTIONAL MATCH (all_so)-[:HAS_OBJECTIVE_LEVEL]->(olr:CTTermRoot) WITH DISTINCT all_so, or, olr, ver MATCH (all_so)<-[:AFTER]-(asa:StudyAction) OPTIONAL MATCH (all_so)<-[:BEFORE]-(bsa:StudyAction) WITH all_so, or, olr, asa, bsa, ver ORDER BY all_so.uid, asa.date DESC RETURN all_so.uid AS study_selection_uid, or.uid AS objective_uid, olr.uid AS objective_level_uid, asa.date AS start_date, asa.status AS status, asa.user_initials AS user_initials, labels(asa) AS change_type, bsa.date AS end_date, all_so.order AS order, ver.version AS objective_version""", {"study_uid": study_uid, "study_selection_uid": study_selection_uid}, ) result = [] for res in helpers.db_result_to_list(specific_objective_selections_audit_trail): for action in res["change_type"]: if "StudyAction" not in action: change_type = action if res["end_date"]: end_date = convert_to_datetime(value=res["end_date"]) else: end_date = None result.append( SelectionHistory( study_selection_uid=res["study_selection_uid"], objective_uid=res["objective_uid"], objective_level_uid=res["objective_level_uid"], start_date=convert_to_datetime(value=res["start_date"]), status=res["status"], user_initials=res["user_initials"], change_type=change_type, end_date=end_date, order=res["order"], objective_version=res["objective_version"], ) ) return result def find_selection_history( self, study_uid: str, study_selection_uid: str | None = None ) -> list[dict | None]: """ Simple method to return all versions of a study objectives for a study. Optionally a specific selection uid is given to see only the response for a specific selection. """ if study_selection_uid: return self._get_selection_with_history( study_uid=study_uid, study_selection_uid=study_selection_uid ) return self._get_selection_with_history(study_uid=study_uid) def close(self) -> None: # Our repository guidelines state that repos should have a close method # But nothing needs to be done in this one pass
#include <iostream> #include <string> #include <vector> #include "Vector2.hpp" #include "raylib.h" #include "raylib-cpp.hpp" #include "imnotgui.hpp" #include "imnotgui_extra.hpp" #define RTEXLOADER_IMPLEMENTATION #include "include/rtexloader.hpp" using namespace imnotgui; using namespace imnotgui::draw; using namespace imnotgui::element; /* <(-)\ _/_ |___|-. <| _| (O) */ int main() { SetConfigFlags(FLAG_WINDOW_RESIZABLE); InitWindow(1280, 720, "ImNotGUI Synchronization Example"); SetTargetFPS(60); initAtlas("resources/atlas_sync.png"); const std::vector<std::string> tabText = {"Intbox", "Floatbox"}; int tabIdx = 0; std::string intboxText = ""; int intValue = 0; std::string floatboxText = ""; float floatValue = 0; int globalTimer = 0; raylib::Vector2 facePos(700, 380), eye1Pos(-50, -70), eye2Pos(20, -70), mouthPos(-50, -10), capPos(0, -120), bubblePos(120, -220); while(!WindowShouldClose()) { globalTimer++; bool fever = (tabIdx==0 && intValue==100) || (tabIdx==1 && floatValue>99.0f); raylib::Vector2 _faceDelta, _eye1Delta, _eye2Delta, _mouthDelta, _capDelta, _bubbleDelta; if(!fever) { _faceDelta = raylib::Vector2{20*sinf(globalTimer*8*DEG2RAD), 30*sinf((globalTimer*6 + 60)*DEG2RAD)}; _eye1Delta = raylib::Vector2{6*sinf((globalTimer*12 - 60)*DEG2RAD), 6*sinf((globalTimer*9 + 20)*DEG2RAD)}; _eye2Delta = raylib::Vector2{6*sinf((globalTimer*5 - 120)*DEG2RAD), 6*sinf((globalTimer*5 + 180)*DEG2RAD)}; _mouthDelta = raylib::Vector2{8*sinf((globalTimer*7 - 10)*DEG2RAD), 5*sinf((globalTimer*14 + 10)*DEG2RAD)}; _capDelta = raylib::Vector2{10*sinf((globalTimer*3 + 50)*DEG2RAD), 10*sinf((globalTimer*3 + 140)*DEG2RAD)}; _bubbleDelta = raylib::Vector2{0, 10*sinf((globalTimer*4)*DEG2RAD)}; } else { _faceDelta = raylib::Vector2{25*sinf(globalTimer*16*DEG2RAD), 30*sinf((globalTimer*24 + 60)*DEG2RAD)}; _eye1Delta = raylib::Vector2{8*sinf((globalTimer*23 - 60)*DEG2RAD), 6*sinf((globalTimer*18 + 20)*DEG2RAD)}; _eye2Delta = raylib::Vector2{8*sinf((globalTimer*10 - 120)*DEG2RAD), 6*sinf((globalTimer*10 + 180)*DEG2RAD)}; _mouthDelta = raylib::Vector2{12*sinf((globalTimer*14 - 10)*DEG2RAD), 5*sinf((globalTimer*28 + 10)*DEG2RAD)}; _capDelta = raylib::Vector2{14*sinf((globalTimer*6 + 50)*DEG2RAD), 10*sinf((globalTimer*6 + 140)*DEG2RAD)}; _bubbleDelta = raylib::Vector2{0, 15*sinf((globalTimer*8)*DEG2RAD)}; } raylib::Vector2 _facePos = facePos + _faceDelta; raylib::Vector2 _eye1Pos = _facePos + eye1Pos + _eye1Delta; raylib::Vector2 _eye2Pos = _facePos + eye2Pos + _eye2Delta; raylib::Vector2 _mouthPos = _facePos + mouthPos + _mouthDelta; raylib::Vector2 _capPos = _facePos + capPos + _capDelta; raylib::Vector2 _bubblePos = facePos + bubblePos + _bubbleDelta; BeginDrawing(); ClearBackground(imnotgui::iuDark2); iui_begin(); // backdrop iui_rect(42, 0, 1196, 85, imnotgui::iuHellaDark); iui_rect(42, 85, 1196, 600, imnotgui::iuDark); iui_rect(42, 680, 1196, 40, imnotgui::iuHellaDark); iui_rect(62, 85, 450, 595, imnotgui::iuDark2); switch(iui_tab_h(42, 30, 9999, 55, 200, 200, {"Intbox", "Floatbox"}, tabIdx)) { case 0: { iui_setFontSize(25); iui_label_shadow(104, 120, "Enter any integer!", RAYWHITE, 5, 5, BLACK); iui_setFontSize(20); iui_intbox(104, 170, 300, 50, intboxText, intValue, "INTBOX"); iui_slider_h(104, 280, 300, intValue, -100, 100, "INTSLIDER_H"); iui_slider_v(464, 100, 200, intValue, -100, 100, "INTSLIDER_V"); iui_setFontSize(25); iui_label_shadow(104, 450, "<(-)\\", WHITE, 5, 5, BLACK); iui_label_shadow(102, 480, " _/_ <- What a nice flamingo!", WHITE, 5, 5, BLACK); iui_label_shadow(110, 510, " |___|-.", WHITE, 5, 5, BLACK); iui_label_shadow(112, 540, " <|", WHITE, 5, 5, BLACK); iui_label_shadow(108, 570, " _|", WHITE, 5, 5, BLACK); iui_setFontSize(20); DrawSpriteAtlas(atlas, getSprite("thief"), _facePos.x, _facePos.y, fever?20*sinf(globalTimer*4*DEG2RAD):0, WHITE); DrawSpriteAtlas(atlas, getSprite("eye"), _eye1Pos.x, _eye1Pos.y, fever?globalTimer*2:0, WHITE); DrawSpriteAtlas(atlas, getSprite("eye"), _eye2Pos.x, _eye2Pos.y, fever?globalTimer*2:0, WHITE); DrawSpriteAtlas(atlas, getSprite("mouth"), _mouthPos.x, _mouthPos.y, fever?globalTimer*2:0, WHITE); iui_setFontSize(30); draw_textbubble_bottom(_bubblePos.x, _bubblePos.y, 360, 80, TextFormat("Give me %d flamingos!", intValue), iuDark2, iuCream, 25, 20); iui_setFontSize(20); break; } case 1: { iui_setFontSize(25); iui_label_shadow(104, 120, "Enter any float!", RAYWHITE, 5, 5, BLACK); iui_setFontSize(20); iui_floatbox(104, 170, 300, 50, floatboxText, floatValue, "FLOATBOX"); iui_slider_h(104, 280, 300, floatValue, -100.0f, 100.0f, "FLOATSLIDER_H"); iui_slider_v(464, 100, 200, floatValue, -100.0f, 100.0f, "FLOATSLIDER_V"); iui_setFontSize(25); iui_label_shadow(104, 450, "(o) (o) (o)", WHITE, 5, 5, BLACK); iui_label_shadow(102, 480, " (o) (o) (o) <- Bunch of donuts", WHITE, 5, 5, BLACK); iui_label_shadow(110, 510, " (o) (o) (o)", WHITE, 5, 5, BLACK); iui_label_shadow(112, 540, "(o) (o) (o)", WHITE, 5, 5, BLACK); iui_label_shadow(108, 570, " (o) (o) (o)", WHITE, 5, 5, BLACK); iui_setFontSize(20); DrawSpriteAtlas(atlas, getSprite("police"), _facePos.x, _facePos.y, fever?20*sinf(globalTimer*4*DEG2RAD):0, WHITE); DrawSpriteAtlas(atlas, getSprite("eye"), _eye1Pos.x, _eye1Pos.y, fever?globalTimer*2:0, WHITE); DrawSpriteAtlas(atlas, getSprite("eye"), _eye2Pos.x, _eye2Pos.y, fever?globalTimer*2:0, WHITE); DrawSpriteAtlas(atlas, getSprite("mouth"), _mouthPos.x, _mouthPos.y, fever?globalTimer*2:0, WHITE); DrawSpriteAtlas(atlas, getSprite("cap"), _capPos.x, _capPos.y, fever?20*sinf(globalTimer*4*DEG2RAD):0, WHITE); iui_setFontSize(30); draw_textbubble_bottom(_bubblePos.x, _bubblePos.y, 360, 80, TextFormat("Give me %.2f donuts!", floatValue), iuDark2, iuCream, 25, 20); iui_setFontSize(20); break; } } int SCREEN_CENTER_X = GetScreenWidth()/2; int SCREEN_CENTER_Y = GetScreenHeight()/2; imnotgui::iui_end(); EndDrawing(); } CloseWindow(); return 0; }
import { SetlistSong } from "@app/hooks/useSetlistRelease"; import styles from "./SortChanger.module.css"; import * as ToggleGroup from "@radix-ui/react-toggle-group"; import { DateIcon, NoteIcon, SongIcon, TimeIcon } from "@app/assets/Icons"; export type SortType = keyof SetlistSong; interface Props { onChange: (sortType: SortType) => void; } const SortChanger: React.FC<Props> = ({ onChange }: Props) => { return <ToggleGroup.Root className={styles.container} type="single" defaultValue="title" onValueChange={(value: SortType) => onChange(value)}> <ToggleGroup.Item className={styles.item} value="title"> <NoteIcon /> Track </ToggleGroup.Item> <ToggleGroup.Item className={styles.item} value="artist"> <SongIcon /> Artist </ToggleGroup.Item> <ToggleGroup.Item className={styles.item} value="length"> <TimeIcon /> Length </ToggleGroup.Item> <ToggleGroup.Item className={styles.item} value="release"> <DateIcon /> Release </ToggleGroup.Item> </ToggleGroup.Root>; }; export default SortChanger;
import { SERVER_CONNECTION_TIMEOUT } from '@configs/constants'; import { ApiEndpoints, ApiMethods, ApiResponse, ContentTypes, ErrorMessages, InfoMessages, RequestCallbackFunction, RequestEvents, RequestHeaders, ResponseEvents, } from '@configs/types'; import logger from '@logger/index'; import { isString } from '@utils/guards'; import { getAuthToken } from '@utils/state'; import { StatusCodes } from 'http-status-codes'; import { IncomingMessage, request } from 'node:http'; const log = logger('NetworkController'); /** * A function that returns the callback function to be passed to the HTTP request for handling API response * @param resolve The reference of the resolve function to resolve a promise * @returns {RequestCallbackFunction} The callback function to be passed to the HTTP request. */ const responseHandler = (resolve: (value: ApiResponse) => void): RequestCallbackFunction => (resp: IncomingMessage) => { const responseStatus = resp.statusCode; if (responseStatus !== StatusCodes.OK) { return resolve({ error: responseStatus as number }); } const respData: Buffer[] = []; resp.setEncoding('utf8'); resp.on(ResponseEvents.DATA, (chunk: Buffer | string) => { respData.push(chunk instanceof Buffer ? chunk : Buffer.from(chunk)); }); resp.on(ResponseEvents.END, () => { resolve(JSON.parse(Buffer.concat(respData).toString('utf-8')) as ApiResponse); }); }; /** * A common function to call the required API. * It calls the API and returns a promise which is resolved when the response is obtained. * @param method The method to be used for calling the API * @param path The API endpoint * @param data For POST request, the data to be passed * @returns A promise that resolves when the response is obtained. */ const networkCall = (method: ApiMethods, path: ApiEndpoints, data?: string | object) => new Promise<ApiResponse>((resolve, reject) => { try { const bearerToken = getAuthToken(); const baseUrl = process.env['BASE_HOST']; if (method === ApiMethods.GET && !bearerToken) { // Bearer token is not there and the request to be made is of GET method log.error(ErrorMessages.INVALID_BEARER_TOKEN); return reject(ErrorMessages.INVALID_BEARER_TOKEN); } if (!baseUrl || !isString(baseUrl)) { log.error(ErrorMessages.INVALID_BASE_URL); return reject(ErrorMessages.INVALID_BASE_URL); } if (method === ApiMethods.POST && !data) { // Shows a warning if data is not passed for a POST request log.warn(InfoMessages.REQUEST_NO_DATA); } const requestRef = request( { hostname: baseUrl, protocol: 'http:', path, method, timeout: SERVER_CONNECTION_TIMEOUT }, responseHandler(resolve), ); if (method === ApiMethods.POST) { requestRef.setHeader( RequestHeaders.CONTENT_TYPE, typeof data === 'string' ? ContentTypes.TEXT : ContentTypes.JSON, ); requestRef.write(typeof data === 'string' ? data : JSON.stringify(data)); } else if (method === ApiMethods.GET) { requestRef.setHeader(RequestHeaders.AUTHORIZATION, `Bearer ${bearerToken}`); } requestRef.on(RequestEvents.ERROR, (err: unknown) => { const error = err instanceof Error ? err.message : (err as string) return reject(`${ErrorMessages.REQUEST_CREATION_ERROR}${error}`); }); requestRef.on(RequestEvents.CLOSE, (err: unknown) => { const error = err instanceof Error ? err.message : (err as string) return reject(`${ErrorMessages.REQUEST_CLOSED_PREMATURELY}${error}`); }); requestRef.end(); } catch (err) { const error = typeof err === 'string' ? err : (err as Error).message; log.error(`${ErrorMessages.REQUEST_TRANSFER_ERROR}${error}`); return reject(`${ErrorMessages.REQUEST_TRANSFER_ERROR}${error}`); } }); export default networkCall;
<template> <!-- App --> <div v-if="checkUrl"> <router-view /> </div> <div v-else-if="currentUser" class="flex bg-packed font-lexend dark:bg-gray-900"> <div id="sidebar-scroll" class="flex-sidebar lg:flex-auto w-sidebar lg:block hidden bg-white dark:bg-gray-800 border-r-2 dark:border-gray-700 h-screen lg:z-0 z-40 overflow-auto lg:relative fixed"> <Sidebar /> </div> <div class="flex-auto w-full overflow-auto h-screen" id="body-scroll"> <Header /> <router-view /> <Footer /> </div> </div> <!-- end app --> <div v-else> <router-view /> </div> </template> <script> import Sidebar from "@/components/Sidebar"; import Header from "@/components/Header"; import Footer from "@/components/Footer"; // npm-js import Scrollbar from "smooth-scrollbar"; export default { name: "App", components: { Header, Footer, Sidebar, }, computed: { checkUrl(){ return this.$route.path.includes('/takesurvey') || this.$route.path.includes('/submit-response') }, currentUser() { return this.$store.state.auth.user; }, showAdminBoard() { if (this.currentUser && this.currentUser['roles']) { return this.currentUser['roles'].includes('ROLE_SUPERADMIN'); } return false; }, showGuestBoard() { if (this.currentUser && this.currentUser['roles']) { return this.currentUser['roles'].includes('ROLE_ADMIN'); } return false; } }, mounted() { Scrollbar.init(document.querySelector("#body-scroll")); setTimeout(() => { var alert_dis = document.querySelectorAll(".alert-dismiss"); alert_dis.forEach((x) => x.addEventListener("click", function () { x.parentElement.classList.add("hidden"); }) ); }, 100); // var acc = document.getElementsByClassName("accordion"); // var i; // for (i = 0; i < acc.length; i++) { // acc[i].addEventListener("click", function () { // this.classList.toggle("active"); // var panel = this.nextElementSibling; // if (panel.style.display === "block") { // panel.style.display = "none"; // this.classList.remove("bg-gray-100"); // this.classList.add("bg-transparent"); // } else { // panel.style.display = "block"; // this.classList.add("bg-gray-100"); // this.classList.remove("bg-transparent"); // } // }); // } }, }; </script>
# **************************************************************************** # # # # Temperature functions # # # # **************************************************************************** # function T(Tsurf::Float64, Tmeso::Float64, Texo::Float64; z_meso_top=80e5, lapserate=-8e-5, weird_Tn_param=8, globvars...) #= Input: z: altitude above surface in cm Tsurf: Surface temperature in KT Tmeso: tropopause/mesosphere tempearture Texo: exobase temperature sptype: "neutral", "ion" or "electron". NECESSARY! Output: A single temperature value in K. Uses the typical temperature structure for neutrals, but interpolates temperatures for ions and electrons above 108 km according to the profiles in Fox & Sung 2001. =# GV = values(globvars) @assert all(x->x in keys(GV), [:alt]) # Subroutines ------------------------------------------------------------------------------------- function upperatmo_i_or_e(z, particle_type; Ti_array=Ti_interped, Te_array=Te_interped, select_alts=new_a) #= Finds the index for altitude z within new_a =# i = something(findfirst(isequal(z), select_alts), 0) returnme = Dict("electron"=>Te_array[i], "ion"=>Ti_array[i]) return returnme[particle_type] end function NEUTRALS() # function upper_atmo_neutrals(z_arr) # @. return Texo - (Texo - Tmeso)*exp(-((z_arr - z_meso_top)^2)/(weird_Tn_param*1e10*Texo)) # end Tn = zeros(size(GV.alt)) Tn[i_lower] .= Tsurf .+ lapserate*GV.alt[i_lower] Tn[i_meso] .= Tmeso # upper atmo Tfile = readdlm("FoxandSung2001_temps_mike.txt",',') T_n = Tfile[2,:] alt_i = Tfile[1,:] .* 1e5 interp_ion = LinearInterpolation(alt_i, T_n) Tn_interped = [interp_ion(a) for a in new_a]; Tn[i_upper] .= Tn_interped # upper_atmo_neutrals(GV.alt[i_upper]) return Tn end function ELECTRONS(;spc="electron") Te = zeros(size(GV.alt)) Te[i_lower] .= Tsurf .+ lapserate*GV.alt[i_lower] Te[i_meso] .= Tmeso # Upper atmo Tfile = readdlm("FoxandSung2001_temps_mike.txt",',') T_e = Tfile[4,:] alt_e = Tfile[1,:] .* 1e5 interp_elec = LinearInterpolation(alt_e, T_e) Te_interped = [interp_elec(a) for a in new_a]; Te[i_upper] .= Te_interped# upperatmo_i_or_e(alt[i_upper], spc) return Te end function IONS(;spc="ion") Ti = zeros(size(GV.alt)) Ti[i_lower] .= Tsurf .+ lapserate*GV.alt[i_lower] Ti[i_meso] .= Tmeso # Upper atmo Tfile = readdlm("FoxandSung2001_temps_mike.txt",',') T_i = Tfile[3,:] alt_i = Tfile[1,:] .* 1e5 interp_ion = LinearInterpolation(alt_i, T_i) Ti_interped = [interp_ion(a) for a in new_a]; Ti[i_upper] .= Ti_interped# upperatmo_i_or_e(alt[i_upper], spc) return Ti end # Define mesosphere scope. z_meso_bottom = alt[searchsortednearest(alt, (Tmeso-Tsurf)/(lapserate))] # Various indices to define lower atmo, mesosphere, and atmo ----------------- i_lower = findall(z->z < z_meso_bottom, GV.alt) i_meso = findall(z->z_meso_bottom <= z <= z_meso_top, GV.alt) i_upper = findall(z->z > z_meso_top, GV.alt) # i_meso_top = findfirst(z->z==z_meso_top, GV.alt) # For interpolating upper atmo temperatures from Fox & Sung 2001 new_a = collect(90e5:2e5:250e5) # In the lower atmosphere, neutrals, ions, and electrons all have the same temperatures. # if z < z_meso_bottom # return Tsurf + lapserate*z # elseif z_meso_bottom <= z <= z_meso_top # return Tmeso # # Near the top of the isothermal mesosphere, profiles diverge. # elseif z > z_meso_top # if sptype=="neutral" # return T_upper_atmo_neutrals(z) # else # return upperatmo_i_or_e(z, sptype) # end # end return Dict("neutrals"=>NEUTRALS(), "ions"=>IONS(), "electrons"=>ELECTRONS()) end
package com.example.studyflow.view.flashmindview import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.studyflow.R import com.example.studyflow.adapter.flasmind.FlashMindTagRecyclerAdapter import com.example.studyflow.databinding.FragmentFlashMindBinding import com.example.studyflow.model.Tag import com.example.studyflow.view.HomePageFragmentDirections import com.example.studyflow.viewmodel.flashmind.FlashMindViewModel import com.example.studyflow.viewmodel.tag.TagViewModel import java.util.Locale class FlashMindFragment : Fragment() { private lateinit var viewModel : FlashMindViewModel private val recyclerAdapter = FlashMindTagRecyclerAdapter(ArrayList<Tag>()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding : FragmentFlashMindBinding = DataBindingUtil.inflate( inflater, R.layout.fragment_flash_mind, container,false ) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this).get(FlashMindViewModel::class.java) viewModel.loadFlashMindTagsFromDB() val recyclerView = view.findViewById<RecyclerView>(R.id.flash_mind_tag_row_recyclerview) recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter = recyclerAdapter val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) { override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { viewHolder as FlashMindTagRecyclerAdapter.FlashMindTagViewHolder viewHolder.view.tag?.let { if (direction == ItemTouchHelper.RIGHT) { val action = FlashMindFragmentDirections.actionFlashMindFragmentToCardFragment(it) Navigation.findNavController(view).navigate(action) } else if (direction == ItemTouchHelper.LEFT) { val action = FlashMindFragmentDirections.actionFlashMindFragmentToExerciseFragment(it) Navigation.findNavController(view).navigate(action) } } } override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) // right background val backgroundRight = ColorDrawable(Color.BLUE) backgroundRight.setBounds(viewHolder.itemView.right + dX.toInt(), viewHolder.itemView.top, viewHolder.itemView.right, viewHolder.itemView.bottom) backgroundRight.draw(c) // Exercise text val textPaintRight = Paint().apply { color = Color.WHITE textSize = 50f textAlign = Paint.Align.CENTER } val textRight = "EXERCISE" c.drawText(textRight, viewHolder.itemView.right.toFloat() + dX / 2, viewHolder.itemView.bottom.toFloat() - viewHolder.itemView.height / 2, textPaintRight) // left background val backgroundLeft = ColorDrawable(Color.RED) backgroundLeft.setBounds(viewHolder.itemView.left + dX.toInt(), viewHolder.itemView.top, viewHolder.itemView.left, viewHolder.itemView.bottom) backgroundLeft.draw(c) // Exercise text val textPaintLeft = Paint().apply { color = Color.WHITE textSize = 50f textAlign = Paint.Align.CENTER } val textLeft = "CARDS" c.drawText(textLeft, viewHolder.itemView.left.toFloat() + dX / 2, viewHolder.itemView.bottom.toFloat() - viewHolder.itemView.height / 2, textPaintLeft) } } }) itemTouchHelper.attachToRecyclerView(recyclerView) observeLiveData() } fun observeLiveData() { viewModel.mutableFlashMindTags.observe(viewLifecycleOwner, Observer { tags -> tags.let { view?.findViewById<RecyclerView>(R.id.flash_mind_tag_row_recyclerview)?.visibility = View.VISIBLE recyclerAdapter.updateFlashMindTagList(tags) } }) } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace _05_howto_solve_maze { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private int Xmin, Ymin, CellWid, CellHgt, NumRows, NumCols; private MazeNode[,] Nodes = null; private MazeNode StartNode = null, EndNode = null; private List<MazeNode> Path = null; private void btnCreate_Click(object sender, EventArgs e) { NumCols = int.Parse(txtWidth.Text); NumRows = int.Parse(txtHeight.Text); CellWid = picMaze.ClientSize.Width / (NumCols + 2); CellHgt = picMaze.ClientSize.Height / (NumCols + 2); if (CellWid > CellHgt) CellWid = CellHgt; else CellHgt = CellWid; Xmin = (picMaze.ClientSize.Width - NumCols * CellWid) / 2; Ymin = (picMaze.ClientSize.Height - NumRows * CellHgt) / 2; Nodes = MakeNodes(NumCols, NumRows); Path = null; StartNode = null; EndNode = null; FindSpanningTree(Nodes[0, 0]); DisplayMaze(Nodes); } private MazeNode[,] MakeNodes(int wid, int hgt) { MazeNode[,] nodes = new MazeNode[hgt, wid]; for(int r=0; r < hgt; r++) { int y = Ymin + CellHgt * r; for(int c = 0; c < wid; c++) { int x = Xmin + CellWid * c; nodes[r, c] = new MazeNode(x, y, CellWid, CellHgt); } } for (int r = 0; r < hgt; r++) { for(int c = 0; c < wid; c++) { if (r > 0) nodes[r, c].AdjacentNodes[MazeNode.North] = nodes[r - 1, c]; if (r < hgt - 1) nodes[r, c].AdjacentNodes[MazeNode.South] = nodes[r + 1, c]; if (c > 0) nodes[r, c].AdjacentNodes[MazeNode.West] = nodes[r, c - 1]; if (c < wid - 1) nodes[r, c].AdjacentNodes[MazeNode.East] = nodes[r, c + 1]; } } return nodes; } private void FindSpanningTree(MazeNode root) { Random rand = new Random(); root.Predecessor = root; List<MazeLink> links = new List<MazeLink>(); foreach(MazeNode neighbor in root.AdjacentNodes) { if (neighbor != null) links.Add(new MazeLink(root, neighbor)); } while (links.Count > 0) { int link_num = rand.Next(0, links.Count); MazeLink link = links[link_num]; links.RemoveAt(link_num); MazeNode to_node = link.ToNode; link.ToNode.Predecessor = link.FromNode; for(int i = links.Count - 1; i >= 0; i--) { if (links[i].ToNode.Predecessor != null) links.RemoveAt(i); } foreach(MazeNode neighbor in to_node.AdjacentNodes) { if ((neighbor != null) && (neighbor.Predecessor == null)) links.Add(new MazeLink(to_node, neighbor)); } } } private void DisplayMaze(MazeNode[,] nodes) { int hgt = nodes.GetUpperBound(0) + 1; int wid = nodes.GetUpperBound(1) + 1; Bitmap bm = new Bitmap( picMaze.ClientSize.Width, picMaze.ClientSize.Height); using(Graphics gr = Graphics.FromImage(bm)) { gr.SmoothingMode = SmoothingMode.AntiAlias; for(int r = 0; r < hgt; r++) { for(int c = 0; c < wid; c++) { nodes[r, c].DrawWalls(gr, Pens.Black); } } } picMaze.Image = bm; } private void picMaze_MouseClick(object sender, MouseEventArgs e) { if (Nodes == null) return; if (e.Button == MouseButtons.Left) StartNode = FindNodeAt(e.Location); else if (e.Button == MouseButtons.Right) EndNode = FindNodeAt(e.Location); if ((StartNode != null) && (EndNode != null)) StartSolving(); picMaze.Refresh(); } private MazeNode FindNodeAt(Point location) { if (location.X < Xmin) return null; if (location.Y < Ymin) return null; int row = (location.Y - Ymin) / CellHgt; if (row >= NumRows) return null; int col = (location.X - Xmin) / CellWid; if (col >= NumCols) return null; return Nodes[row, col]; } private void picMaze_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; if (StartNode != null) StartNode.DrawCenter(e.Graphics, Brushes.Red); if (EndNode != null) EndNode.DrawCenter(e.Graphics, Brushes.Green); if((Path != null) && (Path.Count > 1)) { List<PointF> points = new List<PointF>(); foreach (MazeNode node in Path) points.Add(node.Center); e.Graphics.DrawLines(Pens.Red, points.ToArray()); } } private void StartSolving() { Path = new List<MazeNode>(); foreach (MazeNode node in Nodes) node.DefineNeighbors(); Path.Add(StartNode); StartNode.InPath = true; Solve(EndNode, Path); foreach (MazeNode node in Path) node.InPath = false; picMaze.Refresh(); } private bool Solve(MazeNode end_node, List<MazeNode> path) { MazeNode last_node = path[path.Count - 1]; if (last_node == end_node) return true; foreach (MazeNode neighbor in last_node.Neighbors) { if (!neighbor.InPath) { path.Add(neighbor); neighbor.InPath = true; if (Solve(end_node, path)) return true; neighbor.InPath = false; path.RemoveAt(path.Count - 1); } } return false; } } }
.R.home.bin <- function(arch) { bin <- R.home('bin') if (arch == "i386") bin <- normalizePath(paste0(bin, "/../i386/")) return(bin) } .install.dll <- function(arch = c("x64", "i386")) { arch <- match.arg(arch) temp <- tempdir() bin <- .R.home.bin(arch) ddl <- paste0(temp, '/sdldll.zip') dll <- paste0(temp, '/SDL.dll') if (!dir.exists(bin)) { cat(paste0(" - SDL dll installation skipped\n")) return(TRUE) } url <- if (arch == "x64") { 'https://www.libsdl.org/release/SDL-1.2.15-win32-x64.zip' } else { 'https://www.libsdl.org/release/SDL-1.2.15-win32.zip' } download.file(url, ddl, quiet = TRUE) cat(" - SDL dll downloaded\n") utils::unzip(ddl, exdir = temp) cat(" - SDL dll uncompressed\n") status <- file.copy(dll, bin, recursive = TRUE) if (!all(status)) { cat(" - Error: SDL dll was not copied correctly.\n") return(FALSE) } else { cat(" - SDL dll installed\n") return(TRUE) } } .install.headers <- function() { temp <- tempdir() ddl <- paste0(temp, '/sdldevel.tar.gz') inc <- paste0(R.home('include'), '/SDL') url <- 'https://www.libsdl.org/release/SDL-devel-1.2.15-mingw32.tar.gz' if (!dir.exists(inc)) dir.create(inc) download.file(url, ddl, quiet = TRUE) cat(" - SDL headers downloaded\n") utils::untar(ddl, exdir = temp) cat(" - SDL headers uncompressed\n") includes <- paste0(temp, '/SDL-1.2.15/include/SDL/') includes <- list.files(includes, full.names = T) status <- file.copy(includes, inc, recursive = TRUE) if (!all(status)) { cat(" - Error: headers were not copied correctly\n") return(FALSE) } else { cat(" - SDL headers installed\n") return(TRUE) } } install.sdl <- function() { if (.Platform$OS.type != "windows") stop("This script is designed to install the SDL on Windows only.", call. = FALSE) cat("Downloading and installing SDL headers...\n") s1 <- .install.headers() cat("Downloading and installing SDL dll (x64)...\n") s2 <- .install.dll("x64") cat("Downloading and installing SDL dll (i386)...\n") s3 <- .install.dll("i386") if (s1 + s2 + s3 < 3) stop("Something went wrong during the installation.", call. = FALSE) else cat("Installation of the SDL library: ok") } install.sdl() rm(install.sdl, .install.headers, .install.dll, .R.home.bin)
// // FilterTabbarCollectionViewAdapter.swift // Trinap // // Created by Doyun Park on 2022/11/23. // Copyright © 2022 Trinap. All rights reserved. // import UIKit import RxSwift import RxCocoa final class FilterView: UICollectionView, UICollectionViewDelegate { private var filterMode: FilterMode private var disposeBag = DisposeBag() private var filterDataSource: UICollectionViewDiffableDataSource<Int, FilterMode.Item>? private let underlineView = UIView().than { $0.backgroundColor = .black } init(filterMode: FilterMode) { self.filterMode = filterMode super.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) configureCollectionView() configureUI() bind() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureCollectionView() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16) self.collectionViewLayout = layout self.showsHorizontalScrollIndicator = false self.delegate = self let snapshot = generateSnapshot(self.filterMode) self.register(FilterCell.self) self.filterDataSource = generateDataSource() self.filterDataSource?.apply(snapshot) self.selectItem(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .centeredHorizontally) } private func configureUI() { self.backgroundColor = TrinapAsset.white.color self.layer.masksToBounds = false self.layer.shadowOffset = CGSize(width: 0, height: 1.5) self.layer.shadowRadius = 1 self.layer.shadowOpacity = 0.1 self.addSubview(underlineView) } private func generateDataSource() -> UICollectionViewDiffableDataSource<Int, FilterMode.Item> { return UICollectionViewDiffableDataSource(collectionView: self) { collectionView, indexPath, itemIdentifier in guard let cell = collectionView.dequeueCell(FilterCell.self, for: indexPath) else { return UICollectionViewCell() } cell.configure(title: itemIdentifier.title) return cell } } private func generateSnapshot(_ filterMode: FilterMode) -> NSDiffableDataSourceSnapshot<Int, FilterMode.FilterItem> { var snapshot = NSDiffableDataSourceSnapshot<Int, FilterMode.FilterItem>() snapshot.appendSections([0]) snapshot.appendItems(filterMode.items, toSection: 0) return snapshot } private func bind() { self.rx.itemSelected .compactMap { [weak self] indexPath in return self?.cellForItem(at: indexPath) } .subscribe(onNext: { [weak self] cell in guard let self else { return } let xPosition = cell.frame.origin.x let width = cell.frame.width self.updateView(xPosition: xPosition, width: width) UIView.animate(withDuration: 0.3) { self.layoutIfNeeded() } }) .disposed(by: disposeBag) } private func updateView(xPosition: CGFloat, width: CGFloat) { self.underlineView.snp.remakeConstraints { make in make.leading.equalToSuperview().inset(xPosition) make.width.equalTo(width) make.bottom.equalToSuperview().offset(trinapOffset * 6) make.height.equalTo(2) } } } // MARK: - Layout extension FilterView: UICollectionViewDelegateFlowLayout { private func configureCollectionViewLoyout() -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize layout.scrollDirection = .horizontal return layout } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let cell = collectionView.dequeueCell(FilterCell.self, for: indexPath), let data = self.filterDataSource?.itemIdentifier(for: indexPath) else { return .zero } let size = cell.sizeFittingWith(cellHeight: trinapOffset * 6, text: data.title) if indexPath.row == 0 { underlineView.snp.makeConstraints { make in make.left.equalToSuperview().offset(16) make.width.equalTo(size.width) make.height.equalTo(2) make.bottom.equalToSuperview().offset(trinapOffset * 6) } } return size } }
#include "sort.h" /** * swap_quick - Swaps the positions of two elements in an array. * @array: The array. * @idx1: Index of the first element. * @idx2: Index of the second element. */ void swap_quick(int *array, ssize_t idx1, ssize_t idx2) { int temp; temp = array[idx1]; array[idx1] = array[idx2]; array[idx2] = temp; } /** * hoare_partition - Implements the Hoare partition scheme for quicksort. * @array: The array to be partitioned. * @low: The starting index of the partition. * @high: The ending index of the partition. * @size: The size of the array. * * Return: The position of the last element in the sorted partition. */ int hoare_partition(int *array, int low, int high, int size) { int pivot = array[high]; int i = low - 1; int j = high + 1; while (1) { do { i++; } while (array[i] < pivot); do { j--; } while (array[j] > pivot); if (i >= j) return i; swap_quick(array, i, j); print_array(array, size); } } /** * quicksort - Recursive function to implement the quicksort algorithm. * @array: The array to be sorted. * @low: The starting index of the partition. * @high: The ending index of the partition. * @size: The size of the array. */ void quicksort(int *array, ssize_t low, ssize_t high, int size) { ssize_t position = 0; if (low < high) { position = hoare_partition(array, low, high, size); quicksort(array, low, position - 1, size); quicksort(array, position, high, size); } } /** * quick_sort_hoare - Prepares the terrain for the quicksort algorithm. * @array: The array to be sorted. * @size: The size of the array. */ void quick_sort_hoare(int *array, size_t size) { if (!array || size < 2) return; quicksort(array, 0, size - 1, size); }
from typing import List class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: res = [] candidates.sort() cur = [] def dfs(i, acc): # note we have success condition first here if acc == target: res.append(cur.copy()) return if i >= len(candidates) or acc > target: return # take the value cur.append(candidates[i]) dfs(i + 1, acc + candidates[i]) # not take the value and ignore all same values cur.pop() while i + 1 < len(candidates) and candidates[i] == candidates[i + 1]: i += 1 dfs(i + 1, acc) dfs(0, 0) return res
package com.example.myacronymapplication.network import com.example.myacronymapplication.BuildConfig import com.example.myacronymapplication.data.NactemResponseItem import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query class NactemRetofit { companion object { fun buildRetrofitInstance() : Retrofit = Retrofit.Builder().baseUrl(BuildConfig.MYBASEURL) .addConverterFactory(GsonConverterFactory.create()) .build() fun getService() : NactemService = buildRetrofitInstance().create(NactemService::class.java) } } interface NactemService { @GET("dictionary.py") suspend fun getFullForm(@Query("sf") sf: String) : List<NactemResponseItem> }
from django.http import HttpResponseRedirect from django.shortcuts import render,redirect from django.urls import reverse from userauths.forms import UserRegisterForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from userauths.models import Profile, User from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def RegisterView(request): if request.user.is_authenticated: messages.warning(request, "You are registered!") return redirect(reverse('core:feed')) form = UserRegisterForm(request.POST or None) if form.is_valid(): form.save() full_name = form.cleaned_data.get("full_name") phone = form.cleaned_data.get("phone") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password1") full_name = form.cleaned_data.get("full_name") full_name = form.cleaned_data.get("full_name") user = authenticate(email=email, password=password) login(request, user) profile = Profile.objects.get(user= request.user) profile.full_name= full_name profile.phone= phone profile.save() messages.success(request, f"hi {full_name}. your account created successfully") return redirect(reverse('core:feed')) context = { "form" : form } return render(request,'userauths/sign-up.html',context) @csrf_exempt def LoginView(request): # if request.user.is_authenticated: # return redirect('core:feed') if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') try: user = User.objects.get(email=email) user = authenticate(request, email=email, password=password) if user is not None: login(request, user) messages.success(request, "You are Logged In") return redirect('core:feed') else: messages.error(request, 'Username or password does not exit.') return redirect(reverse("userauths:sign-up")) except: messages.error(request, 'User does not exist') return redirect(reverse("userauths:sign-up")) return HttpResponseRedirect("/") def LogoutView(request): logout(request) messages.success(request, 'You have been logged out') return redirect("userauths:sign-up")
import cv2 def auto_brightness_contrast_grayscale(image, clip_hist_percent): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Calculate grayscale histogram hist = cv2.calcHist([gray], [0], None, [256], [0, 256]) hist_size = len(hist) # Calculate cumulative distribution from the histogram accumulator = [] accumulator.append(float(hist[0])) for index in range(1, hist_size): accumulator.append(accumulator[index - 1] + float(hist[index])) # Locate points to clip maximum = accumulator[-1] clip_hist_percent *= (maximum/100.0) clip_hist_percent /= 2.0 # Locate left cut minimum_gray = 0 while accumulator[minimum_gray] < clip_hist_percent: minimum_gray += 1 # Locate right cut maximum_gray = hist_size - 1 while accumulator[maximum_gray] >= (maximum - clip_hist_percent): maximum_gray -= 1 # Calculate alpha and beta values alpha = 255 / (maximum_gray - minimum_gray) beta = -minimum_gray * alpha auto_result = cv2.convertScaleAbs(image, alpha=alpha, beta=beta) auto_result = cv2.cvtColor(auto_result, cv2.COLOR_BGR2GRAY) auto_result = cv2.cvtColor(auto_result, cv2.COLOR_GRAY2RGB) return auto_result
= CSV Format ifndef::env-site,env-github[] include::_attributes.adoc[] endif::[] :keywords: format, csv, */csv, application/csv MIME type: `application/csv` ID: `csv` The CSV data format is represented as a DataWeave array of objects in which each object represents a row. All simple values are represented as strings. The DataWeave reader for CSV input supports the following parsing strategies: * Indexed * In-Memory * Streaming By default, the CSV reader stores input data from an entire file in-memory if the file is 1.5MB or less. If the file is larger than 1.5 MB, the process writes the data to disk. For very large files, you can improve the performance of the reader by setting a streaming property to true. For additional details, see xref:dataweave-formats.adoc#dw_readers_writers[DataWeave Readers]. == Examples The following examples show uses of the CSV format. * <<example1>> * <<example2>> [[example1]] === Example: Represent CSV Data The following example shows how DataWeave represents CSV data. ==== Input The following sample data serves as input for the DataWeave source. [source,csv,linenums] ---- name,lastname,age,gender Mariano,de Achaval,37,male Paula,de Estrada,37,female ---- ==== Source The DataWeave script transforms the CSV input payload to the DataWeave (dw) format and MIME type. [source,dataweave,linenums] ---- %dw 2.0 output application/dw --- payload ---- ==== Output The DataWeave script produces the following output. [source,dataweave,linenums] ---- [ { name: "Mariano", lastname: "de Achaval", age: "37", gender: "male" }, { name: "Paula", lastname: "de Estrada", age: "37", gender: "female" } ] ---- [[example2]] === Example: Stream CSV Data By default, the CSV reader stores input data from an entire file in-memory if the file is 1.5MB or less. If the file is larger than 1.5 MB, the process writes the data to disk. For very large files, you can improve the performance of the reader by setting a `streaming` property to `true`. To demonstrate the use of this property, the next example streams a CSV file and transforms it to JSON. ==== Input The structure of the CSV input looks something like the following. Note that a streamed file is typically much longer. .CSV File Input for Streaming Example (truncated): [source,csv,linenums] ---- street,city,zip,state,beds,baths,sale_date 3526 HIGH ST,SACRAMENTO,95838,CA,2,1,Wed May 21 00:00:00 EDT 2018 51 OMAHA CT,SACRAMENTO,95823,CA,3,1,Wed May 21 00:00:00 EDT 2018 2796 BRANCH ST,SACRAMENTO,95815,CA,2,1,Wed May 21 00:00:00 EDT 2018 2805 JANETTE WAY,SACRAMENTO,95815,CA,2,1,Wed May 21 00:00:00 EDT 2018 6001 MCMAHON DR,SACRAMENTO,95824,CA,2,1,,Wed May 21 00:00:00 EDT 2018 5828 PEPPERMILL CT,SACRAMENTO,95841,CA,3,1,Wed May 21 00:00:00 EDT 2018 ---- ==== XML Configuration To demonstrate a use of the `streaming` property, the following Mule flow streams a CSV file and transforms it to JSON. [source,xml,linenums] ---- <flow name="dw-streamingFlow" > <scheduler doc:name="Scheduler" > <scheduling-strategy > <fixed-frequency frequency="1" timeUnit="MINUTES"/> </scheduling-strategy> </scheduler> <file:read path="${app.home}/input.csv" config-ref="File_Config" outputMimeType="application/csv; streaming=true; header=true"/> <ee:transform doc:name="Transform Message" > <ee:message > <ee:set-payload ><![CDATA[%dw 2.0 output application/json --- payload map ((row) -> { zipcode: row.zip })]]></ee:set-payload> </ee:message> </ee:transform> <file:write doc:name="Write" config-ref="File_Config1" path="/path/to/output/file/output.json"/> <logger level="INFO" doc:name="Logger" message="#[payload]"/> </flow> ---- * The example configures the Read operation (`<file:read/>`) to stream the CSV input by setting `outputMimeType="application/csv; streaming=true"`. The input CSV file is located in the project directory, `src/main/resources`, which is the location of `${app.home}`. * The DataWeave script in the *Transform Message* component uses the `map` function to iterate over each row in the CSV payload and select the value of each field in the `zip` column. * The Write operation returns a file, `output.json`, which contains the result of the transformation. * The Logger prints the same output payload that you see in `output.json`. ==== Output The CSV streaming example produces the following output. [source,json,linenums] ---- [ { "zipcode": "95838" }, { "zipcode": "95823" }, { "zipcode": "95815" }, { "zipcode": "95815" }, { "zipcode": "95824" }, { "zipcode": "95841" } ] ---- [[properties]] == Configuration Properties DataWeave supports the following configuration properties for this format. [[reader_properties]] === Reader Properties This format accepts properties that provide instructions for reading input data. [cols="1,1,1,3a", options="header"] |=== |Parameter |Type |Default|Description |`bodyStartLineNumber` |`Number`|`0`|Line number on which the body starts. |`escape` |`String`|`\`|Character to use for escaping special characters, such as separators or quotes. |`header` |`Boolean`|`true`|Indicates whether a CSV header is present. * If `header=true`, you can access the fields within the input by name, for example, `payload.userName`. * If `header=false`, you must access the fields by index, referencing the entry first and the field next, for example, `payload[107][2]`. Valid values are `true` or `false`. |`headerLineNumber` |`Number`|`0`|Line number on which the CSV header is located. |`ignoreEmptyLine` |`Boolean`|`true`|Indicates whether to ignore an empty line. Valid values are `true` or `false`. |`quote` |`String`|`"`|Character to use for quotes. |`separator` |`String`|`,`|Character that separates one field from another field. |`streaming` |`Boolean`|`false`|Streams input when set to `true`. Use only if entries are accessed sequentially. The input must be a top-level array. See the <<example2, streaming example>>, and see https://docs.mulesoft.com/dataweave/latest/dataweave-formats#dw_readers_writers[DataWeave Readers]. Valid values are `true` or `false`. |=== [[writer_properties]] === Writer Properties This format accepts properties that provide instructions for writing output data. [cols="1,1,1,3a", options="header"] |=== |Parameter |Type |Default|Description |`bodyStartLineNumber` |`Number`|`0`|Line number on which the body starts. |`bufferSize` |`Number`|`8192`|Size of the buffer writer. The value must be greater than 8. |`deferred` |`Boolean`|`false`|Generates the output as a data stream when set to `true`, and defers the script's execution until the generated content is consumed. Valid values are `true` or `false`. |`encoding` |`String`|`null`|The encoding to use for the output, such as UTF-8. |`escape` |`String`|`\`|Character to use for escaping special characters, such as separators or quotes. |`header` |`Boolean`|`true`|Indicates whether a CSV header is present. * If `header=true`, you can access the fields within the input by name, for example, `payload.userName`. * If `header=false`, you must access the fields by index, referencing the entry first and the field next, for example, `payload[107][2]`. Valid values are `true` or `false`. |`headerLineNumber` |`Number`|`0`|Line number on which the CSV header is located. |`ignoreEmptyLine` |`Boolean`|`true`|Indicates whether to ignore an empty line. Valid values are `true` or `false`. |`lineSeparator` |`String`|`New Line`|Line separator to use when writing CSV, for example, `"\r\n"`. By default, DataWeave uses the system line separator. |`quote` |`String`|`"`|Character to use for quotes. |`quoteHeader` |`Boolean`|`false`|Quotes header values when set to `true`. Valid values are `true` or `false`. |`quoteValues` |`Boolean`|`false`|Quotes every value when set to `true`, including values that contain special characters. Valid values are `true` or `false`. |`separator` |`String`|`,`|Character that separates one field from another field. |=== [[mime_types]] == Supported MIME Types This format supports the following MIME types. [cols="1", options="header"] |=== | MIME Type |`*/csv` |===
#先对words进行排序,然后用set存储满足(由words词典中其他单词逐步添加一个字母组成)条件的单词,用res存储要输出的结果(set中最长的一个单词)。 #注意单词为单个字母时一定是满足条件的,所以要加进去。后面遍历的时候发现word[:-1]在set里面则将word加到set里去。当word长度大于res长度时用word替换res。 #执行用时 : 80 ms, 在Longest Word in Dictionary的Python提交中击败了100.00% 的用户 内存消耗 : 12.2 MB, 在Longest Word in Dictionary的Python提交中击败了42.10% 的用户 class Solution(object): def longestWord(self, words): """ :type words: List[str] :rtype: str """ words.sort() save = set() #用list存储的话,后面搜索会比较慢 res = "" for word in words: if word[:-1] in save or word[:-1] == '': #单字母的单词 word[:-1] == '' if len(word) > len(res): res = word save.add(word) return res
# AutoRescan Plugin for Squeezebox Server # Copyright © Stuart Hickinbottom 2007-2014 # This file is part of AutoRescan. # # AutoRescan 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 2 of the License, or # (at your option) any later version. # # AutoRescan 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 AutoRescan; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # This is a plugin to provide automatic rescanning of music files as they are # changed within the filesystem. It depends on the 'inotify' kernel function # within Linux and, therefore, currently only works when used on a Linux system # where that kernel feature has been enabled. See the INSTALL file for further # instructions on the kernel configuration. # # For further details see: # http://www.hickinbottom.com use strict; use warnings; package Plugins::AutoRescan::Plugin; use base qw(Slim::Plugin::Base); use utf8; use Plugins::AutoRescan::Settings; use Slim::Utils::Strings qw (string); use Slim::Utils::Timers; use Slim::Utils::Log; use Slim::Utils::Prefs; use Time::HiRes; use Scalar::Util qw(blessed); use File::Find; use File::Basename; use Slim::Utils::OSDetect; # Name of this plugin - used for various global things to prevent clashes with # other plugins. use constant PLUGIN_NAME => 'PLUGIN_AUTORESCAN'; # Preference ranges and defaults. use constant AUTORESCAN_DELAY_DEFAULT => 5; use constant AUTORESCAN_SCRIPT_DEFAULT => ''; # Polling control. use constant AUTORESCAN_POLL => 1; # Export the version to the server (as a subversion keyword). use vars qw($VERSION); $VERSION = 'v1.4.1 (trunk-7.x)'; # A logger we will use to write plugin-specific messages. my $log = Slim::Utils::Log->addLogCategory( { 'category' => 'plugin.autorescan', 'defaultLevel' => 'INFO', 'description' => 'PLUGIN_AUTORESCAN' } ); # Monitor object that contains the platform-specific functionality for # monitoring directories for changes. my $monitor; # Hash so we can track directory monitors. my %monitors; # Access to preferences for this plugin and for server-wide settings. my $myPrefs = preferences('plugin.autorescan'); my $serverPrefs = preferences('server'); # Flag to protect against multiple initialisation or shutdown my $initialised = 0; # Below are functions that are part of the standard Squeezebox Server plugin # interface. # Return the name of this plugin; this goes on the server setting plugin # page, for example. sub getDisplayName { return PLUGIN_NAME; } # Set up this plugin when it's inserted or the server started. sub initPlugin() { my $class = shift; return if $initialised; # don't need to do it twice $log->info("Initialising $VERSION"); $class->SUPER::initPlugin(@_); # Create the monitor interface, depending on our current platorm. my $os = Slim::Utils::OSDetect::OS(); if ( $os eq 'unix' ) { $log->debug('Linux monitoring method selected'); eval 'use Plugins::AutoRescan::Monitor_Linux'; $monitor = Plugins::AutoRescan::Monitor_Linux->new($class); } elsif ( $os eq 'win' ) { $log->debug('Windows monitoring method selected'); eval 'use Plugins::AutoRescan::Monitor_Windows'; $monitor = Plugins::AutoRescan::Monitor_Windows->new($class); } else { $log->warn( "Unsupported operating system type '$os' - will not monitor for changes" ); } my $can_script = 0; $can_script = $monitor->{can_script} if ($monitor); # Initialise settings. Plugins::AutoRescan::Settings->new( $class, $can_script ); # Remember we're now initialised. This prevents multiple-initialisation, # which may otherwise cause trouble with duplicate hooks or modes. $initialised = 1; # Make sure the preferences are set to something sensible before we call # on them later. checkDefaults(); # If initialisation worked then add monitors. addWatch() if ($monitor); $log->debug("Initialisation complete"); } # Called when the plugin is being disabled or Squeezebox Server shut down. sub shutdownPlugin() { my $class = shift; return if !$initialised; # don't need to do it twice $log->debug("Shutting down"); # If we've still got a pending callback timer then cancel it so we're # not called back after shutdown. killCallbackTimer(); # Shutdown the monitor. $log->debug("Removing change monitor"); $monitor->delete if $monitor; # We're no longer initialised. $initialised = 0; } # Below are functions that are specific to this plugin. # Called during initialisation, this makes sure that the plugin preferences # stored are sensible. This has the effect of adding them the first time this # plugin is activated and removing the need to check they're defined in each # case of reading them. sub checkDefaults { if ( !defined( $myPrefs->get('delay') ) ) { $myPrefs->set( 'delay', AUTORESCAN_DELAY_DEFAULT ); } if ( !defined( $myPrefs->get('script') ) ) { $myPrefs->set( 'script', AUTORESCAN_SCRIPT_DEFAULT ); } # If the revision isn't yet in the preferences we set it to something # that's guaranteed to be different so that we can detect the plugin # is used for the first time. if ( !defined( $myPrefs->get('revision') ) ) { $myPrefs->set( 'revision', '-undefined-' ); } } # Add a watch to the music folder. sub addWatch() { # Filter media directories for those with audio - LMS7.7+ only. my $audioDirs = Slim::Utils::Misc::getMediaDirs('audio'); for my $audioDir (@$audioDirs) { if ( defined $audioDir && -d $audioDir ) { $log->debug("Adding monitor to music directory: $audioDir"); # Add the watch callback. This will also watch all subordinate folders. addNotifierRecursive($audioDir); # Tell the monitor. $monitor->addDone if $monitor; # Add a poller callback timer. We need this to pump events. Slim::Utils::Timers::setTimer( undef, Time::HiRes::time() + AUTORESCAN_POLL, \&poller ); } else { $log->info( "Music folder is not defined - skipping add of change monitor"); } } } # Recursively add notifiers for all folders under a given root. sub addNotifierRecursive($) { my $dir = shift; if ( -d $dir ) { find( { wanted => sub { addNotifier($File::Find::name) if -d $File::Find::name; }, follow => 1, no_chdir => 1 }, $dir ); } } # Add an monitor for a given directory. sub addNotifier($) { my $dir = shift; # We prune the search from directories that start with a '.' # (don't you also keep your music files in git-annex..?) if (basename($dir) =~ m/^\./) { $File::Find::prune = 1; $log->debug("Not monitoring hidden directory tree: $dir"); return; } # Only add a monitor if we're not already monitoring this directory (and # it is indeed a directory). if (not exists $monitors{$dir}) { # Remember the monitor object created - we do this so we can check if # it's already being monitored later on. $monitors{$dir} = $monitor->addWatch($dir); } } # Called periodically so we can detect and dispatch any events. sub poller() { # Pump that poller - let the monitors decide how to do that. We support # pumping for each monitored directory, or only once in total, depending # on what the monitor type wants to do. if ( $monitor && $monitor->{poll_each} ) { # Loop through the monitored directories and poll each. for my $dir ( keys %monitors ) { $monitor->poll( $dir, $monitors{$dir} ); } } else { # Pump the poller once. $monitor->poll if $monitor; } # Schedule another poll. Slim::Utils::Timers::setTimer( undef, Time::HiRes::time() + AUTORESCAN_POLL, \&poller ); } # Note a directory as having been touched - we schedule a callback to see if # it's convenient to perform a rescan. sub noteTouch { my $dir = shift; # Schedule a callback to trigger a rescan in a short time. setCallbackTimer(); # Make sure we are monitoring any new subdirectories under here. addNotifierRecursive($dir); } # Remove any existing delayed callback timer. This is tolerant if there's # currently no timer set. sub killCallbackTimer { $log->debug("Cancelling any pending change callback"); Slim::Utils::Timers::killOneTimer( undef, \&delayedChangeCallback ); } # Add a new callback timer to call us back in a short while. sub setCallbackTimer { # Remove any existing timer. killCallbackTimer(); # Schedule a callback. $log->debug("Scheduling a delayed callback"); Slim::Utils::Timers::setTimer( undef, Time::HiRes::time() + $myPrefs->get('delay'), \&delayedChangeCallback ); } # Called following a short delay following the most recently detected change. # This is what ultimately triggers the database rescan. sub delayedChangeCallback { $log->debug("Delayed callback invoked"); # Check if there's a scan currently in progress. if ( Slim::Music::Import->stillScanning() ) { # If so then schedule another delayed callback - we'll try again in a short # while. $log->debug("Putting off rescan due to current scan being in progress"); setCallbackTimer(); } else { # If not then we'll trigger the rescan now. $log->info("Triggering database rescan following directory changes"); Slim::Control::Request::executeRequest( undef, ['rescan'] ); # If the monitor supports a rescan script then call it. if ( $monitor->{can_script} ) { $monitor->executeScript( $myPrefs->get('script') ); } } } 1; __END__ # Local Variables: # tab-width:4 # indent-tabs-mode:t # End:
import 'package:get_it/get_it.dart'; import 'package:get_storage/get_storage.dart'; import 'package:grocery_app/data/local/data_source/auth_local_datasource.dart'; import 'package:grocery_app/data/remote/data_source/auth_data_source.dart'; import 'package:grocery_app/data/remote/data_source/category_data_source.dart'; import 'package:grocery_app/data/remote/data_source/home_remote_data_source.dart'; import 'package:grocery_app/data/remote/data_source/offer_data_source.dart'; import 'package:grocery_app/data/remote/data_source/products_remote_data_source.dart'; import 'package:grocery_app/data/repository/auth_data_repository_impl.dart'; import 'package:grocery_app/data/repository/auth_local_repository_impl.dart'; import 'package:grocery_app/data/repository/category_data_repository_impl.dart'; import 'package:grocery_app/data/repository/home_repository_impl.dart'; import 'package:grocery_app/data/repository/productRepositoryImpl.dart'; import 'package:grocery_app/domain/repository/auth_data_repository.dart'; import 'package:grocery_app/domain/repository/auth_local_repositary.dart'; import 'package:grocery_app/domain/repository/category_data_repository.dart'; import 'package:grocery_app/domain/repository/home_repoistory.dart'; import 'package:grocery_app/domain/repository/product_repository.dart'; import 'package:grocery_app/domain/usecase/add_address_use_case.dart'; import 'package:grocery_app/domain/usecase/add_cart_use_case.dart'; import 'package:grocery_app/domain/usecase/add_fav_use_case.dart'; import 'package:grocery_app/domain/usecase/delete_cart_use_case.dart'; import 'package:grocery_app/domain/usecase/get_all_locations.dart'; import 'package:grocery_app/domain/usecase/get_cart_use_case.dart'; import 'package:grocery_app/domain/usecase/get_expand_product_usecase.dart'; import 'package:grocery_app/domain/usecase/get_fav_use_case.dart'; import 'package:grocery_app/domain/usecase/get_product_usecase.dart'; import 'package:grocery_app/domain/usecase/get_user_user_case.dart'; import 'package:grocery_app/domain/usecase/home_use_case.dart'; import 'package:grocery_app/domain/usecase/location_use_case.dart'; import 'package:grocery_app/domain/usecase/logout_usecase.dart'; import 'package:grocery_app/domain/usecase/offer_usecase.dart'; import 'package:grocery_app/domain/usecase/order_create_usercase.dart'; import 'package:grocery_app/domain/usecase/order_usercase.dart'; import 'core/api_provider.dart'; import 'domain/usecase/upate_order_usecase.dart'; final sl = GetIt.instance; Future<void> init() async { //data source sl.registerLazySingleton<AuthDataSource>(() => AuthDataSourceImpl(sl())); sl.registerLazySingleton<AuthLocalDataSource>( () => AuthLocalDataSourceImpl(sl())); sl.registerLazySingleton<CategoryRemoteDataSource>( () => CategoryRemoteDataSourceImpl(sl())); sl.registerLazySingleton<ProductRemoteDataUseCase>( () => ProductRemoteDataUseCaseImpl(sl())); sl.registerLazySingleton<OfferRemoteDataSource>( () => OfferRemoteDataSourceImpl(sl())); sl.registerLazySingleton<HomeRemoteDataSource>( () => HomeRemoteDataSourceImpl(sl())); //repository sl.registerLazySingleton<AuthDataRepository>( () => AuthDataRepositoryImpl(sl())); sl.registerLazySingleton<AuthLocalRepository>(() => AuthLocalRepositoryImpl( sl(), )); sl.registerLazySingleton<CategoryDataRepository>( () => CategoryDataRepositoryImpl(sl())); sl.registerLazySingleton<ProductRepository>( () => ProductRepositoryImpl(sl())); sl.registerLazySingleton<HomeRepository>(() => HomeRepositoryImpl(sl())); //usecase sl.registerLazySingleton<OfferUserCase>(() => OfferUserCase(sl())); sl.registerLazySingleton<HomeUseCase>(() => HomeUseCase(sl())); sl.registerLazySingleton<GetProductUseCase>(() => GetProductUseCase(sl())); sl.registerLazySingleton<OrderStaffUseCase>(() => OrderStaffUseCase(sl())); sl.registerLazySingleton<ProductExpandUseCase>( () => ProductExpandUseCase(sl())); sl.registerLazySingleton<LogoutUseCase>(() => LogoutUseCase(sl())); sl.registerLazySingleton<AddCartUseCase>(() => AddCartUseCase(sl())); sl.registerLazySingleton<GetCartUseCase>(() => GetCartUseCase(sl())); sl.registerLazySingleton<DeleteCartUseCase>(() => DeleteCartUseCase(sl())); sl.registerLazySingleton<OrderCreateUseCase>(() => OrderCreateUseCase(sl())); sl.registerLazySingleton<OrderUseCase>(() => OrderUseCase(sl())); sl.registerLazySingleton<UpdateOrderUseCase>(() => UpdateOrderUseCase(sl())); sl.registerLazySingleton<SaveLocationUseCase>( () => SaveLocationUseCase(sl())); sl.registerLazySingleton<GetLocalLocationUseCase>( () => GetLocalLocationUseCase(sl())); sl.registerLazySingleton<GetAllLocationsUseCase>( () => GetAllLocationsUseCase(sl())); sl.registerLazySingleton<GetNearestLocation>(() => GetNearestLocation(sl())); sl.registerLazySingleton<GetUserUseCaseAddress>( () => GetUserUseCaseAddress(sl())); sl.registerLazySingleton<AddAddressUseCase>(() => AddAddressUseCase(sl())); sl.registerLazySingleton<AddFavUseCase>(() => AddFavUseCase(sl())); sl.registerLazySingleton<GetFavUseCase>(() => GetFavUseCase(sl())); //core sl.registerLazySingleton<ApiProvider>(() => ApiProvider()); await GetStorage.init(); // sl.registerSingleton(NavigationBarMoksha(sl())); // sl.registerLazySingleton<ConnectionInfo>(() => ConnectionInfoImpl(sl())); // sl.registerLazySingleton(() => InternetConnectionChecker()); sl.registerLazySingleton(() => GetStorage()); }
/* * Engineering Ingegneria Informatica S.p.A. * * Copyright (C) 2023 Regione Emilia-Romagna * <p/> * This program is free software: you can redistribute it and/or modify it under the terms of * the GNU Affero General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * <p/> * 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 Affero General Public License for more details. * <p/> * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. */ package it.eng.parer.web.action; import it.eng.parer.jboss.timer.service.JbossTimerEjb; import it.eng.parer.job.utils.JobConstants; import it.eng.parer.slite.gen.Application; import it.eng.parer.slite.gen.action.GestioneJobAbstractAction; import it.eng.parer.slite.gen.form.GestioneJobForm.GestioneJobRicercaFiltri; import it.eng.parer.slite.gen.form.MonitoraggioForm; import it.eng.parer.slite.gen.viewbean.LogVVisLastSchedRowBean; import it.eng.parer.web.ejb.GestioneJobEjb; import it.eng.parer.web.helper.ConfigurationHelper; import it.eng.parer.web.helper.MonitoraggioHelper; import it.eng.parer.web.util.ComboGetter; import it.eng.parer.web.util.WebConstants; import it.eng.parer.ws.utils.CostantiDB; import it.eng.spagoCore.error.EMFError; import it.eng.spagoLite.db.base.BaseTableInterface; import it.eng.spagoLite.db.base.row.BaseRow; import it.eng.spagoLite.db.base.table.BaseTable; import it.eng.spagoLite.db.oracle.decode.DecodeMap; import it.eng.spagoLite.form.base.BaseForm; import it.eng.spagoLite.form.fields.SingleValueField; import it.eng.spagoLite.form.fields.impl.Button; import it.eng.spagoLite.form.fields.impl.CheckBox; import it.eng.spagoLite.form.fields.impl.Input; import it.eng.spagoLite.message.Message; import it.eng.spagoLite.message.Message.MessageLevel; import it.eng.spagoLite.message.MessageBox.ViewMode; import it.eng.spagoLite.security.Secure; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Set; import javax.ejb.EJB; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Gilioli_P */ public class GestioneJobAction extends GestioneJobAbstractAction { public static final String FROM_SCHEDULAZIONI_JOB = "fromSchedulazioniJob"; private final Logger LOG = LoggerFactory.getLogger(GestioneJobAction.class.getName()); @EJB(mappedName = "java:app/Parer-ejb/MonitoraggioHelper") private MonitoraggioHelper monitoraggioHelper; @EJB(mappedName = "java:app/JbossTimerWrapper-ejb/JbossTimerEjb") private JbossTimerEjb jbossTimerEjb; @EJB(mappedName = "java:app/Parer-ejb/ConfigurationHelper") private ConfigurationHelper configHelper; @EJB(mappedName = "java:app/Parer-ejb/GestioneJobEjb") private GestioneJobEjb gestioneJobEjb; private enum OPERAZIONE { START("lancio il timer"), ESECUZIONE_SINGOLA("esecuzione singola"), STOP("stop"); protected String desc; OPERAZIONE(String desc) { this.desc = desc; } public String description() { return desc; } }; /** * Returns the activation date of job otherwise <code>null</code> * * @param jobName * the job name * * @return * * @throws EMFError */ private Timestamp getActivationDateJob(String jobName) throws EMFError { Timestamp res = null; LogVVisLastSchedRowBean rb = monitoraggioHelper.getLogVVisLastSchedRowBean(jobName); if (rb.getFlJobAttivo() != null) { if (rb.getFlJobAttivo().equals("1")) { res = rb.getDtRegLogJobIni(); } } return res; } @Override public String getControllerName() { return Application.Actions.GESTIONE_JOB; } @Override protected String getDefaultPublsherName() { return Application.Publisher.GESTIONE_JOB; } @Secure(action = "Menu.Amministrazione.GestioneJob") @Override public void initOnClick() throws EMFError { getUser().getMenu().reset(); getUser().getMenu().select("Menu.Amministrazione.GestioneJob"); // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione elenchi"> Timestamp dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS.name()); StatoJob creazioneElenchi = new StatoJob(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS.name(), getForm().getCreazioneElenchi().getFl_data_accurata(), getForm().getCreazioneElenchi().getStartCreazioneElenchi(), getForm().getCreazioneElenchi().getStartOnceCreazioneElenchi(), getForm().getCreazioneElenchi().getStopCreazioneElenchi(), getForm().getCreazioneElenchi().getDt_prossima_attivazione(), getForm().getCreazioneElenchi().getAttivo(), getForm().getCreazioneElenchi().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneElenchi); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione indici"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS.name()); StatoJob creazioneIndici = new StatoJob(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS.name(), getForm().getCreazioneIndici().getFl_data_accurata(), getForm().getCreazioneIndici().getStartCreazioneIndici(), getForm().getCreazioneIndici().getStartOnceCreazioneIndici(), getForm().getCreazioneIndici().getStopCreazioneIndici(), getForm().getCreazioneIndici().getDt_prossima_attivazione(), getForm().getCreazioneIndici().getAttivo(), getForm().getCreazioneIndici().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneIndici); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Verifica firme"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.VERIFICA_FIRME_A_DATA_VERS.name()); StatoJob verificaFirme = new StatoJob(JobConstants.JobEnum.VERIFICA_FIRME_A_DATA_VERS.name(), getForm().getVerificaFirme().getFl_data_accurata(), getForm().getVerificaFirme().getStartVerificaFirme(), getForm().getVerificaFirme().getStartOnceVerificaFirme(), getForm().getVerificaFirme().getStopVerificaFirme(), getForm().getVerificaFirme().getDt_prossima_attivazione(), getForm().getVerificaFirme().getAttivo(), getForm().getVerificaFirme().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(verificaFirme); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Coda indici aip da elaborare"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PRODUCER_CODA_INDICI_AIP_DA_ELAB.name()); StatoJob codaIndiciAipDaElab = new StatoJob(JobConstants.JobEnum.PRODUCER_CODA_INDICI_AIP_DA_ELAB.name(), getForm().getCodaIndiciAipDaElab().getFl_data_accurata(), getForm().getCodaIndiciAipDaElab().getStartCodaIndiciAipDaElab(), getForm().getCodaIndiciAipDaElab().getStartOnceCodaIndiciAipDaElab(), getForm().getCodaIndiciAipDaElab().getStopCodaIndiciAipDaElab(), getForm().getCodaIndiciAipDaElab().getDt_prossima_attivazione(), getForm().getVerificaFirme().getAttivo(), getForm().getCodaIndiciAipDaElab().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(codaIndiciAipDaElab); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Calcolo contenuto Sacer"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CALCOLO_CONTENUTO_SACER.name()); StatoJob calcoloContenuto = new StatoJob(JobConstants.JobEnum.CALCOLO_CONTENUTO_SACER.name(), getForm().getCalcoloContenutoSacer().getFl_data_accurata(), getForm().getCalcoloContenutoSacer().getStartCalcoloContenutoSacer(), getForm().getCalcoloContenutoSacer().getStartOnceCalcoloContenutoSacer(), getForm().getCalcoloContenutoSacer().getStopCalcoloContenutoSacer(), getForm().getCalcoloContenutoSacer().getDt_prossima_attivazione(), getForm().getCalcoloContenutoSacer().getAttivo(), getForm().getCalcoloContenutoSacer().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(calcoloContenuto); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Calcolo consistenza"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CALCOLO_CONSISTENZA.name()); StatoJob calcoloConsistenza = new StatoJob(JobConstants.JobEnum.CALCOLO_CONSISTENZA.name(), getForm().getCalcoloConsistenza().getFl_data_accurata(), getForm().getCalcoloConsistenza().getStartCalcoloConsistenza(), getForm().getCalcoloConsistenza().getStartOnceCalcoloConsistenza(), getForm().getCalcoloConsistenza().getStopCalcoloConsistenza(), getForm().getCalcoloConsistenza().getDt_prossima_attivazione(), getForm().getCalcoloConsistenza().getAttivo(), getForm().getCalcoloConsistenza().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(calcoloConsistenza); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Allineamento organizzazioni"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.ALLINEAMENTO_ORGANIZZAZIONI.name()); StatoJob allineamentoOrganizzazioni = new StatoJob(JobConstants.JobEnum.ALLINEAMENTO_ORGANIZZAZIONI.name(), getForm().getAllineamentoOrganizzazioni().getFl_data_accurata(), getForm().getAllineamentoOrganizzazioni().getStartAllineamentoOrganizzazioni(), getForm().getAllineamentoOrganizzazioni().getStartOnceAllineamentoOrganizzazioni(), getForm().getAllineamentoOrganizzazioni().getStopAllineamentoOrganizzazioni(), getForm().getAllineamentoOrganizzazioni().getDt_prossima_attivazione(), getForm().getAllineamentoOrganizzazioni().getAttivo(), getForm().getAllineamentoOrganizzazioni().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(allineamentoOrganizzazioni); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Aggiorna stato archiviazione"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.AGGIORNA_STATO_ARCHIVIAZIONE.name()); StatoJob aggiornaStatoArk = new StatoJob(JobConstants.JobEnum.AGGIORNA_STATO_ARCHIVIAZIONE.name(), getForm().getAggiornamentoStatoArk().getFl_data_accurata(), getForm().getAggiornamentoStatoArk().getStartAggiornamentoStatoArk(), getForm().getAggiornamentoStatoArk().getStartOnceAggiornamentoStatoArk(), getForm().getAggiornamentoStatoArk().getStopAggiornamentoStatoArk(), getForm().getAggiornamentoStatoArk().getDt_prossima_attivazione(), getForm().getAggiornamentoStatoArk().getAttivo(), getForm().getAggiornamentoStatoArk().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(aggiornaStatoArk); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Elabora sessioni recupero archiviazione"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.ELABORA_SESSIONI_RECUPERO.name()); StatoJob elaboraSessioniRecupero = new StatoJob(JobConstants.JobEnum.ELABORA_SESSIONI_RECUPERO.name(), getForm().getElaboraSessioniRecupero().getFl_data_accurata(), getForm().getElaboraSessioniRecupero().getStartElaboraSessioniRecupero(), getForm().getElaboraSessioniRecupero().getStartOnceElaboraSessioniRecupero(), getForm().getElaboraSessioniRecupero().getStopElaboraSessioniRecupero(), getForm().getElaboraSessioniRecupero().getDt_prossima_attivazione(), getForm().getElaboraSessioniRecupero().getAttivo(), getForm().getElaboraSessioniRecupero().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(elaboraSessioniRecupero); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Registra schedulazione TPI"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.REGISTRA_SCHEDULAZIONI_JOB_TPI.name()); StatoJob registraSchedTpi = new StatoJob(JobConstants.JobEnum.REGISTRA_SCHEDULAZIONI_JOB_TPI.name(), getForm().getRegistraSchedTpi().getFl_data_accurata(), getForm().getRegistraSchedTpi().getStartRegistraSchedTpi(), getForm().getRegistraSchedTpi().getStartOnceRegistraSchedTpi(), getForm().getRegistraSchedTpi().getStopRegistraSchedTpi(), getForm().getRegistraSchedTpi().getDt_prossima_attivazione(), getForm().getRegistraSchedTpi().getAttivo(), getForm().getRegistraSchedTpi().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(registraSchedTpi); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione indici AIP"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_INDICE_AIP.name()); StatoJob creazioneIndiciAip = new StatoJob(JobConstants.JobEnum.CREAZIONE_INDICE_AIP.name(), getForm().getCreazioneIndiciAip().getFl_data_accurata(), getForm().getCreazioneIndiciAip().getStartCreazioneIndiciAip(), getForm().getCreazioneIndiciAip().getStartOnceCreazioneIndiciAip(), getForm().getCreazioneIndiciAip().getStopCreazioneIndiciAip(), getForm().getCreazioneIndiciAip().getDt_prossima_attivazione(), getForm().getCreazioneIndiciAip().getAttivo(), getForm().getCreazioneIndiciAip().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneIndiciAip); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Verifica massiva versamenti falliti"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.VERIFICA_MASSIVA_VERS_FALLITI.name()); StatoJob verficaMassivaVersamentiFalliti = new StatoJob( JobConstants.JobEnum.VERIFICA_MASSIVA_VERS_FALLITI.name(), getForm().getVerificaMassivaVersamentiFalliti().getFl_data_accurata(), getForm().getVerificaMassivaVersamentiFalliti().getStartVerificaMassivaVersamentiFalliti(), getForm().getVerificaMassivaVersamentiFalliti().getStartOnceVerificaMassivaVersamentiFalliti(), getForm().getVerificaMassivaVersamentiFalliti().getStopVerificaMassivaVersamentiFalliti(), getForm().getVerificaMassivaVersamentiFalliti().getDt_prossima_attivazione(), getForm().getVerificaMassivaVersamentiFalliti().getAttivo(), getForm().getVerificaMassivaVersamentiFalliti().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(verficaMassivaVersamentiFalliti); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Verifica periodo registro"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_REGISTRO.name()); StatoJob verificaPeriodoRegistro = new StatoJob(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_REGISTRO.name(), getForm().getVerificaPeriodoRegistro().getFl_data_accurata(), getForm().getVerificaPeriodoRegistro().getStartVerificaPeriodoRegistro(), getForm().getVerificaPeriodoRegistro().getStartOnceVerificaPeriodoRegistro(), getForm().getVerificaPeriodoRegistro().getStopVerificaPeriodoRegistro(), getForm().getVerificaPeriodoRegistro().getDt_prossima_attivazione(), getForm().getVerificaPeriodoRegistro().getAttivo(), getForm().getVerificaPeriodoRegistro().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(verificaPeriodoRegistro); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione automatica serie"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_AUTOMATICA_SERIE.name()); StatoJob creazioneAutomaticaSerie = new StatoJob(JobConstants.JobEnum.CREAZIONE_AUTOMATICA_SERIE.name(), getForm().getCreazioneAutomaticaSerie().getFl_data_accurata(), getForm().getCreazioneAutomaticaSerie().getStartCreazioneAutomaticaSerie(), getForm().getCreazioneAutomaticaSerie().getStartOnceCreazioneAutomaticaSerie(), getForm().getCreazioneAutomaticaSerie().getStopCreazioneAutomaticaSerie(), getForm().getCreazioneAutomaticaSerie().getDt_prossima_attivazione(), getForm().getCreazioneAutomaticaSerie().getAttivo(), getForm().getCreazioneAutomaticaSerie().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneAutomaticaSerie); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione indici AIP serie UD"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_SERIE_UD.name()); StatoJob creazioneIndiciAipSerieUd = new StatoJob(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_SERIE_UD.name(), getForm().getCreazioneIndiciAipSerieUd().getFl_data_accurata(), getForm().getCreazioneIndiciAipSerieUd().getStartCreazioneIndiciAipSerieUd(), getForm().getCreazioneIndiciAipSerieUd().getStartOnceCreazioneIndiciAipSerieUd(), getForm().getCreazioneIndiciAipSerieUd().getStopCreazioneIndiciAipSerieUd(), getForm().getCreazioneIndiciAipSerieUd().getDt_prossima_attivazione(), getForm().getCreazioneIndiciAipSerieUd().getAttivo(), getForm().getCreazioneIndiciAipSerieUd().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneIndiciAipSerieUd); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Generazione automatica contenuto effettivo // serie"> dataAttivazioneJob = getActivationDateJob( JobConstants.JobEnum.GENERAZIONE_AUTOMATICA_CONTENUTO_EFFETTIVO.name()); StatoJob generazioneAutomaticaEffettivoSerie = new StatoJob( JobConstants.JobEnum.GENERAZIONE_AUTOMATICA_CONTENUTO_EFFETTIVO.name(), getForm().getGenerazioneAutomaticaEffettivoSerie().getFl_data_accurata(), getForm().getGenerazioneAutomaticaEffettivoSerie().getStartGenerazioneAutomaticaEffettivo(), getForm().getGenerazioneAutomaticaEffettivoSerie().getStartOnceGenerazioneAutomaticaEffettivo(), getForm().getGenerazioneAutomaticaEffettivoSerie().getStopGenerazioneAutomaticaEffettivo(), getForm().getGenerazioneAutomaticaEffettivoSerie().getDt_prossima_attivazione(), getForm().getGenerazioneAutomaticaEffettivoSerie().getAttivo(), getForm().getGenerazioneAutomaticaEffettivoSerie().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(generazioneAutomaticaEffettivoSerie); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Evasione richieste annullamento versamenti"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.EVASIONE_RICH_ANNUL_VERS.name()); StatoJob evasioneRichiesteAnnullamentoVersamenti = new StatoJob( JobConstants.JobEnum.EVASIONE_RICH_ANNUL_VERS.name(), getForm().getEvasioneRichiesteAnnullamentoVersamenti().getFl_data_accurata(), getForm().getEvasioneRichiesteAnnullamentoVersamenti().getStartEvasioneRichiesteAnnulVers(), getForm().getEvasioneRichiesteAnnullamentoVersamenti().getStartOnceEvasioneRichiesteAnnulVers(), getForm().getEvasioneRichiesteAnnullamentoVersamenti().getStopEvasioneRichiesteAnnulVers(), getForm().getEvasioneRichiesteAnnullamentoVersamenti().getDt_prossima_attivazione(), getForm().getEvasioneRichiesteAnnullamentoVersamenti().getAttivo(), getForm().getEvasioneRichiesteAnnullamentoVersamenti().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(evasioneRichiesteAnnullamentoVersamenti); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per l'inizializzazione dei LOG"> String nomeApplicazione = configHelper.getValoreParamApplicByApplic(CostantiDB.ParametroAppl.NM_APPLIC); dataAttivazioneJob = getActivationDateJob( it.eng.parer.sacerlog.job.Constants.NomiJob.INIZIALIZZAZIONE_LOG.name() + "_" + nomeApplicazione); StatoJob inizializzazioneLog = new StatoJob( it.eng.parer.sacerlog.job.Constants.NomiJob.INIZIALIZZAZIONE_LOG.name(), getForm().getInizializzazioneLog().getFl_data_accurata(), null, getForm().getInizializzazioneLog().getStartOnceInizializzazioneLog(), null, getForm().getInizializzazioneLog().getDt_prossima_attivazione(), getForm().getInizializzazioneLog().getAttivo(), getForm().getInizializzazioneLog().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(inizializzazioneLog); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per l'allineamento dei LOG"> dataAttivazioneJob = getActivationDateJob( it.eng.parer.sacerlog.job.Constants.NomiJob.ALLINEAMENTO_LOG.name() + "_" + nomeApplicazione); StatoJob allineamentoLog = new StatoJob(it.eng.parer.sacerlog.job.Constants.NomiJob.ALLINEAMENTO_LOG.name(), getForm().getAllineamentoLog().getFl_data_accurata(), getForm().getAllineamentoLog().getStartAllineamentoLog(), getForm().getAllineamentoLog().getStartOnceAllineamentoLog(), getForm().getAllineamentoLog().getStopAllineamentoLog(), getForm().getAllineamentoLog().getDt_prossima_attivazione(), getForm().getAllineamentoLog().getAttivo(), getForm().getAllineamentoLog().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(allineamentoLog); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Controllo automatico contenuto effettivo // serie"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CONTROLLO_AUTOMATICO_CONTENUTO_EFFETTIVO.name()); StatoJob controlloAutomaticoEffettivoSerie = new StatoJob( JobConstants.JobEnum.CONTROLLO_AUTOMATICO_CONTENUTO_EFFETTIVO.name(), getForm().getControlloAutomaticoEffettivoSerie().getFl_data_accurata(), getForm().getControlloAutomaticoEffettivoSerie().getStartControlloAutomaticoEffettivo(), getForm().getControlloAutomaticoEffettivoSerie().getStartOnceControlloAutomaticoEffettivo(), getForm().getControlloAutomaticoEffettivoSerie().getStopControlloAutomaticoEffettivo(), getForm().getControlloAutomaticoEffettivoSerie().getDt_prossima_attivazione(), getForm().getControlloAutomaticoEffettivoSerie().getAttivo(), getForm().getControlloAutomaticoEffettivoSerie().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(controlloAutomaticoEffettivoSerie); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per calcolo struttura"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CALCOLA_STRUTTURA_JOB.name()); StatoJob calcoloStruttura = new StatoJob(JobConstants.JobEnum.CALCOLA_STRUTTURA_JOB.name(), getForm().getCalcoloStruttura().getFl_data_accurata(), getForm().getCalcoloStruttura().getStartCalcoloStruttura(), getForm().getCalcoloStruttura().getStartOnceCalcoloStruttura(), getForm().getCalcoloStruttura().getStopCalcoloStruttura(), getForm().getCalcoloStruttura().getDt_prossima_attivazione(), getForm().getCalcoloStruttura().getAttivo(), getForm().getCalcoloStruttura().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(calcoloStruttura); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per evasione richieste di restituzione archivio"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.EVASIONE_RICH_REST_ARCH.name()); StatoJob evasioneRichiesteRestArch = new StatoJob(JobConstants.JobEnum.EVASIONE_RICH_REST_ARCH.name(), getForm().getEvasioneRichiesteRestituzioneArchivio().getFl_data_accurata(), getForm().getEvasioneRichiesteRestituzioneArchivio().getStartEvasioneRichiesteRestArch(), getForm().getEvasioneRichiesteRestituzioneArchivio().getStartOnceEvasioneRichiesteRestArch(), getForm().getEvasioneRichiesteRestituzioneArchivio().getStopEvasioneRichiesteRestArch(), getForm().getEvasioneRichiesteRestituzioneArchivio().getDt_prossima_attivazione(), getForm().getEvasioneRichiesteRestituzioneArchivio().getAttivo(), getForm().getEvasioneRichiesteRestituzioneArchivio().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(evasioneRichiesteRestArch); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione Elenchi indici AIP"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_UD.name()); StatoJob creazioneElenchiIndiciAipUd = new StatoJob(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_UD.name(), getForm().getCreazioneElenchiIndiciAip().getFl_data_accurata(), getForm().getCreazioneElenchiIndiciAip().getStartCreazioneElenchiIndiciAip(), getForm().getCreazioneElenchiIndiciAip().getStartOnceCreazioneElenchiIndiciAip(), getForm().getCreazioneElenchiIndiciAip().getStopCreazioneElenchiIndiciAip(), getForm().getCreazioneElenchiIndiciAip().getDt_prossima_attivazione(), getForm().getCreazioneElenchiIndiciAip().getAttivo(), getForm().getCreazioneElenchiIndiciAip().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneElenchiIndiciAipUd); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Allineamento enti convenzionati"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.ALLINEA_ENTI_CONVENZIONATI.name()); StatoJob allineaEntiConvenzionati = new StatoJob(JobConstants.JobEnum.ALLINEA_ENTI_CONVENZIONATI.name(), getForm().getAllineaEntiConvenzionati().getFl_data_accurata(), getForm().getAllineaEntiConvenzionati().getStartAllineaEntiConvenzionati(), getForm().getAllineaEntiConvenzionati().getStartOnceAllineaEntiConvenzionati(), getForm().getAllineaEntiConvenzionati().getStopAllineaEntiConvenzionati(), getForm().getAllineaEntiConvenzionati().getDt_prossima_attivazione(), getForm().getAllineaEntiConvenzionati().getAttivo(), getForm().getAllineaEntiConvenzionati().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(allineaEntiConvenzionati); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Calcolo contenuto fascicoli"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CALCOLO_CONTENUTO_FASCICOLI.name()); StatoJob calcoloContenutoFascicoli = new StatoJob(JobConstants.JobEnum.CALCOLO_CONTENUTO_FASCICOLI.name(), getForm().getCalcoloContenutoFascicoli().getFl_data_accurata(), getForm().getCalcoloContenutoFascicoli().getStartCalcoloContenutoFascicoli(), getForm().getCalcoloContenutoFascicoli().getStartOnceCalcoloContenutoFascicoli(), getForm().getCalcoloContenutoFascicoli().getStopCalcoloContenutoFascicoli(), getForm().getCalcoloContenutoFascicoli().getDt_prossima_attivazione(), getForm().getCalcoloContenutoFascicoli().getAttivo(), getForm().getCalcoloContenutoFascicoli().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(calcoloContenutoFascicoli); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Verifica Periodo tipo fascicolo"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_TIPO_FASC.name()); StatoJob verificaPeriodoTipoFasc = new StatoJob(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_TIPO_FASC.name(), getForm().getVerificaPeriodoTipoFascicolo().getFl_data_accurata(), getForm().getVerificaPeriodoTipoFascicolo().getStartVerificaPeriodoTipoFasc(), getForm().getVerificaPeriodoTipoFascicolo().getStartOnceVerificaPeriodoTipoFasc(), getForm().getVerificaPeriodoTipoFascicolo().getStopVerificaPeriodoTipoFasc(), getForm().getVerificaPeriodoTipoFascicolo().getDt_prossima_attivazione(), getForm().getVerificaPeriodoTipoFascicolo().getAttivo(), getForm().getVerificaPeriodoTipoFascicolo().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(verificaPeriodoTipoFasc); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione elenchi versamento fascicoli"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS_FASCICOLI.name()); StatoJob creazioneElenchiVersFascicoli = new StatoJob( JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS_FASCICOLI.name(), getForm().getCreazioneElenchiVersFascicoli().getFl_data_accurata(), getForm().getCreazioneElenchiVersFascicoli().getStartCreazioneElenchiVersFascicoli(), getForm().getCreazioneElenchiVersFascicoli().getStartOnceCreazioneElenchiVersFascicoli(), getForm().getCreazioneElenchiVersFascicoli().getStopCreazioneElenchiVersFascicoli(), getForm().getCreazioneElenchiVersFascicoli().getDt_prossima_attivazione(), getForm().getCreazioneElenchiVersFascicoli().getAttivo(), getForm().getCreazioneElenchiVersFascicoli().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneElenchiVersFascicoli); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione indici versamento fascicoli"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS_FASC.name()); StatoJob creazioneIndiciVersFascicoli = new StatoJob( JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS_FASC.name(), getForm().getCreazioneIndiciVersFascicoli().getFl_data_accurata(), getForm().getCreazioneIndiciVersFascicoli().getStartCreazioneIndiciVersFascicoli(), getForm().getCreazioneIndiciVersFascicoli().getStartOnceCreazioneIndiciVersFascicoli(), getForm().getCreazioneIndiciVersFascicoli().getStopCreazioneIndiciVersFascicoli(), getForm().getCreazioneIndiciVersFascicoli().getDt_prossima_attivazione(), getForm().getCreazioneIndiciVersFascicoli().getAttivo(), getForm().getCreazioneIndiciVersFascicoli().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneIndiciVersFascicoli); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Validazione fascicoli"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.VALIDAZIONE_FASCICOLI.name()); StatoJob validazioneFascicoli = new StatoJob(JobConstants.JobEnum.VALIDAZIONE_FASCICOLI.name(), getForm().getValidazioneFascicoli().getFl_data_accurata(), getForm().getValidazioneFascicoli().getStartValidazioneFascicoli(), getForm().getValidazioneFascicoli().getStartOnceValidazioneFascicoli(), getForm().getValidazioneFascicoli().getStopValidazioneFascicoli(), getForm().getValidazioneFascicoli().getDt_prossima_attivazione(), getForm().getValidazioneFascicoli().getAttivo(), getForm().getValidazioneFascicoli().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(validazioneFascicoli); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione indici AIP fascicoli"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_FASC.name()); StatoJob creazioneIndiciAipFasc = new StatoJob(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_FASC.name(), getForm().getCreazioneIndiciAipFascicoli().getFl_data_accurata(), getForm().getCreazioneIndiciAipFascicoli().getStartCreazioneIndiciAipFasc(), getForm().getCreazioneIndiciAipFascicoli().getStartOnceCreazioneIndiciAipFasc(), getForm().getCreazioneIndiciAipFascicoli().getStopCreazioneIndiciAipFasc(), getForm().getCreazioneIndiciAipFascicoli().getDt_prossima_attivazione(), getForm().getCreazioneIndiciAipFascicoli().getAttivo(), getForm().getCreazioneIndiciAipFascicoli().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneIndiciAipFasc); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Creazione Elenchi indici AIP fascicoli"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_FASC.name()); StatoJob creazioneElenchiIndiciAipFasc = new StatoJob( JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_FASC.name(), getForm().getCreazioneElenchiIndiciAipFascicoli().getFl_data_accurata(), getForm().getCreazioneElenchiIndiciAipFascicoli().getStartCreazioneElenchiIndiciAipFasc(), getForm().getCreazioneElenchiIndiciAipFascicoli().getStartOnceCreazioneElenchiIndiciAipFasc(), getForm().getCreazioneElenchiIndiciAipFascicoli().getStopCreazioneElenchiIndiciAipFasc(), getForm().getCreazioneElenchiIndiciAipFascicoli().getDt_prossima_attivazione(), getForm().getCreazioneElenchiIndiciAipFascicoli().getAttivo(), getForm().getCreazioneElenchiIndiciAipFascicoli().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(creazioneElenchiIndiciAipFasc); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Preparazione partizione da migrare 1"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_1.name()); StatoJob preparazionePartizioneDaMigrare1 = new StatoJob( JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_1.name(), getForm().getPreparazionePartizioneDaMigrare1().getFl_data_accurata(), getForm().getPreparazionePartizioneDaMigrare1().getStartPreparazionePartizioneDaMigrare1(), getForm().getPreparazionePartizioneDaMigrare1().getStartOncePreparazionePartizioneDaMigrare1(), getForm().getPreparazionePartizioneDaMigrare1().getStopPreparazionePartizioneDaMigrare1(), getForm().getPreparazionePartizioneDaMigrare1().getDt_prossima_attivazione(), getForm().getPreparazionePartizioneDaMigrare1().getAttivo(), getForm().getPreparazionePartizioneDaMigrare1().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(preparazionePartizioneDaMigrare1); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Preparazione partizione da migrare 2"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_2.name()); StatoJob preparazionePartizioneDaMigrare2 = new StatoJob( JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_2.name(), getForm().getPreparazionePartizioneDaMigrare2().getFl_data_accurata(), getForm().getPreparazionePartizioneDaMigrare2().getStartPreparazionePartizioneDaMigrare2(), getForm().getPreparazionePartizioneDaMigrare2().getStartOncePreparazionePartizioneDaMigrare2(), getForm().getPreparazionePartizioneDaMigrare2().getStopPreparazionePartizioneDaMigrare2(), getForm().getPreparazionePartizioneDaMigrare2().getDt_prossima_attivazione(), getForm().getPreparazionePartizioneDaMigrare2().getAttivo(), getForm().getPreparazionePartizioneDaMigrare2().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(preparazionePartizioneDaMigrare2); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Preparazione partizione da migrare 3"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_3.name()); StatoJob preparazionePartizioneDaMigrare3 = new StatoJob( JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_3.name(), getForm().getPreparazionePartizioneDaMigrare3().getFl_data_accurata(), getForm().getPreparazionePartizioneDaMigrare3().getStartPreparazionePartizioneDaMigrare3(), getForm().getPreparazionePartizioneDaMigrare3().getStartOncePreparazionePartizioneDaMigrare3(), getForm().getPreparazionePartizioneDaMigrare3().getStopPreparazionePartizioneDaMigrare3(), getForm().getPreparazionePartizioneDaMigrare3().getDt_prossima_attivazione(), getForm().getPreparazionePartizioneDaMigrare3().getAttivo(), getForm().getPreparazionePartizioneDaMigrare3().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(preparazionePartizioneDaMigrare3); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Preparazione partizione da migrare 4"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_4.name()); StatoJob preparazionePartizioneDaMigrare4 = new StatoJob( JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_4.name(), getForm().getPreparazionePartizioneDaMigrare4().getFl_data_accurata(), getForm().getPreparazionePartizioneDaMigrare4().getStartPreparazionePartizioneDaMigrare4(), getForm().getPreparazionePartizioneDaMigrare4().getStartOncePreparazionePartizioneDaMigrare4(), getForm().getPreparazionePartizioneDaMigrare4().getStopPreparazionePartizioneDaMigrare4(), getForm().getPreparazionePartizioneDaMigrare4().getDt_prossima_attivazione(), getForm().getPreparazionePartizioneDaMigrare4().getAttivo(), getForm().getPreparazionePartizioneDaMigrare4().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(preparazionePartizioneDaMigrare4); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per produzione coda da migrare 1"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_1.name()); StatoJob producerCodaDaMigrare1 = new StatoJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_1.name(), getForm().getProducerCodaDaMigrare1().getFl_data_accurata(), getForm().getProducerCodaDaMigrare1().getStartProducerCodaDaMigrare1(), getForm().getProducerCodaDaMigrare1().getStartOnceProducerCodaDaMigrare1(), getForm().getProducerCodaDaMigrare1().getStopProducerCodaDaMigrare1(), getForm().getProducerCodaDaMigrare1().getDt_prossima_attivazione(), getForm().getProducerCodaDaMigrare1().getAttivo(), getForm().getProducerCodaDaMigrare1().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(producerCodaDaMigrare1); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per produzione coda da migrare 2"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_2.name()); StatoJob producerCodaDaMigrare2 = new StatoJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_2.name(), getForm().getProducerCodaDaMigrare2().getFl_data_accurata(), getForm().getProducerCodaDaMigrare2().getStartProducerCodaDaMigrare2(), getForm().getProducerCodaDaMigrare2().getStartOnceProducerCodaDaMigrare2(), getForm().getProducerCodaDaMigrare2().getStopProducerCodaDaMigrare2(), getForm().getProducerCodaDaMigrare2().getDt_prossima_attivazione(), getForm().getProducerCodaDaMigrare2().getAttivo(), getForm().getProducerCodaDaMigrare2().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(producerCodaDaMigrare2); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per produzione coda da migrare 3"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_3.name()); StatoJob producerCodaDaMigrare3 = new StatoJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_3.name(), getForm().getProducerCodaDaMigrare3().getFl_data_accurata(), getForm().getProducerCodaDaMigrare3().getStartProducerCodaDaMigrare3(), getForm().getProducerCodaDaMigrare3().getStartOnceProducerCodaDaMigrare3(), getForm().getProducerCodaDaMigrare3().getStopProducerCodaDaMigrare3(), getForm().getProducerCodaDaMigrare3().getDt_prossima_attivazione(), getForm().getProducerCodaDaMigrare3().getAttivo(), getForm().getProducerCodaDaMigrare3().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(producerCodaDaMigrare3); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per produzione coda da migrare 4"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_4.name()); StatoJob producerCodaDaMigrare4 = new StatoJob(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_4.name(), getForm().getProducerCodaDaMigrare4().getFl_data_accurata(), getForm().getProducerCodaDaMigrare4().getStartProducerCodaDaMigrare4(), getForm().getProducerCodaDaMigrare4().getStartOnceProducerCodaDaMigrare4(), getForm().getProducerCodaDaMigrare4().getStopProducerCodaDaMigrare4(), getForm().getProducerCodaDaMigrare4().getDt_prossima_attivazione(), getForm().getProducerCodaDaMigrare4().getAttivo(), getForm().getProducerCodaDaMigrare4().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(producerCodaDaMigrare4); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per verifica migrazione subpartizione"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.VERIFICA_MIGRAZIONE_SUBPARTIZIONE.name()); StatoJob verificaMigrazioneSubpartizione = new StatoJob( JobConstants.JobEnum.VERIFICA_MIGRAZIONE_SUBPARTIZIONE.name(), getForm().getVerificaMigrazioneSubpartizione().getFl_data_accurata(), getForm().getVerificaMigrazioneSubpartizione().getStartVerificaMigrazioneSubpartizione(), getForm().getVerificaMigrazioneSubpartizione().getStartOnceVerificaMigrazioneSubpartizione(), getForm().getVerificaMigrazioneSubpartizione().getStopVerificaMigrazioneSubpartizione(), getForm().getVerificaMigrazioneSubpartizione().getDt_prossima_attivazione(), getForm().getVerificaMigrazioneSubpartizione().getAttivo(), getForm().getVerificaMigrazioneSubpartizione().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(verificaMigrazioneSubpartizione); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per Calcolo contenuto aggiornamenti metadati"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CALCOLO_CONTENUTO_AGGIORNAMENTI_METADATI.name()); StatoJob calcoloContenutoAggMeta = new StatoJob( JobConstants.JobEnum.CALCOLO_CONTENUTO_AGGIORNAMENTI_METADATI.name(), getForm().getCalcoloContenutoAggiornamentiMetadati().getFl_data_accurata(), getForm().getCalcoloContenutoAggiornamentiMetadati().getStartCalcoloContenutoAgg(), getForm().getCalcoloContenutoAggiornamentiMetadati().getStartOnceCalcoloContenutoAgg(), getForm().getCalcoloContenutoAggiornamentiMetadati().getStopCalcoloContenutoAgg(), getForm().getCalcoloContenutoAggiornamentiMetadati().getDt_prossima_attivazione(), getForm().getCalcoloContenutoAggiornamentiMetadati().getAttivo(), getForm().getCalcoloContenutoAggiornamentiMetadati().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(calcoloContenutoAggMeta); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="UI Gestione job per controlla migrazione subpartizione"> dataAttivazioneJob = getActivationDateJob(JobConstants.JobEnum.CONTROLLA_MIGRAZIONE_SUBPARTIZIONE.name()); StatoJob controlloMigrazioneSubpartizione = new StatoJob( JobConstants.JobEnum.CONTROLLA_MIGRAZIONE_SUBPARTIZIONE.name(), getForm().getControllaMigrazioneSubpartizione().getFl_data_accurata(), getForm().getControllaMigrazioneSubpartizione().getStartControllaMigrazioneSubpartizione(), getForm().getControllaMigrazioneSubpartizione().getStartOnceControllaMigrazioneSubpartizione(), getForm().getControllaMigrazioneSubpartizione().getStopControllaMigrazioneSubpartizione(), getForm().getControllaMigrazioneSubpartizione().getDt_prossima_attivazione(), getForm().getControllaMigrazioneSubpartizione().getAttivo(), getForm().getControllaMigrazioneSubpartizione().getDt_reg_log_job_ini(), dataAttivazioneJob); gestisciStatoJob(controlloMigrazioneSubpartizione); // </editor-fold> forwardToPublisher(Application.Publisher.GESTIONE_JOB); } /** * Cuore della classe: qui è definita la logica STANDARD degli stati dei job a livello di <b>interfaccia web<b>. Per * i job che devono implementare una logica non standard non è consigliabile utilizzare questo metodo. Si è cercato * di mantenere una simmetria tra esposizione/inibizione dei controlli grafici. * * @param statoJob * Rappresentazione dello stato <b>a livello di interfaccia grafica</b> del job. * * @throws EMFError * in caso di errore generale */ private void gestisciStatoJob(StatoJob statoJob) throws EMFError { // se non è ancora passato un minuto da quando è stato premuto un pulsante non posso fare nulla boolean operazioneInCorso = jbossTimerEjb.isEsecuzioneInCorso(statoJob.getNomeJob()); statoJob.getFlagDataAccurata().setViewMode(); statoJob.getFlagDataAccurata().setValue("L'operazione richiesta verrà effettuata entro il prossimo minuto."); statoJob.getStart().setHidden(operazioneInCorso); statoJob.getEsecuzioneSingola().setHidden(operazioneInCorso); statoJob.getStop().setHidden(operazioneInCorso); statoJob.getDataProssimaAttivazione().setHidden(operazioneInCorso); statoJob.getFlagDataAccurata().setHidden(!operazioneInCorso); if (operazioneInCorso) { return; } // Posso operare sulla pagina Date nextActivation = jbossTimerEjb.getDataProssimaAttivazione(statoJob.getNomeJob()); boolean dataAccurata = jbossTimerEjb.isDataProssimaAttivazioneAccurata(statoJob.getNomeJob()); DateFormat formato = new SimpleDateFormat(WebConstants.DATE_FORMAT_TIMESTAMP_TYPE); /* * Se il job è già schedulato o in esecuzione singola nascondo il pulsante Start/esecuzione singola, mostro Stop * e visualizzo la prossima attivazione. Viceversa se è fermo mostro Start e nascondo Stop */ if (nextActivation != null) { statoJob.getStart().setViewMode(); statoJob.getEsecuzioneSingola().setViewMode(); statoJob.getStop().setEditMode(); statoJob.getDataProssimaAttivazione().setValue(formato.format(nextActivation)); } else { statoJob.getStart().setEditMode(); statoJob.getEsecuzioneSingola().setEditMode(); statoJob.getStop().setViewMode(); statoJob.getDataProssimaAttivazione().setValue(null); } boolean flagHidden = nextActivation == null || dataAccurata; // se la data c'è ma non è accurata non visualizzare la "data prossima attivazione" statoJob.getDataProssimaAttivazione().setHidden(!flagHidden); if (statoJob.getDataAttivazione() != null) { statoJob.getCheckAttivo().setChecked(true); statoJob.getDataRegistrazioneJob() .setValue(formato.format(new Date(statoJob.getDataAttivazione().getTime()))); } else { statoJob.getCheckAttivo().setChecked(false); statoJob.getDataRegistrazioneJob().setValue(null); } } // <editor-fold defaultstate="collapsed" desc="UI Classe che mappa lo stato dei job"> /** * Astrazione dei componenti della pagina utilizzati per i "box" dei job. * * @author Snidero_L */ public static final class StatoJob { private final String nomeJob; private final Input<String> flagDataAccurata; private final Button<String> start; private final Button<String> esecuzioneSingola; private final Button<String> stop; private final Input<Timestamp> dataProssimaAttivazione; private final CheckBox<String> checkAttivo; private final Input<Timestamp> dataRegistrazioneJob; private final Timestamp dataAttivazione; // Mi serve per evitare una null pointer Exception private static final Button<String> NULL_BUTTON = new Button<String>(null, "EMPTY_BUTTON", "Pulsante vuoto", null, null, null, false, true, true, false); public StatoJob(String nomeJob, Input<String> flagDataAccurata, Button<String> start, Button<String> esecuzioneSingola, Button<String> stop, Input<Timestamp> dataProssimaAttivazione, CheckBox<String> checkAttivo, Input<Timestamp> dataRegistrazioneJob, Timestamp dataAttivazione) { this.nomeJob = nomeJob; this.flagDataAccurata = flagDataAccurata; this.start = start; this.esecuzioneSingola = esecuzioneSingola; this.stop = stop; this.dataProssimaAttivazione = dataProssimaAttivazione; this.checkAttivo = checkAttivo; this.dataRegistrazioneJob = dataRegistrazioneJob; this.dataAttivazione = dataAttivazione; } public String getNomeJob() { return nomeJob; } public Input<String> getFlagDataAccurata() { return flagDataAccurata; } public Button<String> getStart() { if (start == null) { return NULL_BUTTON; } return start; } public Button<String> getEsecuzioneSingola() { return esecuzioneSingola; } public Button<String> getStop() { if (stop == null) { return NULL_BUTTON; } return stop; } public Input<Timestamp> getDataProssimaAttivazione() { return dataProssimaAttivazione; } public CheckBox<String> getCheckAttivo() { return checkAttivo; } public Input<Timestamp> getDataRegistrazioneJob() { return dataRegistrazioneJob; } public Timestamp getDataAttivazione() { return dataAttivazione; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Funzioni non implementate"> @Override public void insertDettaglio() throws EMFError { throw new UnsupportedOperationException("Not supported yet."); } @Override public void loadDettaglio() throws EMFError { throw new UnsupportedOperationException("Not supported yet."); } @Override public void undoDettaglio() throws EMFError { throw new UnsupportedOperationException("Not supported yet."); } @Override public void saveDettaglio() throws EMFError { throw new UnsupportedOperationException("Not supported yet."); } @Override public void dettaglioOnClick() throws EMFError { throw new UnsupportedOperationException("Not supported yet."); } @Override public void elencoOnClick() throws EMFError { goBack(); } @Override public void process() throws EMFError { throw new UnsupportedOperationException("Not supported yet."); } @Override public void reloadAfterGoBack(String publisherName) { try { ricercaGestioneJob(); } catch (EMFError ex) { LOG.error(ex.getDescription()); getMessageBox().addError("Errore durante il caricamento dell'elenco dei JOB"); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneElenchi schedulation"> @Override public void startCreazioneElenchi() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS.name(), "Creazione elenchi", null, OPERAZIONE.START); } @Override public void startOnceCreazioneElenchi() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS.name(), "Creazione elenchi", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneElenchi() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS.name(), "Creazione elenchi", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneIndici schedulation"> @Override public void startCreazioneIndici() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS.name(), "Creazione indici", null, OPERAZIONE.START); } @Override public void startOnceCreazioneIndici() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS.name(), "Creazione indici", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneIndici() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS.name(), "Creazione indici", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage VerificaFirme schedulation"> @Override public void startVerificaFirme() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_FIRME_A_DATA_VERS.name(), "Verifica firme", null, OPERAZIONE.START); } @Override public void startOnceVerificaFirme() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_FIRME_A_DATA_VERS.name(), "Verifica firme", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopVerificaFirme() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_FIRME_A_DATA_VERS.name(), "Verifica firme", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CodaIndiciAipDaElab schedulation"> @Override public void startCodaIndiciAipDaElab() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_INDICI_AIP_DA_ELAB.name(), "Coda indici aip da elaborare", null, OPERAZIONE.START); } @Override public void startOnceCodaIndiciAipDaElab() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_INDICI_AIP_DA_ELAB.name(), "Coda indici aip da elaborare", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCodaIndiciAipDaElab() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_INDICI_AIP_DA_ELAB.name(), "Coda indici aip da elaborare", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CalcolaContenutoSacer schedulation"> @Override public void startCalcoloContenutoSacer() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_SACER.name(), "Calcolo Contenuto Sacer", null, OPERAZIONE.START); } @Override public void startOnceCalcoloContenutoSacer() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_SACER.name(), "Calcolo Contenuto Sacer", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCalcoloContenutoSacer() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_SACER.name(), "Calcolo Contenuto Sacer", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage AllineamentoOrganizzazioni schedulation"> @Override public void startAllineamentoOrganizzazioni() throws EMFError { esegui(JobConstants.JobEnum.ALLINEAMENTO_ORGANIZZAZIONI.name(), "Allineamento organizzazioni", null, OPERAZIONE.START); } @Override public void startOnceAllineamentoOrganizzazioni() throws EMFError { esegui(JobConstants.JobEnum.ALLINEAMENTO_ORGANIZZAZIONI.name(), "Allineamento organizzazioni", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopAllineamentoOrganizzazioni() throws EMFError { esegui(JobConstants.JobEnum.ALLINEAMENTO_ORGANIZZAZIONI.name(), "Allineamento organizzazioni", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage AggiornaStatoArk schedulation"> @Override public void startAggiornamentoStatoArk() throws EMFError { esegui(JobConstants.JobEnum.AGGIORNA_STATO_ARCHIVIAZIONE.name(), "Aggiorna stato archiviazione", null, OPERAZIONE.START); } @Override public void startOnceAggiornamentoStatoArk() throws EMFError { esegui(JobConstants.JobEnum.AGGIORNA_STATO_ARCHIVIAZIONE.name(), "Aggiorna stato archiviazione", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopAggiornamentoStatoArk() throws EMFError { esegui(JobConstants.JobEnum.AGGIORNA_STATO_ARCHIVIAZIONE.name(), "Aggiorna stato archiviazione", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ElaboraSessioniRecupero schedulation"> @Override public void startElaboraSessioniRecupero() throws EMFError { esegui(JobConstants.JobEnum.ELABORA_SESSIONI_RECUPERO.name(), "Elabora sessioni recupero archiviazione", null, OPERAZIONE.START); } @Override public void startOnceElaboraSessioniRecupero() throws EMFError { esegui(JobConstants.JobEnum.ELABORA_SESSIONI_RECUPERO.name(), "Elabora sessioni recupero archiviazione", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopElaboraSessioniRecupero() throws EMFError { esegui(JobConstants.JobEnum.ELABORA_SESSIONI_RECUPERO.name(), "Elabora sessioni recupero archiviazione", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage RegistraSchedTpi schedulation"> @Override public void startRegistraSchedTpi() throws EMFError { esegui(JobConstants.JobEnum.REGISTRA_SCHEDULAZIONI_JOB_TPI.name(), "Registra schedulazioni job TPI", null, OPERAZIONE.START); } @Override public void startOnceRegistraSchedTpi() throws EMFError { esegui(JobConstants.JobEnum.REGISTRA_SCHEDULAZIONI_JOB_TPI.name(), "Registra schedulazioni job TPI", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopRegistraSchedTpi() throws EMFError { esegui(JobConstants.JobEnum.REGISTRA_SCHEDULAZIONI_JOB_TPI.name(), "Registra schedulazioni job TPI", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneIndiciAIP schedulation"> @Override public void startCreazioneIndiciAip() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP.name(), "Creazione indici AIP", null, OPERAZIONE.START); } @Override public void startOnceCreazioneIndiciAip() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP.name(), "Creazione indici AIP", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneIndiciAip() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP.name(), "Creazione indici AIP", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ProducerCodaDaMigrare1 schedulation"> @Override public void startProducerCodaDaMigrare1() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_1.name(), "Producer coda da migrare 1", null, OPERAZIONE.START); } @Override public void startOnceProducerCodaDaMigrare1() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_1.name(), "Producer coda da migrare 1", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopProducerCodaDaMigrare1() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_1.name(), "Producer coda da migrare 1", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ProducerCodaDaMigrare2 schedulation"> @Override public void startProducerCodaDaMigrare2() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_2.name(), "Producer coda da migrare 2", null, OPERAZIONE.START); } @Override public void startOnceProducerCodaDaMigrare2() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_2.name(), "Producer coda da migrare 2", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopProducerCodaDaMigrare2() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_2.name(), "Producer coda da migrare 2", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ProducerCodaDaMigrare3 schedulation"> @Override public void startProducerCodaDaMigrare3() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_3.name(), "Producer coda da migrare 3", null, OPERAZIONE.START); } @Override public void startOnceProducerCodaDaMigrare3() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_3.name(), "Producer coda da migrare 3", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopProducerCodaDaMigrare3() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_3.name(), "Producer coda da migrare 3", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ProducerCodaDaMigrare4 schedulation"> @Override public void startProducerCodaDaMigrare4() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_4.name(), "Producer coda da migrare 4", null, OPERAZIONE.START); } @Override public void startOnceProducerCodaDaMigrare4() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_4.name(), "Producer coda da migrare 4", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopProducerCodaDaMigrare4() throws EMFError { esegui(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE_4.name(), "Producer coda da migrare 4", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage PreparazionePartizioneDaMigrare1 schedulation"> @Override public void startPreparazionePartizioneDaMigrare1() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_1.name(), "Preparazione Partizione da migrare 1", null, OPERAZIONE.START); } @Override public void startOncePreparazionePartizioneDaMigrare1() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_1.name(), "Preparazione Partizione da migrare 1", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopPreparazionePartizioneDaMigrare1() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_1.name(), "Preparazione Partizione da migrare 1", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage PreparazionePartizioneDaMigrare2 schedulation"> @Override public void startPreparazionePartizioneDaMigrare2() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_2.name(), "Preparazione Partizione da migrare 2", null, OPERAZIONE.START); } @Override public void startOncePreparazionePartizioneDaMigrare2() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_2.name(), "Preparazione Partizione da migrare 2", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopPreparazionePartizioneDaMigrare2() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_2.name(), "Preparazione Partizione da migrare 2", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage PreparazionePartizioneDaMigrare3 schedulation"> @Override public void startPreparazionePartizioneDaMigrare3() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_3.name(), "Preparazione Partizione da migrare 3", null, OPERAZIONE.START); } @Override public void startOncePreparazionePartizioneDaMigrare3() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_3.name(), "Preparazione Partizione da migrare 3", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopPreparazionePartizioneDaMigrare3() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_3.name(), "Preparazione Partizione da migrare 3", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage PreparazionePartizioneDaMigrare4 schedulation"> @Override public void startPreparazionePartizioneDaMigrare4() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_4.name(), "Preparazione Partizione da migrare 4", null, OPERAZIONE.START); } @Override public void startOncePreparazionePartizioneDaMigrare4() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_4.name(), "Preparazione Partizione da migrare 4", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopPreparazionePartizioneDaMigrare4() throws EMFError { esegui(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE_4.name(), "Preparazione Partizione da migrare 4", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage VerificaMigrazioneSubpartizione schedulation"> @Override public void startVerificaMigrazioneSubpartizione() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_MIGRAZIONE_SUBPARTIZIONE.name(), "Verifica migrazione subpartizione", null, OPERAZIONE.START); } @Override public void startOnceVerificaMigrazioneSubpartizione() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_MIGRAZIONE_SUBPARTIZIONE.name(), "Verifica migrazione subpartizione", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopVerificaMigrazioneSubpartizione() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_MIGRAZIONE_SUBPARTIZIONE.name(), "Verifica migrazione subpartizione", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ControllaMigrazioneSubpartizione schedulation"> @Override public void startControllaMigrazioneSubpartizione() throws EMFError { esegui(JobConstants.JobEnum.CONTROLLA_MIGRAZIONE_SUBPARTIZIONE.name(), "Controlla migrazione subpartizione", null, OPERAZIONE.START); } @Override public void startOnceControllaMigrazioneSubpartizione() throws EMFError { esegui(JobConstants.JobEnum.CONTROLLA_MIGRAZIONE_SUBPARTIZIONE.name(), "Controlla migrazione subpartizione", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopControllaMigrazioneSubpartizione() throws EMFError { esegui(JobConstants.JobEnum.CONTROLLA_MIGRAZIONE_SUBPARTIZIONE.name(), "Controlla migrazione subpartizione", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage VerificaMassivaVersamentiFalliti schedulation"> @Override public void startVerificaMassivaVersamentiFalliti() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_MASSIVA_VERS_FALLITI.name(), "Verifica massiva versamenti falliti", null, OPERAZIONE.START); } @Override public void startOnceVerificaMassivaVersamentiFalliti() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_MASSIVA_VERS_FALLITI.name(), "Verifica massiva versamenti falliti", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopVerificaMassivaVersamentiFalliti() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_MASSIVA_VERS_FALLITI.name(), "Verifica massiva versamenti falliti", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage VerificaPeriodoRegistro schedulation"> @Override public void startVerificaPeriodoRegistro() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_REGISTRO.name(), "Verifica periodo registro", null, OPERAZIONE.START); } @Override public void startOnceVerificaPeriodoRegistro() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_REGISTRO.name(), "Verifica periodo registro", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopVerificaPeriodoRegistro() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_REGISTRO.name(), "Verifica periodo registro", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneAutomaticaSerie schedulation"> @Override public void startCreazioneAutomaticaSerie() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_AUTOMATICA_SERIE.name(), "Creazione automatica serie", null, OPERAZIONE.START); } @Override public void startOnceCreazioneAutomaticaSerie() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_AUTOMATICA_SERIE.name(), "Creazione automatica serie", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneAutomaticaSerie() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_AUTOMATICA_SERIE.name(), "Creazione automatica serie", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneIndiciAIPSerieUD schedulation"> @Override public void startCreazioneIndiciAipSerieUd() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_SERIE_UD.name(), "Creazione indice AIP serie ud", null, OPERAZIONE.START); } @Override public void startOnceCreazioneIndiciAipSerieUd() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_SERIE_UD.name(), "Creazione indice AIP serie ud", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneIndiciAipSerieUd() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_SERIE_UD.name(), "Creazione indice AIP serie ud", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage GenerazioneAutomaticaEffettivo schedulation"> @Override public void startGenerazioneAutomaticaEffettivo() throws EMFError { esegui(JobConstants.JobEnum.GENERAZIONE_AUTOMATICA_CONTENUTO_EFFETTIVO.name(), "Generazione automatica contenuto effettivo serie", null, OPERAZIONE.START); } @Override public void startOnceGenerazioneAutomaticaEffettivo() throws EMFError { esegui(JobConstants.JobEnum.GENERAZIONE_AUTOMATICA_CONTENUTO_EFFETTIVO.name(), "Generazione automatica contenuto effettivo serie", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopGenerazioneAutomaticaEffettivo() throws EMFError { esegui(JobConstants.JobEnum.GENERAZIONE_AUTOMATICA_CONTENUTO_EFFETTIVO.name(), "Generazione automatica contenuto effettivo serie", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ControlloAutomaticoEffettivo schedulation"> @Override public void startControlloAutomaticoEffettivo() throws EMFError { esegui(JobConstants.JobEnum.CONTROLLO_AUTOMATICO_CONTENUTO_EFFETTIVO.name(), "Controllo automatico contenuto effettivo serie", null, OPERAZIONE.START); } @Override public void startOnceControlloAutomaticoEffettivo() throws EMFError { esegui(JobConstants.JobEnum.CONTROLLO_AUTOMATICO_CONTENUTO_EFFETTIVO.name(), "Controllo automatico contenuto effettivo serie", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopControlloAutomaticoEffettivo() throws EMFError { esegui(JobConstants.JobEnum.CONTROLLO_AUTOMATICO_CONTENUTO_EFFETTIVO.name(), "Controllo automatico contenuto effettivo serie", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage EvasioneRichiesteAnnullamentoVersamenti // schedulation"> @Override public void startEvasioneRichiesteAnnulVers() throws EMFError { esegui(JobConstants.JobEnum.EVASIONE_RICH_ANNUL_VERS.name(), "Evasione richieste di annullamento versamenti", null, OPERAZIONE.START); } @Override public void startOnceEvasioneRichiesteAnnulVers() throws EMFError { esegui(JobConstants.JobEnum.EVASIONE_RICH_ANNUL_VERS.name(), "Evasione richieste di annullamento versamenti", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopEvasioneRichiesteAnnulVers() throws EMFError { esegui(JobConstants.JobEnum.EVASIONE_RICH_ANNUL_VERS.name(), "Evasione richieste di annullamento versamenti", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CalcoloStruttura schedulation"> @Override public void startCalcoloStruttura() throws EMFError { esegui(JobConstants.JobEnum.CALCOLA_STRUTTURA_JOB.name(), "Calcolo struttura", null, OPERAZIONE.START); } @Override public void startOnceCalcoloStruttura() throws EMFError { esegui(JobConstants.JobEnum.CALCOLA_STRUTTURA_JOB.name(), "Calcolo struttura", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCalcoloStruttura() throws EMFError { esegui(JobConstants.JobEnum.CALCOLA_STRUTTURA_JOB.name(), "Calcolo struttura", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CalcoloEstrazione schedulation"> @Override public void startEvasioneRichiesteRestArch() throws EMFError { esegui(JobConstants.JobEnum.EVASIONE_RICH_REST_ARCH.name(), "Evasione richieste di restituzione archivio", null, OPERAZIONE.START); } @Override public void startOnceEvasioneRichiesteRestArch() throws EMFError { esegui(JobConstants.JobEnum.EVASIONE_RICH_REST_ARCH.name(), "Evasione richieste di restituzione archivio", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopEvasioneRichiesteRestArch() throws EMFError { esegui(JobConstants.JobEnum.EVASIONE_RICH_REST_ARCH.name(), "Evasione richieste di restituzione archivio", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage AllineamentoLog schedulation"> @Override public void startOnceInizializzazioneLog() throws EMFError { String nomeApplicazione = configHelper.getValoreParamApplicByApplic(CostantiDB.ParametroAppl.NM_APPLIC); esegui(it.eng.parer.sacerlog.job.Constants.NomiJob.INIZIALIZZAZIONE_LOG.name(), "Inizializzazione Log", nomeApplicazione, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void startAllineamentoLog() throws EMFError { String nomeApplicazione = configHelper.getValoreParamApplicByApplic(CostantiDB.ParametroAppl.NM_APPLIC); esegui(it.eng.parer.sacerlog.job.Constants.NomiJob.ALLINEAMENTO_LOG.name(), "Allineamento Log", nomeApplicazione, OPERAZIONE.START); } @Override public void startOnceAllineamentoLog() throws EMFError { String nomeApplicazione = configHelper.getValoreParamApplicByApplic(CostantiDB.ParametroAppl.NM_APPLIC); esegui(it.eng.parer.sacerlog.job.Constants.NomiJob.ALLINEAMENTO_LOG.name(), "Allineamento Log", nomeApplicazione, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopAllineamentoLog() throws EMFError { String nomeApplicazione = configHelper.getValoreParamApplicByApplic(CostantiDB.ParametroAppl.NM_APPLIC); esegui(it.eng.parer.sacerlog.job.Constants.NomiJob.ALLINEAMENTO_LOG.name(), "Allineamento Log", nomeApplicazione, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneElenchiIndiciAIPUd schedulation"> @Override public void startCreazioneElenchiIndiciAip() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_UD.name(), "Creazione elenchi indici AIP", null, OPERAZIONE.START); } @Override public void startOnceCreazioneElenchiIndiciAip() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_UD.name(), "Creazione elenchi indici AIP", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneElenchiIndiciAip() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_UD.name(), "Creazione elenchi indici AIP", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CalcolaContenutoFascicoli schedulation"> @Override public void startCalcoloContenutoFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_FASCICOLI.name(), "Calcolo contenuto fascicoli", null, OPERAZIONE.START); } @Override public void startOnceCalcoloContenutoFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_FASCICOLI.name(), "Calcolo contenuto fascicoli", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCalcoloContenutoFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_FASCICOLI.name(), "Calcolo contenuto fascicoli", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage AllineaEntiConvenzionati schedulation"> @Override public void startAllineaEntiConvenzionati() throws EMFError { esegui(JobConstants.JobEnum.ALLINEA_ENTI_CONVENZIONATI.name(), "Allinea enti convenzionati", null, OPERAZIONE.START); } @Override public void startOnceAllineaEntiConvenzionati() throws EMFError { esegui(JobConstants.JobEnum.ALLINEA_ENTI_CONVENZIONATI.name(), "Allinea enti convenzionati", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopAllineaEntiConvenzionati() throws EMFError { esegui(JobConstants.JobEnum.ALLINEA_ENTI_CONVENZIONATI.name(), "Allinea enti convenzionati", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage VerificaPeriodoTipoFascicolo schedulation"> @Override public void startVerificaPeriodoTipoFasc() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_TIPO_FASC.name(), "Verifica periodo tipo fascicolo", null, OPERAZIONE.START); } @Override public void startOnceVerificaPeriodoTipoFasc() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_TIPO_FASC.name(), "Verifica periodo tipo fascicolo", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopVerificaPeriodoTipoFasc() throws EMFError { esegui(JobConstants.JobEnum.VERIFICA_COMPATIBILITA_TIPO_FASC.name(), "Verifica periodo tipo fascicolo", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneElencoVersFascicoli schedulation"> @Override public void startCreazioneElenchiVersFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS_FASCICOLI.name(), "Creazione elenchi versamento fascicoli", null, OPERAZIONE.START); } @Override public void startOnceCreazioneElenchiVersFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS_FASCICOLI.name(), "Creazione elenchi versamento fascicoli", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneElenchiVersFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_VERS_FASCICOLI.name(), "Creazione elenchi versamento fascicoli", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneIndiciVersFascicoli schedulation"> @Override public void startCreazioneIndiciVersFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS_FASC.name(), "Creazione indici versamento fascicoli", null, OPERAZIONE.START); } @Override public void startOnceCreazioneIndiciVersFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS_FASC.name(), "Creazione indici versamento fascicoli", null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void stopCreazioneIndiciVersFascicoli() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICI_ELENCHI_VERS_FASC.name(), "Creazione indici versamento fascicoli", null, OPERAZIONE.STOP); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage ValidazioneFascicoli schedulation"> @Override public void startValidazioneFascicoli() throws EMFError { esegui(JobConstants.JobEnum.VALIDAZIONE_FASCICOLI.name(), "Validazione fascicoli", null, OPERAZIONE.START); } @Override public void stopValidazioneFascicoli() throws EMFError { esegui(JobConstants.JobEnum.VALIDAZIONE_FASCICOLI.name(), "Validazione fascicoli", null, OPERAZIONE.STOP); } @Override public void startOnceValidazioneFascicoli() throws EMFError { esegui(JobConstants.JobEnum.VALIDAZIONE_FASCICOLI.name(), "Validazione fascicoli", null, OPERAZIONE.ESECUZIONE_SINGOLA); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneIndiciAIPFascicoli schedulation"> @Override public void startCreazioneIndiciAipFasc() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_FASC.name(), "Creazione indici AIP fascicoli", null, OPERAZIONE.START); } @Override public void stopCreazioneIndiciAipFasc() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_FASC.name(), "Creazione indici AIP fascicoli", null, OPERAZIONE.STOP); } @Override public void startOnceCreazioneIndiciAipFasc() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_INDICE_AIP_FASC.name(), "Creazione indici AIP fascicoli", null, OPERAZIONE.ESECUZIONE_SINGOLA); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CalcoloContenutoAggiornamentiMetadati // schedulation"> @Override public void startCalcoloContenutoAgg() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_AGGIORNAMENTI_METADATI.name(), "Calcolo contenuto aggiornamenti metadati", null, OPERAZIONE.START); } @Override public void stopCalcoloContenutoAgg() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_AGGIORNAMENTI_METADATI.name(), "Calcolo contenuto aggiornamenti metadati", null, OPERAZIONE.STOP); } @Override public void startOnceCalcoloContenutoAgg() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONTENUTO_AGGIORNAMENTI_METADATI.name(), "Calcolo contenuto aggiornamenti metadati", null, OPERAZIONE.ESECUZIONE_SINGOLA); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CalcoloConsistenza schedulation"> @Override public void startCalcoloConsistenza() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONSISTENZA.name(), "Calcolo consistenza", null, OPERAZIONE.START); } @Override public void stopCalcoloConsistenza() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONSISTENZA.name(), "Calcolo consistenza", null, OPERAZIONE.STOP); } @Override public void startOnceCalcoloConsistenza() throws EMFError { esegui(JobConstants.JobEnum.CALCOLO_CONSISTENZA.name(), "Calcolo consistenza", null, OPERAZIONE.ESECUZIONE_SINGOLA); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Methods to manage CreazioneElenchiIndiciAIPFascicoli schedulation"> @Override public void startCreazioneElenchiIndiciAipFasc() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_FASC.name(), "Creazione elenchi indici AIP fascicoli", null, OPERAZIONE.START); } @Override public void stopCreazioneElenchiIndiciAipFasc() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_FASC.name(), "Creazione elenchi indici AIP fascicoli", null, OPERAZIONE.STOP); } @Override public void startOnceCreazioneElenchiIndiciAipFasc() throws EMFError { esegui(JobConstants.JobEnum.CREAZIONE_ELENCHI_INDICI_AIP_FASC.name(), "Creazione elenchi indici AIP fascicoli", null, OPERAZIONE.ESECUZIONE_SINGOLA); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Esecuzione di un job STANDARD"> /** * Esegui una delle seguenti operazioni: * <ul> * <li>{@link OPERAZIONE#START}</li> * <li>{@link OPERAZIONE#ESECUZIONE_SINGOLA}</li> * <li>{@link OPERAZIONE#STOP}</li> * </ul> * * @param nomeJob * nome del job * @param descrizioneJob * descrizione (che comparirà sul LOG) del job * @param nomeApplicazione * nome dell'applicazione. <b>Obbligatorio per i job che elaborano i LOG "PREMIS"</b> * @param operazione * una delle tre operazioni dell'enum * * @throws EMFError * Errore di esecuzione */ private void esegui(String nomeJob, String descrizioneJob, String nomeApplicazione, OPERAZIONE operazione) throws EMFError { // Messaggio sul logger di sistema StringBuilder info = new StringBuilder(descrizioneJob); info.append(": ").append(operazione.description()).append(" [").append(nomeJob); if (nomeApplicazione != null) { info.append("_").append(nomeApplicazione); } info.append("]"); LOG.info(info.toString()); String message = "Errore durante la schedulazione del job"; switch (operazione) { case START: jbossTimerEjb.start(nomeJob, null); message = descrizioneJob + ": job correttamente schedulato"; break; case ESECUZIONE_SINGOLA: jbossTimerEjb.esecuzioneSingola(nomeJob, null); message = descrizioneJob + ": job correttamente schedulato per esecuzione singola"; break; case STOP: jbossTimerEjb.stop(nomeJob); message = descrizioneJob + ": schedulazione job annullata"; break; } // Segnalo l'avvenuta operazione sul job getMessageBox().addMessage(new Message(MessageLevel.INF, message)); getMessageBox().setViewMode(ViewMode.plain); // Risetto la pagina rilanciando l'initOnClick initOnClick(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="NUOVA GESTIONE JOB"> @Secure(action = "Menu.Amministrazione.GestioneJobRicerca") public void gestioneJobRicercaPage() throws EMFError { getUser().getMenu().reset(); getUser().getMenu().select("Menu.Amministrazione.GestioneJobRicerca"); getForm().getGestioneJobRicercaList().setTable(null); resetFiltriGestioneJobRicercaPage(); popolaInformazioniJob(); tabRicercaJobTabOnClick(); getForm().getGestioneJobInfo().getSalvaFotoGestioneJob().setEditMode(); getForm().getGestioneJobInfo().getDisabilitaAllJobs().setEditMode(); getForm().getGestioneJobInfo2().getRipristinaFotoGestioneJob().setEditMode(); getForm().getGestioneJobInfo().getRicaricaGestioneJob().setEditMode(); getSession().removeAttribute("visualizzaRipristinaFoto"); abilitaDisabilitaBottoniJob(!gestioneJobEjb.isDecJobFotoEmpty() && gestioneJobEjb.areAllJobsDisattivati(), getSession().getAttribute("fotoSalvata") != null); forwardToPublisher(Application.Publisher.GESTIONE_JOB_RICERCA); } public void resetFiltriGestioneJobRicercaPage() throws EMFError { getForm().getGestioneJobRicercaFiltri().setEditMode(); getForm().getGestioneJobRicercaFiltri().reset(); getForm().getGestioneJobRicercaList().setTable(null); BaseTable ambitoTableBean = gestioneJobEjb.getAmbitoJob(); getForm().getGestioneJobRicercaFiltri().getNm_ambito() .setDecodeMap(DecodeMap.Factory.newInstance(ambitoTableBean, "nm_ambito", "nm_ambito")); getForm().getGestioneJobRicercaFiltri().getTi_stato_job().setDecodeMap(ComboGetter.getMappaTiStatoJob()); } public String[] calcolaInformazioniJob() { BaseRow infoJobRowBean = gestioneJobEjb.getInfoJobRowBean(); int niTotJobPresenti = infoJobRowBean.getBigDecimal("ni_tot_job_presenti") != null ? infoJobRowBean.getBigDecimal("ni_tot_job_presenti").intValue() : 0; int niTotJobAttivi = infoJobRowBean.getBigDecimal("ni_tot_job_attivi") != null ? infoJobRowBean.getBigDecimal("ni_tot_job_attivi").intValue() : 0; int niTotJobDisattivi = infoJobRowBean.getBigDecimal("ni_tot_job_disattivi") != null ? infoJobRowBean.getBigDecimal("ni_tot_job_disattivi").intValue() : 0; String[] info = new String[3]; info[0] = "" + niTotJobPresenti; info[1] = "" + niTotJobAttivi; info[2] = "" + niTotJobDisattivi; return info; } public void popolaInformazioniJob() { String[] info = calcolaInformazioniJob(); getForm().getGestioneJobRicercaInfo().getNi_tot_job_presenti().setValue(info[0]); getForm().getGestioneJobRicercaInfo().getNi_tot_job_attivi().setValue(info[1]); getForm().getGestioneJobRicercaInfo().getNi_tot_job_disattivi().setValue(info[2]); } public void popolaInfoDecJobAmministrazioneJobTab() throws EMFError { String[] info = calcolaInformazioniJob(); getForm().getGestioneJobInfo().getNi_tot_job_presenti().setValue(info[0]); getForm().getGestioneJobInfo().getNi_tot_job_attivi().setValue(info[1]); getForm().getGestioneJobInfo().getNi_tot_job_disattivi().setValue(info[2]); } @Override public void ricercaGestioneJob() throws EMFError { getForm().getGestioneJobRicercaFiltri().getRicercaGestioneJob().setDisableHourGlass(true); GestioneJobRicercaFiltri filtri = getForm().getGestioneJobRicercaFiltri(); if (getRequest().getAttribute("fromLink") == null && getRequest().getAttribute("fromListaPrinc") == null) { if (getSession().getAttribute(FROM_SCHEDULAZIONI_JOB) != null) { getSession().removeAttribute(FROM_SCHEDULAZIONI_JOB); } else { filtri.post(getRequest()); } } popolaInformazioniJob(); if (filtri.validate(getMessageBox())) { BaseTable jobTB = gestioneJobEjb.getDecJobTableBean(filtri); getForm().getGestioneJobRicercaList().setTable(jobTB); getForm().getGestioneJobRicercaList().getTable().setPageSize(100); getForm().getGestioneJobRicercaList().getTable().first(); } forwardToPublisher(Application.Publisher.GESTIONE_JOB_RICERCA); } @Override public void tabRicercaJobTabOnClick() throws EMFError { getForm().getGestioneJobTabs().setCurrentTab(getForm().getGestioneJobTabs().getRicercaJobTab()); ricercaGestioneJob(); forwardToPublisher(Application.Publisher.GESTIONE_JOB_RICERCA); } @Override public void tabAmmJobTabOnClick() throws EMFError { getForm().getGestioneJobTabs().setCurrentTab(getForm().getGestioneJobTabs().getAmmJobTab()); abilitaDisabilitaBottoniJob(!gestioneJobEjb.isDecJobFotoEmpty() && gestioneJobEjb.areAllJobsDisattivati(), getSession().getAttribute("fotoSalvata") != null); decoraDatiTabAmmJobTab(); forwardToPublisher(Application.Publisher.GESTIONE_JOB_RICERCA); } public void decoraDatiTabAmmJobTab() throws EMFError { popolaInfoDecJobAmministrazioneJobTab(); popolaInfoDecJobFotoAmministrazioneJobTab(); BaseTable jobTB = gestioneJobEjb.getDecJobTableBeanPerAmm(); getForm().getGestioneJobListPerAmm().setTable(jobTB); getForm().getGestioneJobListPerAmm().getTable().setPageSize(100); getForm().getGestioneJobListPerAmm().getTable().first(); BaseTable jobFotoTB = gestioneJobEjb.getDecJobFotoTableBeanPerAmm(); getForm().getGestioneJobFotoListPerAmm().setTable(jobFotoTB); getForm().getGestioneJobFotoListPerAmm().getTable().setPageSize(100); getForm().getGestioneJobFotoListPerAmm().getTable().first(); } public void getNuoviJob() throws JSONException { JSONObject jso = new JSONObject(); // Recupero i nomi dei nuovi JOB Object[] nmJobObj = gestioneJobEjb.getInfoJobFotoNomiJobRowBean(); jso.put("nm_job_array_nuovi", (Set<String>) nmJobObj[0]); jso.put("nm_job_array_solo_foto", (Set<String>) nmJobObj[1]); redirectToAjax(jso); } public void popolaInfoDecJobFotoAmministrazioneJobTab() throws EMFError { BaseRow infoJobFotoRowBean = gestioneJobEjb.getInfoJobFotoRowBean(); int niTotJobPresenti2 = infoJobFotoRowBean.getBigDecimal("ni_tot_job_presenti2") != null ? infoJobFotoRowBean.getBigDecimal("ni_tot_job_presenti2").intValue() : 0; int niTotJobAttivi2 = infoJobFotoRowBean.getBigDecimal("ni_tot_job_attivi2") != null ? infoJobFotoRowBean.getBigDecimal("ni_tot_job_attivi2").intValue() : 0; int niTotJobDisattivi2 = infoJobFotoRowBean.getBigDecimal("ni_tot_job_disattivi2") != null ? infoJobFotoRowBean.getBigDecimal("ni_tot_job_disattivi2").intValue() : 0; int niTotJobNuovi2 = infoJobFotoRowBean.getBigDecimal("ni_tot_job_nuovi2") != null ? infoJobFotoRowBean.getBigDecimal("ni_tot_job_nuovi2").intValue() : 0; int niTotJobSoloFoto = infoJobFotoRowBean.getBigDecimal("ni_tot_job_solo_foto") != null ? infoJobFotoRowBean.getBigDecimal("ni_tot_job_solo_foto").intValue() : 0; Date dataLastFoto = infoJobFotoRowBean.getTimestamp("last_job_foto"); DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); getForm().getGestioneJobInfo2().getNi_tot_job_presenti2().setValue("" + niTotJobPresenti2); getForm().getGestioneJobInfo2().getNi_tot_job_attivi2().setValue("" + niTotJobAttivi2); getForm().getGestioneJobInfo2().getNi_tot_job_disattivi2().setValue("" + niTotJobDisattivi2); getForm().getGestioneJobInfo2().getNi_tot_job_nuovi2().setValue("" + niTotJobNuovi2); getForm().getGestioneJobInfo2().getNi_tot_job_solo_foto().setValue("" + niTotJobSoloFoto); getForm().getInfoJob2Section().setLegend("Foto dei job alla data " + df.format(dataLastFoto)); } @Override public void startMassivoGestioneJob() throws EMFError { // Recupero i record selezionati getForm().getGestioneJobRicercaList().post(getRequest()); BaseTable tabella = (BaseTable) getForm().getGestioneJobRicercaList().getTable(); if (tabella != null) { ArrayList<Object[]> listaSelezionati = new ArrayList<>(); ArrayList<Object[]> listaNonSelezionati = new ArrayList<>(); ArrayList<Object[]> listaNoTimer = new ArrayList<>(); boolean almenoUnoSel = false; for (int i = 0; i < tabella.size(); i++) { BaseRow riga = tabella.getRow(i); if (riga.getString("job_selezionati").equals("1")) { almenoUnoSel = true; Object[] jobDaValutare = new Object[3]; jobDaValutare[0] = i; jobDaValutare[1] = riga.getString("nm_job"); jobDaValutare[2] = riga.getString("ds_job"); if (riga.getString("stato_job").equals("DISATTIVO")) { if (riga.getString("ti_sched_job").equals("NO_TIMER")) { listaNoTimer.add(jobDaValutare); } else { listaSelezionati.add(jobDaValutare); } } else { listaNonSelezionati.add(jobDaValutare); } } } if (almenoUnoSel) {// listaSelezionati String message = ""; String jobSchedulatiString = ""; for (Object[] obj : listaSelezionati) { startGestioneJobOperation((int) obj[0], (String) obj[1], (String) obj[2]); jobSchedulatiString = jobSchedulatiString + (String) obj[1] + "<br>"; } if (!jobSchedulatiString.equals("")) { message = "Sono stati schedulati i seguenti job: <br><br>" + jobSchedulatiString + "<br>"; } String jobNonSchedulatiString = ""; for (Object[] obj : listaNonSelezionati) { jobNonSchedulatiString = jobNonSchedulatiString + (String) obj[1] + "<br>"; } if (!jobNonSchedulatiString.equals("")) { message = message + "<br>Non sono stati schedulati i seguenti job: <br><br>" + jobNonSchedulatiString + "<br> in quanto in stato già ATTIVO o IN_ELABORAZIONE<br>"; } String jobNoTimerString = ""; for (Object[] obj : listaNoTimer) { jobNoTimerString = jobNoTimerString + (String) obj[1] + "<br>"; } if (!jobNoTimerString.equals("")) { message = message + "<br>Non sono stati schedulati i seguenti job: <br><br>" + jobNoTimerString + "<br> in quanto di tipo NO_TIMER. Per essi è possibile lanciare solo l'ESECUZIONE SINGOLA<br>"; } getMessageBox().clear(); getMessageBox().setViewMode(ViewMode.alert); getMessageBox() .addInfo(message + "L'operazione richiesta diventerà effettiva entro il prossimo minuto."); } else { getMessageBox().addInfo("Nessun job selezionato"); } } else { getMessageBox().addInfo("Nessun job selezionato"); } popolaInformazioniJob(); ricercaGestioneJob(); } @Override public void stopMassivoGestioneJob() throws EMFError { // Recupero i record selezionati getForm().getGestioneJobRicercaList().post(getRequest()); BaseTable tabella = (BaseTable) getForm().getGestioneJobRicercaList().getTable(); if (tabella != null) { ArrayList<Object[]> listaSelezionati = new ArrayList<>(); ArrayList<Object[]> listaNonSelezionati = new ArrayList<>(); ArrayList<Object[]> listaNoTimer = new ArrayList<>(); boolean almenoUnoSel = false; for (int i = 0; i < tabella.size(); i++) { BaseRow riga = tabella.getRow(i); if (riga.getString("job_selezionati").equals("1")) { almenoUnoSel = true; Object[] jobDaValutare = new Object[3]; jobDaValutare[0] = i; jobDaValutare[1] = riga.getString("nm_job"); jobDaValutare[2] = riga.getString("ds_job"); if (riga.getString("stato_job").equals("ATTIVO")) { if (riga.getString("ti_sched_job").equals("NO_TIMER")) { listaNoTimer.add(jobDaValutare); } else { listaSelezionati.add(jobDaValutare); } } else { listaNonSelezionati.add(jobDaValutare); } } } if (almenoUnoSel) { String jobSchedulatiString = ""; String message = ""; for (Object[] obj : listaSelezionati) { stopGestioneJobOperation((int) obj[0], (String) obj[1], (String) obj[2]); jobSchedulatiString = jobSchedulatiString + (String) obj[1] + "<br>"; } if (!jobSchedulatiString.equals("")) { message = "Sono stati stoppati i seguenti job: <br><br>" + jobSchedulatiString + "<br>"; } String jobNonSchedulatiString = ""; for (Object[] obj : listaNonSelezionati) { jobNonSchedulatiString = jobNonSchedulatiString + (String) obj[1] + "<br>"; } if (!jobNonSchedulatiString.equals("")) { message = message + "<br>Non sono stati stoppati i seguenti job: <br><br>" + jobNonSchedulatiString + "<br> in quanto in stato già DISATTIVO o IN_ESECUZIONE<br>"; } String jobNoTimerString = ""; for (Object[] obj : listaNoTimer) { jobNoTimerString = jobNoTimerString + (String) obj[1] + "<br>"; } if (!jobNoTimerString.equals("")) { message = message + "<br>Non sono stati stoppati i seguenti job: <br><br>" + jobNoTimerString + "<br> in quanto di tipo NO_TIMER<br>"; } getMessageBox().clear(); getMessageBox().setViewMode(ViewMode.alert); getMessageBox() .addInfo(message + "L'operazione richiesta diventerà effettiva entro il prossimo minuto."); } else { getMessageBox().addInfo("Nessun job selezionato"); } } else { getMessageBox().addInfo("Nessun job selezionato"); } popolaInformazioniJob(); ricercaGestioneJob(); } @Override public void esecuzioneSingolaMassivaGestioneJob() throws EMFError { // Recupero i record selezionati getForm().getGestioneJobRicercaList().post(getRequest()); BaseTable tabella = (BaseTable) getForm().getGestioneJobRicercaList().getTable(); if (tabella != null) { ArrayList<Object[]> listaSelezionati = new ArrayList<>(); ArrayList<Object[]> listaNonSelezionati = new ArrayList<>(); boolean almenoUnoSel = false; for (int i = 0; i < tabella.size(); i++) { BaseRow riga = tabella.getRow(i); if (riga.getString("job_selezionati").equals("1")) { almenoUnoSel = true; Object[] jobDaValutare = new Object[3]; jobDaValutare[0] = i; jobDaValutare[1] = riga.getString("nm_job"); jobDaValutare[2] = riga.getString("ds_job"); if (riga.getString("stato_job").equals("DISATTIVO")) { listaSelezionati.add(jobDaValutare); } else { listaNonSelezionati.add(jobDaValutare); } } } if (almenoUnoSel) { String jobSchedulatiString = ""; String message = ""; for (Object[] obj : listaSelezionati) { esecuzioneSingolaGestioneJobOperation((int) obj[0], (String) obj[1], (String) obj[2]); jobSchedulatiString = jobSchedulatiString + (String) obj[1] + "<br>"; } if (!jobSchedulatiString.equals("")) { message = "Sono stati attivati in esecuzione singola i seguenti job: <br><br>" + jobSchedulatiString + "<br>"; } String jobNonSchedulatiString = ""; for (Object[] obj : listaNonSelezionati) { jobNonSchedulatiString = jobNonSchedulatiString + (String) obj[1] + "<br>"; } if (!jobNonSchedulatiString.equals("")) { message = message + "<br>Non sono stati attivati in esecuzione singola i seguenti job: <br><br>" + jobNonSchedulatiString + "<br> in quanto in stato già ATTIVO o IN_ESECUZIONE<br>"; } getMessageBox().clear(); getMessageBox().setViewMode(ViewMode.alert); getMessageBox() .addInfo(message + "L'operazione richiesta diventerà effettiva entro il prossimo minuto."); } else { getMessageBox().addInfo("Nessun job selezionato"); } } else { getMessageBox().addInfo("Nessun job selezionato"); } popolaInformazioniJob(); ricercaGestioneJob(); } @Override public void salvaFotoGestioneJob() throws EMFError { // Eseguo il salvataggio foto, solo se ho almeno 1 JOB attivo BaseTable tabella = (BaseTable) getForm().getGestioneJobListPerAmm().getTable(); boolean trovatoAttivo = false; for (BaseRow riga : tabella) { if (riga.getString("stato_job").equals("ATTIVO")) { trovatoAttivo = true; break; } } if (trovatoAttivo) { gestioneJobEjb.salvaFoto(); getSession().setAttribute("fotoSalvata", true); getMessageBox().addInfo("Foto JOB salvata con successo!"); } else { getMessageBox().addInfo("Nessun JOB attivo trovato: non è stata salvata la foto!"); } tabAmmJobTabOnClick(); abilitaDisabilitaBottoniJob(!gestioneJobEjb.isDecJobFotoEmpty() && gestioneJobEjb.areAllJobsDisattivati(), getSession().getAttribute("fotoSalvata") != null); } @Override public void ripristinaFotoGestioneJob() throws EMFError { gestioneJobEjb.ripristinaFotoGestioneJob(); tabAmmJobTabOnClick(); getMessageBox().addInfo( "Ripristino foto effettuato con successo! Attendere il minuto successivo per l'allineamento dei JOB eventualmente rischedulati"); forwardToPublisher(getLastPublisher()); } @Override public void ricaricaGestioneJob() throws EMFError { tabAmmJobTabOnClick(); } public void abilitaDisabilitaBottoniJob(boolean abilitaRipristinaFoto, boolean abilitaDisabilitaAllJobs) { if (abilitaRipristinaFoto) { getForm().getGestioneJobInfo2().getRipristinaFotoGestioneJob().setReadonly(false); getSession().setAttribute("visualizzaRipristinaFoto", true); } else { getForm().getGestioneJobInfo2().getRipristinaFotoGestioneJob().setReadonly(true); getSession().removeAttribute("visualizzaRipristinaFoto"); } if (abilitaDisabilitaAllJobs) { getForm().getGestioneJobInfo().getDisabilitaAllJobs().setReadonly(false); } else { getForm().getGestioneJobInfo().getDisabilitaAllJobs().setReadonly(true); } } public void apriVisualizzaSchedulazioniJob() throws EMFError { Integer riga = Integer.parseInt(getRequest().getParameter("riga")); String nmJob = ((BaseTable) getForm().getGestioneJobRicercaList().getTable()).getRow(riga).getString("nm_job"); redirectToSchedulazioniJob(nmJob); } private void redirectToSchedulazioniJob(String nmJob) throws EMFError { MonitoraggioForm form = prepareRedirectToSchedulazioniJob(nmJob); redirectToPage(Application.Actions.MONITORAGGIO, form, form.getJobSchedulatiList().getName(), getForm().getGestioneJobRicercaList().getTable(), getNavigationEvent()); } private MonitoraggioForm prepareRedirectToSchedulazioniJob(String nmJob) throws EMFError { MonitoraggioForm form = new MonitoraggioForm(); /* Preparo la pagina di destinazione */ form.getFiltriJobSchedulati().setEditMode(); DecodeMap dec = ComboGetter.getMappaSortedGenericEnum("nm_job", JobConstants.JobEnum.values()); dec.keySet().remove(JobConstants.JobEnum.PREPARA_PARTIZIONE_DA_MIGRARE.name()); dec.keySet().remove(JobConstants.JobEnum.PRODUCER_CODA_DA_MIGRARE.name()); form.getFiltriJobSchedulati().getNm_job().setDecodeMap(dec); /* Setto il valore del Job da cercare in Visualizzazione Job Schedulati */ form.getFiltriJobSchedulati().getNm_job().setValue(nmJob); // Preparo la data di Schedulazione Da una settimana prima rispetto la data corrente Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, -7); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); DateFormat f = new SimpleDateFormat("dd/MM/yyyy"); form.getFiltriJobSchedulati().getDt_reg_log_job_da().setValue(f.format(c.getTime())); getSession().setAttribute("fromGestioneJob", true); return form; } // redirectToPage private void redirectToPage(final String action, BaseForm form, String listToPopulate, BaseTableInterface<?> table, String event) throws EMFError { ((it.eng.spagoLite.form.list.List<SingleValueField<?>>) form.getComponent(listToPopulate)).setTable(table); redirectToAction(action, "?operation=ricercaJobSchedulati", form); } // public public void startGestioneJobOperation() throws EMFError { // Recupero la riga sulla quale ho cliccato Start Integer riga = Integer.parseInt(getRequest().getParameter("riga")); // Eseguo lo start del job interessato String nmJob = getForm().getGestioneJobRicercaList().getTable().getRow(riga).getString("nm_job"); String dsJob = getForm().getGestioneJobRicercaList().getTable().getRow(riga).getString("ds_job"); startGestioneJobOperation(riga, nmJob, dsJob); getRequest().setAttribute("fromListaPrinc", true); ricercaGestioneJob(); } public void startGestioneJobOperation(int riga, String nmJob, String dsJob) throws EMFError { // Eseguo lo start del job interessato setJobVBeforeOperation(nmJob, riga); eseguiNuovo(nmJob, dsJob, null, OPERAZIONE.START); } public void stopGestioneJobOperation() throws EMFError { // Recupero la riga sulla quale ho cliccato Start Integer riga = Integer.parseInt(getRequest().getParameter("riga")); // Eseguo lo start del job interessato String nmJob = getForm().getGestioneJobRicercaList().getTable().getRow(riga).getString("nm_job"); String dsJob = getForm().getGestioneJobRicercaList().getTable().getRow(riga).getString("ds_job"); stopGestioneJobOperation(riga, nmJob, dsJob); getRequest().setAttribute("fromListaPrinc", true); ricercaGestioneJob(); } public void stopGestioneJobOperation(int riga, String nmJob, String dsJob) throws EMFError { // Eseguo lo start del job interessato setJobVBeforeOperation(nmJob, riga); eseguiNuovo(nmJob, dsJob, null, OPERAZIONE.STOP); } public void esecuzioneSingolaGestioneJobOperation() throws EMFError { // Recupero la riga sulla quale ho cliccato Start Integer riga = Integer.parseInt(getRequest().getParameter("riga")); // Eseguo lo start del job interessato String nmJob = getForm().getGestioneJobRicercaList().getTable().getRow(riga).getString("nm_job"); String dsJob = getForm().getGestioneJobRicercaList().getTable().getRow(riga).getString("ds_job"); esecuzioneSingolaGestioneJobOperation(riga, nmJob, dsJob); getRequest().setAttribute("fromListaPrinc", true); ricercaGestioneJob(); } public void esecuzioneSingolaGestioneJobOperation(int riga, String nmJob, String dsJob) throws EMFError { // Eseguo lo start del job interessato setJobVBeforeOperation(nmJob, riga); eseguiNuovo(nmJob, dsJob, null, OPERAZIONE.ESECUZIONE_SINGOLA); } @Override public void totJobOperation() throws EMFError { ricercaGestioneJob(); forwardToPublisher(getLastPublisher()); } @Override public void totJobAttiviOperation() throws EMFError { String[] attivi = new String[1]; attivi[0] = "ATTIVO"; getRequest().setAttribute("fromLink", true); getForm().getGestioneJobRicercaFiltri().getDs_job().setValue(""); getForm().getGestioneJobRicercaFiltri().getNm_ambito().setValue(""); getForm().getGestioneJobRicercaFiltri().getTi_stato_job().setValues(attivi); ricercaGestioneJob(); forwardToPublisher(getLastPublisher()); } @Override public void totJobDisattiviOperation() throws EMFError { String[] disattivi = new String[1]; disattivi[0] = "DISATTIVO"; getRequest().setAttribute("fromLink", true); getForm().getGestioneJobRicercaFiltri().getDs_job().setValue(""); getForm().getGestioneJobRicercaFiltri().getNm_ambito().setValue(""); getForm().getGestioneJobRicercaFiltri().getTi_stato_job().setValues(disattivi); ricercaGestioneJob(); forwardToPublisher(getLastPublisher()); } @Override public void disabilitaAllJobs() throws EMFError { gestioneJobEjb.disabilitaAllJobs(); tabAmmJobTabOnClick(); getMessageBox().addInfo("Tutti i job disattivati con successo!"); forwardToPublisher(getLastPublisher()); } private void eseguiNuovo(String nomeJob, String descrizioneJob, String nomeApplicazione, OPERAZIONE operazione) throws EMFError { // Messaggio sul logger di sistema StringBuilder info = new StringBuilder(descrizioneJob); info.append(": ").append(operazione.description()).append(" [").append(nomeJob); if (nomeApplicazione != null) { info.append("_").append(nomeApplicazione); } info.append("]"); LOG.info(info.toString()); String message = "Errore durante la schedulazione del job"; switch (operazione) { case START: jbossTimerEjb.start(nomeJob, null); message = descrizioneJob + ": job correttamente schedulato. L'operazione richiesta verrà schedulata correttamente entro il prossimo minuto."; break; case ESECUZIONE_SINGOLA: jbossTimerEjb.esecuzioneSingola(nomeJob, null); message = descrizioneJob + ": job correttamente schedulato per esecuzione singola. L'operazione richiesta verrà effettuata entro il prossimo minuto."; break; case STOP: jbossTimerEjb.stop(nomeJob); message = descrizioneJob + ": schedulazione job annullata. L'operazione richiesta diventerà effettiva entro il prossimo minuto."; break; } // Segnalo l'avvenuta operazione sul job getMessageBox().addMessage(new Message(MessageLevel.INF, message)); getMessageBox().setViewMode(ViewMode.plain); } public void setJobVBeforeOperation(String nmJob, int riga) throws EMFError { Timestamp dataAttivazioneJob = getActivationDateJob(nmJob); StatoJob statoJob = new StatoJob(nmJob, null, null, null, null, null, null, null, dataAttivazioneJob); gestisciStatoJobNuovo(statoJob); } private boolean gestisciStatoJobNuovo(StatoJob statoJob) throws EMFError { // se non è ancora passato un minuto da quando è stato premuto un pulsante non posso fare nulla return jbossTimerEjb.isEsecuzioneInCorso(statoJob.getNomeJob()); } // </editor-fold> }
import { pgTable, text, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; import { sql } from "drizzle-orm"; export const users = pgTable("users", { id: uuid("id") .primaryKey() .default(sql`uuid_generate_v4()`), userName: varchar("username", { length: 15 }).notNull().unique(), password: text("password").notNull(), createdAt: timestamp("created_at").notNull().defaultNow(), }); export const messages = pgTable("messages", { id: uuid("id") .primaryKey() .default(sql`uuid_generate_v4()`), message: text("message").notNull(), recipientId: uuid("recipient_id").references(() => users.id), senderId: uuid("sender_id").references(() => users.id), dateSent: timestamp("created_at").notNull().defaultNow(), });
Title: Gestures ---- Text: # Gestures Any tap, swipe, drag, pinch, or otherwise interaction with the screen with one or more fingers is a possible gesture that can be used to make changes in Graphic. Here is a list with the most common gestures in Graphic and some examples of their use: (image: gestures1-ipad.jpg width: 750) #### Pinch to Zoom Place two fingers on the screen, usually the thumb and the index finger, and move them together to zoom out or move them apart to zoom in on the canvas. #### Two-Finger Scrolling Place two fingers on the canvas, keep them pressed and drag them to navigate on the canvas without zooming in or out. (video: gestures2-ipad.mp4 width: 750) #### Tap to Select Use one finger to quickly touch the screen in one spot. Tap to select objects on the canvas, open or close menus and panels, select tools from the Toolbar, apply commands and effects, or simply open documents. (video: gestures3-ipad.mp4 width: 750) #### Double Tap Use one finger to quickly touch the screen two times in one spot. Use this gesture to add or edit text, finish editing paths or to rename layers and objects. (video: gestures4-ipad.mp4 width: 750) #### Tap & Hold Use one finger to tap the screen in one spot and keep it pressed. This gesture can be used to open the context menu when working on the canvas or to remove colors, gradients and patterns from their palettes. (video: gestures5-ipad.mp4 width: 750) #### Tap & Drag Place one finger on the screen and drag immediately. This simple gesture can be used for: • **Adjusting**: Drag any of the slider buttons to adjust the setting it controls. • **Drawing**: draw (link: LINK text: _**lines**_), (link: docs-ipad/shapes/arcs text: _**arcs**_), (link: docs-ipad/shapes/ellipses text: _**ellipses**_), (link: docs-ipad/shapes/rectangles text: _**rectangles**_), (link: docs-ipad/shapes/rounded-rectangles text: _**rounded rectangles**_), (link: docs-ipad/shapes/polygons text: _**polygons**_), (link: docs-ipad/shapes/stars text: _**stars**_), (link: docs-ipad/paths/freehand-paths text: _**freehand paths**_) or (link: docs-ipad/brushes/creating-brush-strokes text: _**calligraphic brushes**_). • **Erasing**: erase objects using the (link: docs-ipad/adjusting-objects/erasing-objects text: _**Eraser tool**_). • **Selecting**: create selection marquees to select (link: docs-ipad/adjusting-objects/selecting-objects#boundingbox text: _**objects**_) or (link: docs-ipad/paths/editing-path-points#selectmultiple text: _**path points**_). • **Movement**: move selected (link: docs-ipad/adjusting-objects/moving-objects text: _**objects**_) or (link: docs-ipad/paths/editing-path-points text: _**path points**_). • **Rotating**: rotate (link: docs-ipad/adjusting-objects/rotating-objects text: _**objects**_) or (link: docs-ipad/paths/rotating-path-points text: _**path points**_) using the bounding box or the Rotate tool. • **Scaling**: scale (link: docs-ipad/adjusting-objects/scaling-objects text: _**objects**_) or (link: docs-ipad/paths/scaling-path-points text: _**path points**_) using the bounding box or the Scale tool. • **Slanting**: slant (link: docs-ipad/adjusting-objects/slanting-objects text: _**objects**_) or (link: docs-ipad/paths/slanting-path-points text: _**path points**_) using the Shear tool. • **Add Shapes**: add a shape from the (link: docs-ipad/shape-libraries#addshape text: **Shape Libraries panel**) in a specific spot. #### Tap & Hold + Drag Use one finger to tap the screen in one spot and keep it pressed, and then drag. This gesture can be used to: • **Move Documents**: (link: docs-ipad/documents/creating-folders text: **isolate documents**) and move them inside a folder . • **Move Layers or Objects**: (link: docs-ipad/layers/moving-layers text: **isolate layers or objects**) inside the Layers panel and move them. #### Tap & Drag + Tap & Hold Use one finger to tap and drag. While dragging, tap and hold with a second finger. This gesture is the equivalent of holding the **Shift ⇧** key on a Mac. It can be used to constrain the behavior of the following actions: • **Drawing**: draw straight, (link: docs-ipad/shapes/lines#lines text: _**horizontal or vertical lines**_), (link: docs-ipad/shapes/ellipses text: _**circles**_) and (link: docs-ipad/shapes/rectangles text: _**squares**_). • **Movement**: (link: docs-ipad/adjusting-objects/moving-objects text: _**constrain the movement**_) of objects in a horizontal and vertical direction. • **Rotating**: (link: docs-ipad/adjusting-objects/rotating-objects text: _**constrain the rotation**_) to 15˚ increments. • **Scaling and Slanting**: (link: docs-ipad/adjusting-objects/scaling-objects text: _**scale**_) and (link: docs-ipad/adjusting-objects/slanting-objects text: _**slant**_) in a horizontal and vertical direction. • **Path Selection tool**: move (link: docs-ipad/paths/editing-path-points#modifycurves text: _**path points**_) or (link: docs-ipad/paths/editing-path-points#modifycurves text: _**path handles**_) independently. • **Pen tool**: create curved paths and move (link: http://www.graphic.com/docs-ipad/paths/creating-paths#creatingpaths text: _**path handles**_) independently. #### Tap & Drag + Two Fingers Tap & Hold Use one finger to tap and drag. While dragging, tap and hold with a second and a third finger. This gesture is the equivalent of holding the **Shift ⇧** and **Option ⌥** keys on a Mac. It can be used to constrain the behavior of the following actions: • **Movement**: (link: docs-ipad/paths/editing-path-points#selectmultiple text: _**constrain the movement**_) of anchor points in a horizontal and vertical direction. • **Scaling**: (link: docs-ipad/adjusting-objects/scaling-objects#scaleboundingbox text: _**scale objects**_) from the center of the bounding box in a horizontal or vertical direction . Besides these somewhat classic gestures, there are another three (link: docs-ipad/gestures/customize-gestures text: _**customizable gestures**_).
using Microsoft.EntityFrameworkCore; // NuGet Microsoft.EntityFrameworkCore using Microsoft.Extensions.Options; // NuGet Microsoft.EntityFrameworkCore.SqlServer using Microsoft.VisualStudio.TestTools.UnitTesting; using MoviesRepositoryLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace MoviesRepositoryLib.Tests { [TestClass] public class MoviesRepository2Tests { private const bool useDatabase = true; private static IMoviesRepository _repo; // https://learn.microsoft.com/en-us/dotnet/core/testing/order-unit-tests?pivots=mstest [ClassInitialize] public static void InitOnce(TestContext context) { if (useDatabase) { var optionsBuilder = new DbContextOptionsBuilder<MoviesDbContext>(); optionsBuilder.UseSqlServer(Secrets.ConnectionStringSimply); // connection string structure // "Data Source=mssql7.unoeuro.com;Initial Catalog=FROM simply.com;Persist Security Info=True;User ID=FROM simply.com;Password=DB PASSWORD FROM simply.com;TrustServerCertificate=True" MoviesDbContext _dbContext = new(optionsBuilder.Options); // clean database table: remove all rows _dbContext.Database.ExecuteSqlRaw("TRUNCATE TABLE dbo.Movies"); _repo = new MoviesRepositoryDB(_dbContext); } else { _repo = new MoviesRepositoryList(); } } // Test methods are execute in alphabetical order [TestMethod] public void AddTest() { _repo.Add(new Movie { Title = "Z", Year = 1895 }); Movie snowWhite = _repo.Add(new Movie { Title = "Snehvide", Year = 1937 }); Assert.IsTrue(snowWhite.Id >= 0); IEnumerable<Movie> all = _repo.Get(); Assert.AreEqual(2, all.Count()); Assert.ThrowsException<ArgumentNullException>( () => _repo.Add(new Movie { Title = null, Year = 1895 })); Assert.ThrowsException<ArgumentException>( () => _repo.Add(new Movie { Title = "", Year = 1895 })); Assert.ThrowsException<ArgumentOutOfRangeException>( () => _repo.Add(new Movie { Title = "B", Year = 1894 })); } [TestMethod()] public void GetTest() { IEnumerable<Movie> movies = _repo.Get(orderBy: "Title"); Assert.AreEqual(movies.First().Title, "Snehvide"); movies = _repo.Get(orderBy: "Year"); Assert.AreEqual(movies.First().Title, "Z"); movies = _repo.Get(titleIncludes: "vide"); Assert.AreEqual(1, movies.Count()); Assert.AreEqual(movies.First().Title, "Snehvide"); } [TestMethod] public void GetByIdTest() { Movie m = _repo.Add(new Movie { Title = "Tarzan", Year = 1932 }); Movie? movie = _repo.GetById(m.Id); Assert.IsNotNull(movie); Assert.AreEqual("Tarzan", movie.Title); Assert.AreEqual(1932, movie.Year); Assert.IsNull(_repo.GetById(-1)); } [TestMethod] public void RemoveTest() { Movie m = _repo.Add(new Movie { Title = "Olsenbanden", Year = 1968 }); Movie? movie = _repo.Remove(m.Id); Assert.IsNotNull(movie); Assert.AreEqual("Olsenbanden", movie.Title); Movie? movie2 = _repo.Remove(m.Id); Assert.IsNull(movie2); } [TestMethod] public void UpdateTest() { Movie m = _repo.Add(new Movie { Title = "Citizen Kane", Year = 1941 }); Movie? movie = _repo.Update(m.Id, new Movie { Title = "Den Store Mand", Year = 1941 }); Assert.IsNotNull(movie); Movie? movie2 = _repo.GetById(m.Id); Assert.AreEqual("Den Store Mand", movie.Title); Assert.IsNull( _repo.Update(-1, new Movie { Title = "Buh", Year = 1967 })); Assert.ThrowsException<ArgumentException>( () => _repo.Update(m.Id, new Movie { Title = "", Year = 1941 })); } } }
import streamlit as st import pandas as pd import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from transformers import BertTokenizer, BertModel, AdamW, get_linear_schedule_with_warmup from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.metrics import accuracy_score, classification_report import numpy as np from torch.utils.data import DataLoader, Dataset class TextClassificationDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_length): self.texts = texts self.labels = labels self.tokenizer = tokenizer self.max_length = max_length def __len__(self): return len(self.texts) def __getitem__(self, idx): text = self.texts[idx] label = self.labels[idx] encoding = self.tokenizer(text, return_tensors='pt', max_length=self.max_length, padding='max_length', truncation=True) return {'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(), 'label': torch.tensor(label)} class BERTClassifier(nn.Module): def __init__(self, bert_model_name, num_classes): super(BERTClassifier, self).__init__() self.bert = BertModel.from_pretrained(bert_model_name) self.dropout = nn.Dropout(0.1) self.fc = nn.Linear(self.bert.config.hidden_size, num_classes) def forward(self, input_ids, attention_mask): outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask) pooled_output = outputs.pooler_output x = self.dropout(pooled_output) logits = self.fc(x) return logits def train(model, data_loader, optimizer, scheduler, device): model.train() for batch in data_loader: optimizer.zero_grad() input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['label'].to(device) outputs = model(input_ids=input_ids, attention_mask=attention_mask) loss = nn.CrossEntropyLoss()(outputs, labels) loss.backward() optimizer.step() scheduler.step() def evaluate(model, data_loader, device): model.eval() predictions = [] actual_labels = [] with torch.no_grad(): for batch in data_loader: input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['label'].to(device) outputs = model(input_ids=input_ids, attention_mask=attention_mask) _, preds = torch.max(outputs, dim=1) predictions.extend(preds.cpu().tolist()) actual_labels.extend(labels.cpu().tolist()) return accuracy_score(actual_labels, predictions), classification_report(actual_labels, predictions) # Streamlit UI st.title("BERT Text Classification with Streamlit") data_file = st.file_uploader("Upload your CSV file", type=["csv"]) if data_file is not None: data = pd.read_csv(data_file) if 'text' in data.columns and 'label' in data.columns: st.write("Data successfully loaded!") bert_model_name = 'bert-base-uncased' num_classes = 2 max_length = 128 batch_size = 16 num_epochs = 4 learning_rate = 2e-5 train_texts, val_texts, train_labels, val_labels = train_test_split(data['text'].tolist(), data['label'].tolist(), test_size=0.2, random_state=42) print(len(train_texts), len(train_labels)) tokenizer = BertTokenizer.from_pretrained(bert_model_name) train_dataset = TextClassificationDataset(train_texts, train_labels, tokenizer, max_length) val_dataset = TextClassificationDataset(val_texts, val_labels, tokenizer, max_length) train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) val_dataloader = DataLoader(val_dataset, batch_size=batch_size) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = BERTClassifier(bert_model_name, num_classes).to(device) optimizer = AdamW(model.parameters(), lr=learning_rate) total_steps = len(train_dataloader) * num_epochs scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_steps) if st.button("Train Model"): for epoch in range(num_epochs): print(f"Epoch {epoch + 1}/{num_epochs}") train(model, train_dataloader, optimizer, scheduler, device) accuracy, report = evaluate(model, val_dataloader, device) print(f"Validation Accuracy: {accuracy:.4f}") print(report) st.success("Model trained successfully!") if st.button("Save Trained Model"): torch.save(model.state_dict(), "bert_classifier.pth") #save_model(model, label_encoder) st.success("Model and label encoder saved successfully!") else: st.error("CSV must include 'text' and 'label' columns") else: st.warning("Please upload a CSV file to proceed.")
"use client"; import { AppContainer, ConductorForm, ConductorList } from "@/components"; import { Conductor } from "@/shared/interfaces/conductor.interface"; import { ConductorService } from "@/shared/services"; import { useState } from "react"; import useSWR from "swr"; const ConductorPage = () => { const { data, error } = useSWR("/v1/condutor", fetchConductors); const [filteredItems, setFilteredItems] = useState<Conductor[]>(); const handleFilter = (searchTerm: string) => { if (!searchTerm) { setFilteredItems(undefined); return; } const filteredItems = data?.filter((conductor) => { return ( conductor.nome.toLowerCase().includes(searchTerm) || conductor.numeroHabilitacao.toLowerCase().includes(searchTerm) ); }); setFilteredItems(filteredItems); }; return ( <AppContainer hasError={error} title="Condutores"> <ConductorForm /> <ConductorList conductors={filteredItems ?? data} handleFilter={handleFilter} /> </AppContainer> ); }; export default ConductorPage; const fetchConductors = async () => { const { data } = await ConductorService().getAll(); return data; };
--- layout: note title: 函数柯里化作用 excerpt: Read more... date: 2022-5-29 14:17:11 updated: 2022-5-29 14:17:11 comments: false lang: zh-CN --- 1. 参数复用 ```js function checkDigital(reg) { return function(string) { return reg.test(string) } } let checkFunction = checkDigital(/\d+/g) checkFunction('test1') // true checkFunction('testtest') // false ``` 2. 提前确认 ```js const on = ( function() { if(document.addEventListener) { return document.addEventListener } else { } } )() ``` 3. 延迟运行 ```js Function.prototype.bind = function (context) { var _this = this var args = Array.prototype.slice.call(arguments, 1) return function() { return _this.apply(context, args) } } ```
--- authors: - finn date: 2023-11-04 categories: - ElementUI --- # 正确认识ElementUI中prop的作用 在 Vue 中,通过使用 v-model 指令与表单组件实现表单数据的双向绑定。但是在 Element UI 中的 el-form 和 el-form-item 组件中,我们还需要使用 prop 属性来指定表单域对应的数据字段名。 本篇文章从该问题入手,介绍 Element UI 中的 prop 属性。 <!-- more --> !!! Question "起源" **为什么`el-input`绑定了数据,`el-form` 和 `el-form-item` 还需要绑定?** 在 Vue 中,表单数据是通过 v-model 指令与组件进行绑定的。在示例中,el-input 组件通过 v-model="formData.name" 和 formData 对象中的 name 字段进行了双向绑定。 但是,在 Element UI 的 el-form 和 el-form-item 组件中,需要显式地指定表单域对应的数据字段名(即 prop 属性),这是因为 el-form 和 el-form-item 组件主要用于表单验证和提交操作。 通过指定 prop 属性,可以将表单域与数据模型之间建立起联系,方便进行表单验证、数据提交等操作。例如,在表单验证时,我们可以根据表单域的 prop 属性定义验证规则,从而确保用户输入的数据符合要求。 此外,通过指定 prop 属性,还可以建立对应关系,方便进行表单数据的初始化、重置等操作。这使得我们能够更加方便地操作表单数据,提高了开发效率。 综上所述,虽然 el-input 组件已经通过 v-model 与表单数据进行了绑定,但是为了方便表单验证、数据提交等操作,我们仍然需要在 el-form-item 中指定 prop 属性来建立表单域与数据模型之间的联系。 ## prop 属性的作用 在 Element UI 的表单组件中,prop 属性用于建立表单域与数据模型之间的联系。它表示表单域对应的数据字段名,可以与 el-form 组件中的 model 属性配合使用,将表单数据与表单域进行绑定。 例如,在 el-form-item 中指定 prop 属性如下: ```html <el-form :model="formData" ref="form"> <el-form-item label="姓名" prop="name"> <el-input v-model="formData.name"></el-input> </el-form-item> </el-form> ``` 在这个例子中,prop 属性的值为 "name",表示该表单域对应的数据字段是 formData 对象中的 name 字段。当用户在输入框中输入姓名时,`formData.name` 的值也会相应地更新。同时,如果 `formData.name` 发生变化,输入框中的内容也会自动更新。 通过 prop 属性,我们可以为表单域建立与数据模型之间的联系,方便进行表单验证、数据提交等操作。 ## prop 属性的应用 在 Element UI 中,prop 属性主要应用于以下几个方面: ### 1. 表单验证 通过指定 prop 属性,我们可以为表单域定义验证规则,确保用户输入的数据符合要求。例如,以下是一个包含两个表单域的 el-form 组件: ```html <el-form :model="formData" :rules="formRules" ref="form"> <el-form-item label="用户名" prop="username"> <el-input v-model="formData.username"></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input type="password" v-model="formData.password"></el-input> </el-form-item> </el-form> ``` 在这个例子中,我们通过在 el-form 上指定 rules 属性来设置整个表单的验证规则。同时,在每个 el-form-item 中也通过 prop 属性分别指定了 username 和 password 这两个表单域的验证规则。 ### 2. 表单初始化 通过指定 prop 属性,我们可以建立表单域与数据模型之间的联系,方便进行表单数据的初始化。例如,以下是一个包含两个表单域的 el-form 组件: ```html <el-form :model="formData" ref="form"> <el-form-item label="姓名" prop="name"> <el-input v-model="formData.name"></el-input> </el-form-item> <el-form-item label="年龄" prop="age"> <el-input type="number" v-model="formData.age"></el-input> </el-form-item> </el-form> ``` 在这个例子中,我们通过在 el-form 组件上指定 model 属性,将表单数据与 formData 对象进行了双向绑定。同时,在每个 el-form-item 中也通过 prop 属性分别指定了 name 和 age 这两个表单域对应的数据字段。 在组件初始化时,可以通过设置 formData 的初始值,来自动为每个表单域初始化默认值。例如,以下是设置 formData 初始值的代码: ```javascript data() { return { formData: { name: '张三', age: 18 } } }, ``` ### 3. 表单提交 通过指定 prop 属性,我们可以建立表单域与数据模型之间的联系,方便进行表单数据的提交。例如,以下是一个包含两个表单域的 el-form 组件: ```html <el-form :model="formData" ref="form" @submit="onSubmit"> <el-form-item label="姓名" prop="name"> <el-input v-model="formData.name"></el-input> </el-form-item> <el-form-item label="年龄" prop="age"> <el-input type="number" v-model="formData.age"></el-input> </el-form-item> <el-form-item> <el-button type="primary" native-type="submit">提交</el-button> </el-form-item> </el-form> ``` 在这个例子中,我们通过在 el-form 组件上指定 model 属性,将表单数据与 formData 对象进行了双向绑定。同时,在每个 el-form-item 中也通过 prop 属性分别指定了 name 和 age 这两个表单域对应的数据字段。 当用户提交表单时,可以在 `onSubmit` 方法中获取 formData 中的数据,进行相关的数据处理和提交操作。例如,以下是 `onSubmit` 方法的代码: ```javascript methods: { onSubmit() { console.log(this.formData) // 输出表单数据 } } ``` 通过以上三个方面的应用,我们可以更加方便地操作表单数据,提高开发效率。同时,通过学习和掌握 prop 属性的使用,可以更好地理解和运用 Vue 和 Element UI 的相关知识点。
/* https://codeforces.com/problemset/problem/1437/D D. Minimal Height Tree time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard output Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode: a = [] # the order in which vertices were processed q = Queue() q.put(1) # place the root at the end of the queue while not q.empty(): k = q.pop() # retrieve the first vertex from the queue a.append(k) # append k to the end of the sequence in which vertices were visited for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order q.put(y) Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order. Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height. The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1. Help Monocarp to find any tree with given visiting order a and minimum height. Input The first line contains a single integer t (1≤t≤1000) — the number of test cases. The first line of each test case contains a single integer n (2≤n≤2⋅105) — the number of vertices in the tree. The second line of each test case contains n integers a1,a2,…,an (1≤ai≤n; ai≠aj; a1=1) — the order in which the vertices were visited by the BFS algorithm. It's guaranteed that the total sum of n over test cases doesn't exceed 2⋅105. Output For each test case print the minimum possible height of a tree with the given visiting order a. */ /* * 模拟建个图,然后再找深度 */ #include <iostream> #include <cstdio> #include <vector> #include <queue> #include <string> #include <string.h> #include <cmath> #define re register #define pb push_back #define cl clear #define MAXN 200005 using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> P; const int INF = 1e9; int head[MAXN], tot; struct Edge{ int u, v, next; }G[MAXN<<1]; inline void addEdge(int u, int v){ G[++tot].u = u; G[tot].v = v; G[tot].next = head[u]; head[u] = tot; } inline int read(){ int x = 0, f = 1; char ch = getchar(); while(ch<'0'||ch>'9'){ if(ch=='-') f = -1; ch = getchar(); } while(ch>='0'&&ch<='9'){ x=(x<<1)+(x<<3)+(ch^48); ch = getchar(); } return x*f; } int n, arr[MAXN], depth[MAXN], ans; bool vis[MAXN]; inline void DFS(int x, int fat){ vis[x] = true; depth[x] = depth[fat] + 1; ans = max(ans,depth[x]); for(re int i = head[x], to ; i ; i = G[i].next){ to = G[i].v; if(!vis[to]){ DFS(to,x); } } } void solve(){ memset(head,0,sizeof(head)); ans = tot = 0; n = read(); for(re int i = 1 ; i <= n ; ++i){ arr[i] = read(); vis[i] = false; depth[i] = 0; } queue<int> q; int last = 1; addEdge(last,arr[2]); addEdge(arr[2],last); q.push(arr[2]); for(re int i = 3 ; i <= n ; ++i){ if(arr[i]<arr[i-1]){ last = q.front(); q.pop(); } addEdge(last,arr[i]); addEdge(arr[i],last); q.push(arr[i]); } DFS(1,0); printf("%d\n",ans-1); } int main(){ int t = 1; t = read(); while(t--) solve(); return 0; }
const bcrypt = require('bcrypt'); const jwt = require('../jwt-to-promise'); const { Router } = require('express'); const secret = 'lapamChushki'; const { body, validationResult } = require('express-validator'); const router = Router(); router.get('/register', (req, res) => { res.render('register', {_title: 'Register Page'}); }); router.post('/register', body('email').trim(), body('password').trim(), body('rePass').trim(), body('username').trim(), body('email', 'Email should be in the following format: <name>@<domain>.<extension>') .isEmail(), body('password', 'Password must be at least 5 characters long') .isLength({ min: 5 }), body('firstName', 'Firstname must be at least 1 characters long') .isLength({min: 1}), body('lastName', 'Lastname must be at least 1 characters long') .isLength({min: 1}), body('rePass', 'Password missmatch.').custom((value, { req }) => value == req.body.password), async (req, res) => { const { email, password, rePass, firstName, lastName } = req.body; const { errors } = validationResult(req); try { if (errors.length > 0) { throw errors; } const salt = await bcrypt.genSalt(3); const hash = await bcrypt.hash(password, salt); const payload = { email }; const user = { email, password: hash, firstName, lastName } const result = await req.userStorage.createData(user); if(result){ const token = await jwt.sign(payload, secret, { expiresIn: '2d' }); res.cookie('token', token); req.user = { email, fullName: `${firstName} ${lastName}` }; res.redirect('/'); }else{ const error = []; error.push({msg: 'This user is already taken!'}); throw error } } catch (error) { console.log(error); res.render('register', { _title: 'Register Page', error, email, firstName, lastName }) } }); router.get('/login', (req, res) => { res.render('login', { _title: 'Login Page' }); }); router.post('/login', body('email', 'Email ist required') .trim() .isLength({ min: 2 }), body('password', 'Password ist required') .trim() .isLength({ min: 4 }), async (req, res) => { const { email , password } = req.body; const { errors } = validationResult(req); try { const user = await req.userStorage.getUser(email); if(!user){ const error = []; error.push({msg: 'Invalid Credentials.'}); throw error; } if(errors.length > 0) { throw errors } const hash = user.password; const isValid = await bcrypt.compare(password, hash); if (isValid) { const payload = { email }; const token = await jwt.sign(payload, secret, { expiresIn: '2d' }); res.cookie('token', token); req.user = user; res.redirect('/'); } else { const error = []; error.push({msg: 'Expired Session. Please Login.'}); throw error; } } catch (error) { console.log(error); res.render('login', {_title: 'Login Page', error, email}); } }); router.get('/logout', (req, res) => { res.clearCookie('token'); req.user = null; res.redirect('/'); }); module.exports = router;
# This example requires the 'message_content' intent. import random import discord token = "" # First line of secrets should be token with open("secrets.txt", "r") as f: token = f.readline() intents = discord.Intents.all() intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hi'): await message.channel.send(f"Hello {message.author}") if message.content.startswith('$ping'): await message.channel.send('pong') if message.content.startswith('$roll'): content = message.content.split()[1] amounts = content.split('d') total = 0 try: for i in range(int(amounts[0])): total += random.randint(1,int(amounts[1])) await message.channel.send(f"You rolled {amounts[0]} {amounts[1]} sided dice for a total of {total}") except Exception as e: # Make bot do nothing if message is in wrong format print(e) pass if message.content.startswith('$rps'): content = (message.content.split()[1]).lower() if content == 'scissors' or content == 'rock' or content == 'paper': result = random.randint(0,2) == 1 if result == 0: await message.channel.send(f"You won!") elif result == 1: await message.channel.send(f"Tie!") else: await message.channel.send(f"You Lost!") client.run(token)
<script lang="ts"> import { fly, fade } from 'svelte/transition'; let visible: boolean = false; export function open() { visible = true; } export function close() { visible = false; } export let content: any; </script> {#if visible} <div class="overlay" transition:fade={{ duration: 500 }} /> <div id="details-pane" transition:fly={{ y: 100, duration: 400, delay: 300 }}> {@html content} <!-- svelte-ignore a11y-missing-attribute --> <!-- svelte-ignore a11y-click-events-have-key-events --> <a class="close-button" role="button" on:click={close}> Close </a> </div> {/if} <style> .close-button { background-color: var(--cornerstonebank-red); color: rgb(255, 255, 255); border: var(--cornerstonebank-red); padding: 1rem 2rem; font-size: 1.2rem; text-decoration: none; cursor: pointer; } .overlay { position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100%; height: 100%; background: hsla(0, 0%, 100%, 0.85); } #details-pane { position: absolute; top: 10%; left: 50%; transform: translateX(-50%); width: clamp(250px, 50%, 640px); background: hsla(0, 0%, 100%, 0.88); display: flex; justify-content: center; align-items: flex-end; flex-direction: column; padding: 2rem; box-shadow: 0 0.25rem 1.25rem 0.25rem hsl(0deg 0% 0% / 30%); } </style>
import React, { Component, forwardRef, useEffect, useState } from "react"; import { Link } from "react-router-dom"; import axios from "axios"; import { ToastContainer, toast } from "react-toastify"; import { Button, Dialog, DialogContent, Fade, Grid, IconButton, Typography, } from "@mui/material"; import { Box } from "@mui/system"; const Author = () => { const [authors, setAuthors] = useState([]); const [openDeleteConfirmationBox, setOpenDeleteConfirmationBox] = useState(false); const [selectedAuthorId, setSelectedAuthorId] = useState(null); useEffect(() => { getAllAuthors(); }, []); const getAllAuthors = () => { axios .get("https://localhost:7186/api/Author") .then((response) => { setAuthors(response.data); }) .catch((error) => { alert("error occured while fetching authors."); }); }; const showDeleteConfirmationBox = (id) => { setOpenDeleteConfirmationBox(true); setSelectedAuthorId(id); }; const cancelDeleteConfirmationBox = () => { setOpenDeleteConfirmationBox(false); }; const onClickDeleteConfirmationBox = () => { if (selectedAuthorId == null) { alert("Author not Selected"); } else { axios .delete( `https://localhost:7186/api/Author?authorId=${selectedAuthorId}` ) .then(getAllAuthors); { setOpenDeleteConfirmationBox(false); } } }; return ( <div> <h1>Authors</h1> <Link to="/create-author" class="btn btn-primary"> Add </Link> <table class="table"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> <th>Actions</th> </tr> </thead> <tbody> {authors.map((x) => { return ( <tr> <td>{x.firstName}</td> <td>{x.lastName}</td> <td>{x.email}</td> <td> <Link to={`/edit-author/${x.id}`} className="btn btn-success"> Edit </Link> <Link onClick={() => showDeleteConfirmationBox(x.id)} class="btn btn-danger" style={{ marginLeft: "5px " }} > Delete </Link> </td> </tr> ); })} </tbody> </table> <Dialog fullWidth open={openDeleteConfirmationBox} maxWidth="md" scroll="body" onClose={cancelDeleteConfirmationBox} //onBackdropClick={closeDialog} //TransitionComponent={Transition} > <DialogContent sx={{ px: 8, py: 6, position: "relative" }}> <IconButton size="medium" onClick={cancelDeleteConfirmationBox} sx={{ position: "absolute", right: "1rem", top: "1rem" }} > X </IconButton> <Grid container spacing={6}> <Grid item xs={12}> <Box sx={{ mb: 3, display: "flex", justifyContent: "flex-start", flexDirection: "column", }} > <Typography variant="h5">Please Confirm!</Typography> <Typography variant="body1"> Are you sure you want to delete this ? </Typography> </Box> </Grid> <Grid item xs={12} sx={{ display: "flex", justifyContent: "flex-end", gap: "1rem", }} > <Button onClick={() => cancelDeleteConfirmationBox()} size="medium" variant="contained" color="primary" > Cancel </Button> <Button onClick={() => onClickDeleteConfirmationBox()} size="medium" variant="contained" color="error" > Confirm </Button>{" "} <ToastContainer /> </Grid> </Grid> </DialogContent> </Dialog> </div> ); }; export default Author;
package com.enkhee.forecastmvvm.data.db import android.content.Context import android.util.Log import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.enkhee.forecastmvvm.data.db.entity.CurrentWeatherEntry import com.enkhee.forecastmvvm.data.db.entity.WeatherLocation @Database( entities = [CurrentWeatherEntry::class, WeatherLocation::class], version = 1 ) abstract class ForecastDatabase : RoomDatabase() { abstract fun currentWeatherDao(): CurrentWeatherDao abstract fun weatherLocationDao(): WeatherLocationDao companion object { @Volatile private var instance: ForecastDatabase? = null private val LOCK = Any() operator fun invoke(context: Context) = instance ?: synchronized(LOCK) { instance ?: buildDatabase(context).also { instance = it } } private fun buildDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, ForecastDatabase::class.java, "futureWeatherEntries") .build() } }
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ToDo } from '../../interfaces/toDoList.model'; @Component ({ selector: 'app-to-do-list-item', templateUrl: './to-do-list-item.component.html', styleUrl: 'to-do-list-item.component.css', standalone: true, imports: [CommonModule] }) export class ToDoListItemComponent { @Input() todo: ToDo = { task: '', completed: false, duration: 0 }; @Output() markCompleted = new EventEmitter<ToDo>(); @Output() removeTodo = new EventEmitter<ToDo>; constructor(){} onMarkCompleted() { this.markCompleted.emit(this.todo); } onRemoveTodo() { this.removeTodo.emit(this.todo); } }
#### Simper analysis on field exclusion data library(tidyverse) library(skimr) library(ggbiplot) library(vegan) library(here) library(permute) theme_set(theme_classic()) # Data Prep --------------------------------------------------------------- exp <- read_csv(here::here("data", "tidy", "field_exclusion_tidy.csv")) exp <- exp %>% mutate(treatment = factor(treatment), region = factor(region), site = factor(site)) %>% unite(interaction, c(region, treatment), sep = "_", remove = F) %>% select(-c(salinity, date, time, month, replicate)) exp_env_data <- exp %>% select(treatment, region, site, interaction) exp_comm_data <- exp %>% select(balanus_no:fucus_pt) mean_abundance <- exp %>% unite(interaction, c(region, treatment), sep = "_", remove = F) %>% group_by(interaction) %>% summarise(across(where(is.numeric), mean)) # Simper ------------------------------------------------------------------ # perm <- how(within = Within(type = "free"), # plots = Plots(strata = exp_env_data$site, type = "free"), # blocks = NULL) # # # simper analysis on salinity region # exp_salinity_species_contributions <- simper(wisconsin(exp_comm_data), group = exp_env_data$region, permutations = perm) # # ## simper analysis on experiment data by treatment # exp_treatment_species_contributions <- simper(wisconsin(exp_comm_data), group = exp_env_data$treatment, permutations = perm) # # # put results in a tibble # salinity_species_contribution <- tibble(species = exp_salinity_species_contributions$High_Low$species, # contribution = exp_salinity_species_contributions$High_Low$average, group = rep("salinity", 12)) # # treatment_species_contribution <- tibble(species = exp_treatment_species_contributions$E_C$species, # contribution = exp_treatment_species_contributions$E_C$average, group = rep("treatment", 12)) # # t1 <- treatment_species_contribution %>% # group_by(group) %>% # slice_max(contribution, n = 4) # # # arrange by highest to lowest contributors # t2 <- salinity_species_contribution %>% # slice_max(contribution, n = 4) # Simper analysis with all 4 groups at once ------------------------------- perm <- how(within = Within(type = "free"), plots = Plots(strata = exp_env_data$site, type = "free"), blocks = NULL) exp_no_grazers <- simper(wisconsin(exp_comm_data), group = exp_env_data$interaction, permutations = perm) ##################### High exclusion vs. High control ##################### he_hc <- summary(exp_no_grazers)$High_exclusion_High_control indices <- which(he_hc$cumsum <= 0.8) taxon <- rownames(he_hc)[indices] avg <- round(he_hc$average[indices]*100, 1) cumsum <- round(he_hc$cumsum[indices]*100, 1) avga <- mean_abundance %>% filter(interaction == "High_exclusion") %>% select(contains(taxon)) %>% t() avgb <- mean_abundance %>% filter(interaction == "High_control") %>% select(contains(taxon)) %>% t() simper_table_1 <- tibble(comparison = c("high salinity - ", "", "high salinity + "), taxon = taxon, `avg contribution (%)` = avg, `cumulative contribution (%)` = cumsum, `mean abundance group a` = avga, `mean abundance group b` = avgb ) ##################### High exclusion vs. Low control ##################### he_lc <- summary(exp_no_grazers)$High_exclusion_Low_control indices <- which(he_lc$cumsum <= 0.8) taxon <- rownames(he_lc)[indices] avg <- round(he_lc$average[indices]*100, 1) cumsum <- round(he_lc$cumsum[indices]*100, 1) avga <- mean_abundance %>% filter(interaction == "High_exclusion") %>% select(contains(taxon)) %>% t() avgb <- mean_abundance %>% filter(interaction == "Low_control") %>% select(contains(taxon)) %>% t() simper_table_2 <- tibble(comparison = c("high salinity - ", "", "low salinity + ", ""), taxon = taxon, `avg contribution (%)` = avg, `cumulative contribution (%)` = cumsum, `mean abundance group a` = avga, `mean abundance group b` = avgb ) ##################### High exclusion vs. Low exclusion ##################### he_le <- summary(exp_no_grazers)$High_exclusion_Low_exclusion indices <- which(he_le$cumsum <= 0.8) taxon <- rownames(he_le)[indices] avg <- round(he_le$average[indices] * 100, 1) cumsum <- round(he_le$cumsum[indices] * 100, 1) avga <- mean_abundance %>% filter(interaction == "High_exclusion") %>% select(contains(taxon)) %>% t() avgb <- mean_abundance %>% filter(interaction == "Low_exclusion") %>% select(contains(taxon)) %>% t() simper_table_3 <- tibble(comparison = c("high salinity - ", "", "low salinity - "), taxon = taxon, `avg contribution (%)` = avg, `cumulative contribution (%)` = cumsum, `mean abundance group a` = avga, `mean abundance group b` = avgb ) ##################### High control vs. Low control ##################### hc_lc <- summary(exp_no_grazers)$High_control_Low_control indices <- which(hc_lc$cumsum <= 0.8) taxon <- rownames(hc_lc)[indices] avg <- round(hc_lc$average[indices]*100, 1) cumsum <- round(hc_lc$cumsum[indices]*100, 1) avga <- mean_abundance %>% filter(interaction == "High_control") %>% select(contains(taxon)) %>% t() avgb <- mean_abundance %>% filter(interaction == "Low_control") %>% select(contains(taxon)) %>% t() simper_table_4 <- tibble(comparison = c("high salinity + ", "", "low salinity + "), taxon = taxon, `avg contribution (%)` = avg, `cumulative contribution (%)` = cumsum, `mean abundance group a` = avga, `mean abundance group b` = avgb ) ##################### High control vs. Low exclusion ##################### hc_le <- summary(exp_no_grazers)$High_control_Low_exclusion indices <- which(hc_le$cumsum <= 0.8) taxon <- rownames(hc_le)[indices] avg <- round(hc_le$average[indices]*100, 1) cumsum <- round(hc_le$cumsum[indices]*100, 1) avga <- mean_abundance %>% filter(interaction == "High_control") %>% select(contains(taxon)) %>% t() avgb <- mean_abundance %>% filter(interaction == "Low_exclusion") %>% select(contains(taxon)) %>% t() simper_table_5 <- tibble(comparison = c("high salinity + ", "", "low salinity - "), taxon = taxon, `avg contribution (%)` = avg, `cumulative contribution (%)` = cumsum, `mean abundance group a` = avga, `mean abundance group b` = avgb ) ##################### Low control vs. Low exclusion ##################### lc_le <- summary(exp_no_grazers)$Low_control_Low_exclusion indices <- which(lc_le$cumsum <= 0.8) taxon <- rownames(lc_le)[indices] avg <- round(lc_le$average[indices] * 100, 1) cumsum <- round(lc_le$cumsum[indices] * 100, 1) avga <- mean_abundance %>% filter(interaction == "Low_control") %>% select(contains(taxon)) %>% t() avgb <- mean_abundance %>% filter(interaction == "Low_exclusion") %>% select(contains(taxon)) %>% t() simper_table_6 <- tibble(comparison = c("low salinity + ", "", "low salinity - "), taxon = taxon, `avg contribution (%)` = avg, `cumulative contribution (%)` = cumsum, `mean abundance group a` = avga, `mean abundance group b` = avgb ) ##################### combining tables ##################### df <- rbind(simper_table_1, simper_table_2, simper_table_3, simper_table_4, simper_table_5, simper_table_6) df$taxon[df$taxon == "ulva_pt"] <- "Ulva sp. (%)" df$taxon[df$taxon == "chthamalus_no"] <- "Chthamalus dalli (no.)" df$taxon[df$taxon == "balanus_no"] <- "Balanus glandula (no.)" df$taxon[df$taxon == "fucus_pt"] <- "Fucus distichus (%)" df$taxon[df$taxon == "diatom_pt"] <- "Diatoms (%)" df %>% select(-comparison) %>% mutate(across("avg contribution (%)":"cumulative contribution (%)", round, 2)) %>% mutate(across("mean abundance group a":"mean abundance group b", round, 1)) %>% kableExtra::kable(align = "lccrr") %>% kableExtra::kable_classic() %>% kableExtra::kable_styling(full_width = F, position = "left") %>% kableExtra::pack_rows("high salinity - vs. high salinity +", 1, 3) %>% kableExtra::pack_rows("high salinity - vs. low salinity +", 4, 7) %>% kableExtra::pack_rows("high salinity - vs. low salinity -", 8, 10) %>% kableExtra::pack_rows("high salinity + vs. low salinity +", 11, 13) %>% kableExtra::pack_rows("high salinity + vs. low salinity -", 14, 16) %>% kableExtra::pack_rows("low salinity + vs. low salinity -", 17, 19) %>% kableExtra::save_kable("./figures/simper_table_fieldexp.png")
package Day7_102222; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.Select; public class T1_Select_Statement { public static void main(String[] args) throws InterruptedException { //setup your chromedriver with webdrivermanager WebDriverManager.chromedriver().setup(); //initialize chrome options ChromeOptions options = new ChromeOptions(); //add options for maximizing the chrome window for windows is "start-maximize" options.addArguments("start-fullscreen"); //define the webdriver and pass the options into the method //creating an instance for chrome driver to use for automation WebDriver driver = new ChromeDriver(options); //go to google page driver.navigate().to("https://www.mlcalc.com"); //wait few seconds Thread.sleep(3000); driver.findElement(By.xpath("//*[text() = 'Show advanced options']")).click(); Thread.sleep(2000); //use select command for month drop down WebElement strtMonth = driver.findElement(By.xpath("//*[@name = 'sm']")); Select startMonthDropdown = new Select(strtMonth); //select by visible text startMonthDropdown.selectByVisibleText("Nov"); //use select command for year drop down WebElement strtyear = driver.findElement(By.xpath("//*[@name = 'sy']")); Select startYearDropdown = new Select(strtyear); //select by visible text startYearDropdown.selectByVisibleText("2023"); //if you cannot use the select command // driver.findElement(By.xpath("//*[@name='sy']")).click(); // driver.findElement(By.xpath("//*[text()='2023']")).click(); driver.quit(); }//end of main }//end of java class
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/modern-normalize.min.css" /> <link rel="stylesheet" href="./css/styles.css" /> </head> <body> <!-- header --> <header class="page-header"> <div class="container page-header-container"> <nav class="navigation"> <a class="logo logo-header" href="./index.html" >Web<span class="logo-accent">Studio</span> </a> <ul class="navigation-list"> <li> <a class="navigation-link home-page" href="./index.html" >Studio</a > </li> <li> <a class="navigation-link" href="">Portfolio</a> </li> <li> <a class="navigation-link" href="">Contacts</a> </li> </ul> </nav> <address class="address-list"> <ul class="address-list"> <li> <a class="address-link" href="mailto:[email protected]"> [email protected] </a> </li> <li> <a class="address-link" href="tel:+110001111111"> +11 (000) 111-11-11 </a> </li> </ul> </address> </div> </header> <!-- main content --> <main> <section class="section hero-section"> <div class="hero-section-container container"> <h1 class="page-title">Effective Solutions for Your Business</h1> <button class="button" type="button">Order Service</button> </div> </section> <section class="section"> <div class="container"> <h2 class="visually-hidden">benefits</h2> <ul class="benefits-list"> <li class="benefit-item"> <div class="icon-container"> <svg class="icon" width="64" height="64"> <use href="./images/icons.svg#icon-antenna"></use> </svg> </div> <h3 class="benefit">Strategy</h3> <p class="benefit-text"> Our goal is to identify the business problem to walk away with the perfect and creative solution. </p> </li> <li class="benefit-item"> <div class="icon-container"> <svg class="icon" width="64" height="64"> <use href="./images/icons.svg#icon-clock"></use> </svg> </div> <h3 class="benefit">Punctuality</h3> <p class="benefit-text"> Bring the key message to the brand's audience for the best price within the shortest possible time. </p> </li> <li class="benefit-item"> <div class="icon-container"> <svg class="icon" width="64" height="64"> <use href="./images/icons.svg#icon-diagram"></use> </svg> </div> <h3 class="benefit">Diligence</h3> <p class="benefit-text"> Research and confirm brands that present the strongest digital growth opportunities and minimize risk. </p> </li> <li class="benefit-item"> <div class="icon-container"> <svg class="icon" width="64" height="64"> <use href="./images/icons.svg#icon-astronaut"></use> </svg> </div> <h3 class="benefit">Technologies</h3> <p class="benefit-text"> Design practice focused on digital experiences. We bring forth a deep passion for problem-solving. </p> </li> </ul> </div> </section> <!-- our masters section --> <section class="section master-section"> <div class="container"> <h2 class="master-section-title section-title">Our Team</h2> <ul class="masters-list"> <li class="master-item"> <img class="master-image" src="./images/img1.jpg" alt="worker-picture" width="264" /> <div class="master-description"> <h3 class="master">Mark Guerrero</h3> <p class="master-position">Product Designer</p> <ul class="socials-list"> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="master-item"> <img class="master-image" src="./images/img2.jpg" alt="worker-picture" width="264" /> <div class="master-description"> <h3 class="master">Tom Ford</h3> <p class="master-position">Frontend Developer</p> <ul class="socials-list"> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="master-item"> <img class="master-image" src="./images/img3.jpg" alt="worker-picture" width="264" /> <div class="master-description"> <h3 class="master">Camila Garcia</h3> <p class="master-position">Marketing</p> <ul class="socials-list"> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="master-item"> <img class="master-image" src="./images/img4.jpg" alt="worker-picture" width="264" /> <div class="master-description"> <h3 class="master">Daniel Wilson</h3> <p class="master-position">UI Designer</p> <ul class="socials-list"> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-link" href=""> <svg class="social-icon" width="16" height="16"> <use href="./images/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> </ul> </div> </section> <!-- our portfolio section --> <section class="section"> <div class="container"> <h2 class="portfolio-section-title section-title">Our Portfolio</h2> <ul class="portfolio"> <li class="portfolio-item"> <div class="overlay-container"> <img class="project-icon" src="./images/banking-app.jpg" alt="image" width="360" /> <p class="overlay-text"> 14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App </p> </div> <div class="project-description-container"> <h3 class="project-title">Banking App</h3> <p class="project-description">App</p> </div> </li> <li class="portfolio-item"> <div class="overlay-container"> <img class="project-icon" src="./images/cashless-payment.jpg" alt="image" width="360" /> <p class="overlay-text"> 14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App </p> </div> <div class="project-description-container"> <h3 class="project-title">Cashless Payment</h3> <p class="project-description">Marketing</p> </div> </li> <li class="portfolio-item"> <div class="overlay-container"> <img class="project-icon" src="./images/meditation-app.jpg" alt="image" width="360" /> <p class="overlay-text"> 14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App </p> </div> <div class="project-description-container"> <h3 class="project-title">Meditation App</h3> <p class="project-description">App</p> </div> </li> <li class="portfolio-item"> <div class="overlay-container"> <img class="project-icon" src="./images/taxi-service.jpg" alt="image" width="360" /> <p class="overlay-text"> 14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App </p> </div> <div class="project-description-container"> <h3 class="project-title">Taxi Service</h3> <p class="project-description">Marketing</p> </div> </li> <li class="portfolio-item"> <div class="overlay-container"> <img class="project-icon" src="./images/screen-illustrations.jpg" alt="image" width="360" /> <p class="overlay-text"> 14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App </p> </div> <div class="project-description-container"> <h3 class="project-title">Screen Illustrations</h3> <p class="project-description">Design</p> </div> </li> <li class="portfolio-item"> <div class="overlay-container"> <img class="project-icon" src="./images/online-coures.jpg" alt="image" width="360" /> <p class="overlay-text"> 14 Stylish and User-Friendly App Design Concepts · Task Manager App · Calorie Tracker App · Exotic Fruit Ecommerce App · Cloud Storage App </p> </div> <div class="project-description-container"> <h3 class="project-title">Online Courses</h3> <p class="project-description">Marketing</p> </div> </li> </ul> </div> </section> </main> <!-- footer --> <footer class="section footer"> <div class="footer-container container"> <div class="footer-logo-container"> <a class="footer-logo logo" href="./index.html" >Web<span class="logo-accent">Studio</span> </a> <p class="footer-text"> Increase the flow of customers and sales for your business with digital marketing & growth solutions. </p> </div> <div class="footer-socials-container"> <p class="footer-socials-text">Social media</p> <ul class="footer-socials"> <li class="footer-socials-item"> <a class="footer-socials-link" href=""> <svg class="footer-socials-icon" width="24" height="24"> <use href="./images/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="footer-socials-item"> <a class="footer-socials-link" href=""> <svg class="footer-socials-icon" width="24" height="24"> <use href="./images/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="footer-socials-item"> <a class="footer-socials-link" href=""> <svg class="footer-socials-icon" width="24" height="24"> <use href="./images/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="footer-socials-item"> <a class="footer-socials-link" href=""> <svg class="footer-socials-icon" width="24" height="24"> <use href="./images/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> <div class="form-subscribe-container"> <p class="form-title-footer">Subscribe</p> <form class="form-subscribe"> <label class="subscribe-label"> <input class="form-subscribe-input" type="email" placeholder="E-mail" name="user-email" /> </label> <button class="subscribe-button" type="submit"> Subscribe <svg class="telegram-icon" width="24" height="24"> <use href="./images/icons.svg#icon-telegram"></use> </svg> </button> </form> </div> </div> </footer> <div class="backdrop is-open"> <div class="service-form-container"> <button class="modal-close-button" type="button"> <svg class="modal-close-icon" width="8" height="8"> <use href="./images/icons.svg#icon-close"></use> </svg> </button> <p class="form-title">Leave your contacts and we will call you back</p> <form class=""> <div class="form-input-container"> <label class="label" for="user-name">Name</label> <div class="input-wrapper"> <input class="form-input" type="text" name="user-name" id="user-name" required pattern="[a-zA-Zа-яА-ЯіІїЇйЙєЄґҐ'{30}]" title="Klymentii" /> <svg class="form-input-icon" width="18" height="24"> <use href="./images/icons.svg#icon-man"></use> </svg> </div> </div> <div class="form-input-container"> <label class="label" for="users-phone">Phone</label> <div class="input-wrapper"> <input class="form-input" type="tel" name="userphone" id="users-phone" required pattern="[0-9]{3}-[0-9]{3}-[0-9]{2}-[0-9{2}] " title="xxx-xxx-xx-xx" /> <svg class="form-input-icon" width="18" height="24"> <use href="./images/icons.svg#icon-phone"></use> </svg> </div> </div> <div class="form-input-container"> <label class="label" for="user-email">Email</label> <div class="input-wrapper"> <input class="form-input" type="email" name="user-mail" id="user-email" required pattern="[a-zA-Z0-9@.{25}]" title="[email protected]" /> <svg class="form-input-icon" width="18" height="24"> <use href="./images/icons.svg#icon-email"></use> </svg> </div> </div> <div class="form-textarea-container"> <label class="label" for="user-comment">Comment</label> <textarea class="form-textarea" name="user-comment" id="user-comment" placeholder="Text input" ></textarea> </div> <div class="privacy-policy-container"> <input class="privacy-policy-checkbox visually-hidden" type="checkbox" value="true" name="user-privacy" id="user-privacy" /> <label class="label" for="user-privacy"> <span class="privacy-policy-fake-checkbox"> <svg class="privacy-policy-fake-icon" width="10" height="8"> <use href="./images/icons.svg#icon-checkmark"></use> </svg> </span> I accept the terms and conditions of the <a class="privacy-policy-link" href="">Privacy Policy</a></label > </div> <button class="button form-button" type="submit">Send</button> </form> </div> </div> </body> </html>
# frozen_string_literal: true class Agency::CaseStudiesController < Agency::BaseController before_action :perform_authorization before_action :set_industry, only: %i[index show favorite unfavorite] before_action :set_case_study, only: %i[show favorite unfavorite edit update destroy] before_action :ensure_access, only: :show def index @my_case_study = 0 if params[:my_case_study] == "1" fetch_my_case_studies @my_case_study = 1 else fetch_favorite_case_studies fetch_remaining_case_studies end @agency_active_package_name = current_agency.active_package_name @agency_niche = AgencyNiche.find_or_create_by( agency_id: current_agency.id, industry_id: @industry.id ) end def categories my_case_studies @cs_counts = {} CaseStudy::CATEGORIES.each do |c| @cs_counts[c[:key]] = CaseStudy.send(c[:key]).joins(:images).distinct.count end end def category_case_studies @category = CaseStudy::CATEGORIES.detect do |c| c[:id] == params[:category_id].to_i end || CaseStudy::CATEGORIES.first @case_studies = CaseStudy.includes(:industries) .send(@category[:key]) .where(search_query) .priority_order .joins(:images).distinct .paginate(page: params[:page], per_page: 20) @agency_active_package_name = current_agency.active_package_name end def new @case_study = CaseStudy.new end def create @case_study = CaseStudy.new(case_study_params) if @case_study.save @case_study.published! if params[:publish].present? flash[:success] = 'Casestudy added Successfully' redirect_to agency_case_study_categories_path else flash[:error] = @case_study.errors.full_messages.to_sentence redirect_to new_agency_case_study_path(@case_study) end end def edit; end def update if @case_study.update(case_study_params) @case_study.published! if params[:publish].present? @case_study.draft! if params[:draft].present? flash[:success] = 'CaseStudy updated Successfully' redirect_to agency_case_study_categories_path else flash[:error] = @case_study.errors.full_messages.to_sentence redirect_to edit_agency_case_study_path(@case_study) end end def show @my_case_study = params[:my_case_study] @category_id = params[:category_id] @case_studies = CaseStudy.where(industry_id: @case_study.industry_id).order(:updated_at) index_of_current = @case_studies.ids.index(@case_study.id) @next = (@case_studies + @case_studies)[index_of_current + 1] @previous = (@case_studies + @case_studies)[index_of_current - 1] end def favorite if current_user.favorited_case_studies.include?(@case_study) current_user.favorite_case_studies.where(case_study_id: @case_study.id).destroy_all @favorite = false else current_user.favorited_case_studies << @case_study @favorite = true end @agency_active_package_name = current_agency.active_package_name fetch_favorite_case_studies fetch_remaining_case_studies end def create_agency_niche params[:industry_ids]&.each do |industry_id| @agency_niche = AgencyNiche.find_or_create_by( agency_id: current_agency.id, industry_id: industry_id ) end end def destroy @case_study.destroy redirect_to agency_case_study_categories_path end private def fetch_favorite_case_studies @case_studies = @industry.case_studies.published.where(search_query).order(created_at: :desc) @fav_case_studies = @case_studies.select do |case_study| case_study if current_user.favorited_case_studies.include?(case_study) && case_study.images.count.positive? end end def fetch_remaining_case_studies @case_studies = @industry.case_studies.published.where(search_query).order(created_at: :desc) @rem_case_studies = @case_studies.select do |case_study| case_study if current_user.favorited_case_studies.exclude?(case_study) && case_study.images.count.positive? end end def set_industry @industry = Industry.find(params[:industry_id]) end def set_case_study @case_study = CaseStudy.find(params[:id]) end def perform_authorization authorize current_agency, :case_study? end def ensure_access return true if @case_study.has_access?(current_agency.active_package_name) redirect_to agency_case_studies_path( industry_id: @industry.id ) and return end def search_query return '' if params[:name].blank? "lower(case_studies.title) ILIKE '%#{params[:name]}%'" end def fetch_my_case_studies @case_studies = @industry.case_studies.published.where(search_query).order(created_at: :desc) @my_case_studies = @case_studies.select do |case_study| case_study if case_study.agency_id == current_agency.id && case_study.images.count.positive? end end def my_case_studies @my_case_studies = CaseStudy.includes(:industries).where( case_studies: { agency_id: current_agency.id } ).priority_order.paginate(page: params[:page], per_page: 20) end def case_study_params params.require(:case_study).permit( :title, :description, :detailed_description, :descriptive_image, :in_their_words, :stat1_text, :stat1_value, :stat2_text, :stat2_value, :stat3_text, :stat3_value, :assignee_id, :agency_id, :tier, :short_desc, services: [], images_attributes: [:id, :file, :_destroy], industry_ids: [] ) end end
/* * Generic.java * * Copyright (c) 2009-2013 Guillaume Mazoyer * * This file is part of GNOME Split. * * GNOME Split 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. * * GNOME Split 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 GNOME Split. If not, see <http://www.gnu.org/licenses/>. */ package org.gnome.split.core.merger; import java.io.File; import java.io.IOException; import org.gnome.split.core.exception.EngineException; import org.gnome.split.core.exception.MissingChunkException; import org.gnome.split.core.io.GRandomAccessFile; /** * Algorithm to merge files with an algorithm which does not use any headers * in the files. * * @author Guillaume Mazoyer */ public final class Generic extends DefaultMergeEngine { public Generic(File file, String filename) { super(file, filename); } @Override protected void loadHeaders() throws IOException { // Update the filename only if it is not specified by the user if (filename == null) { String name = file.getName().substring(0, file.getName().lastIndexOf('.')); filename = file.getAbsolutePath().replace(file.getName(), "") + name; } // We do not use an MD5 sum md5 = false; // Setup to found chunks to merge String directory = file.getAbsolutePath().replace(file.getName(), ""); String name = file.getName(); // Get all the files of the directory File[] files = new File(directory).listFiles(); // Setup default values parts = 0; fileLength = 0; for (File chunk : files) { boolean valid = chunk.getName().contains(name.substring(0, name.lastIndexOf('.'))); if (!chunk.isDirectory() && valid) { // Increase the number of chunks parts++; // Update the size fileLength += chunk.length(); } } } @Override protected String getNextChunk(String part, int number) { // Get the current extension String current; if (number >= 100) { current = String.valueOf(number); } else if (number >= 10) { current = "0" + number; } else { current = "00" + number; } // Finally return (part + current); } @Override public void merge() throws IOException, EngineException { String part = file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 3); GRandomAccessFile out = null; File chunk = null; boolean run = true; try { // Open the final file out = new GRandomAccessFile(filename, "rw"); // We assume that there is at least one part (which is kinda // ridiculous, but still...). We'll do some tricks to find out // which files we have to merge parts = file.getName().endsWith(".000") ? 0 : 1; for (int i = parts; i <= parts; i++) { // Next chunk chunk = new File(this.getNextChunk(part, i)); if (!chunk.exists()) { // Check if the chunk really exists throw new MissingChunkException(); } // Open the chunk to read it GRandomAccessFile access = new GRandomAccessFile(chunk, "r"); // Notify the view from a new part read this.fireEnginePartRead(chunk.getName()); // Merge the file run = this.mergeChunk(out, access, 0, access.length()); // Reading stopped if (!run) { return; } // Add the part the full read parts chunks.add(chunk.getAbsolutePath()); // Close the part access.close(); // Lets find out if there is one more part if (new File(this.getNextChunk(part, (i + 1))).exists()) { parts++; } } // Notify the end this.fireEngineEnded(); } finally { try { // Close the final file out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
import { Column, Entity, Unique, OneToMany, DeleteDateColumn, } from 'typeorm'; import { Exclude } from 'class-transformer'; import { PermissionEntity } from '../permission/permission.entity'; import { GuidIdentity } from '../../common/guid.entity'; @Entity({ name: 'resource_servers', }) @Unique('idx_resource_server_identifier', ['tenant', 'identifier']) export class ResourceServerEntity extends GuidIdentity { @Column({ length: 32 }) name: string; @Column({ nullable: true, default: false }) is_system: boolean; @Column({ nullable: true }) token_dialect: string; @Column({ nullable: true, default: false }) enforce_policies: boolean; @Column({ nullable: true }) signing_secret: string; @Column({ length: 36 }) tenant: string; @Column({ length: 36 }) identifier: string; @Column({ nullable: true }) allow_offline_access: boolean; @Column({ nullable: true }) skip_consent_for_verifiable_first_party_clients: boolean; @Column({ nullable: true }) token_lifetime: number; @Column({ nullable: true }) token_lifetime_for_web: number; @Column({ nullable: true }) signing_alg: string; @OneToMany(() => PermissionEntity, (permission) => permission.resource_server, { cascade: true, eager: true, }) permissions?: PermissionEntity[]; @DeleteDateColumn() @Exclude() dtime?: Date; }
import React, { useState, useEffect } from "react"; import { StarIcon } from "@heroicons/react/24/solid"; import { useSelector, useDispatch } from "react-redux"; import { getProducts } from "../../actions/productAction"; const categories = [ { _id: 1, name: "computer monitors", }, { _id: 2, name: "Laptops", }, { _id: 3, name: "Digital Watches", }, { _id: 4, name: "Mobiles", }, ]; const reviews = [5, 4, 3, 2, 1]; const product = { _id: 1, name: "Large 45 L Laptop Backpack Backpack Spacy Laptop Unisex College & School Bags (Grey)", ratings: 4, reviews: 455, color: "gray", Mprice: 999, price: 399, discount: 60, freeDelivery: true, }; import "./multiSlider.css"; import ProuctContainer from "./ProuctContainer"; import { set } from "mongoose"; const min = 0; const max = 100; const step = 1; function ProductFilter() { const dispatch = useDispatch(); const { loading, error, products } = useSelector((state) => state.products); const [keyword, setKeyword] = useState(""); const [minPrice, setMinPrice] = useState(0); const [maxPrice, setMaxPrice] = useState(10); useEffect(() => { dispatch(getProducts(keyword, 1, [1, 50000])); }, [keyword, minPrice, maxPrice]); const handleCategoryChange = (e) => setKeyword(e.target.value); const handleMinPriceRange = (event) => { let value = event.target.value; if (+value > +maxPrice) { console.log(value); setMaxPrice(value); } else if (+value < +maxPrice) { setMinPrice(value); } }; const handleMaxPriceRange = (event) => { let value = event.target.value; if (+maxPrice <= +value) { setMinPrice(value); } else { setMaxPrice(value); } }; const minPos = ((minPrice - min) / (max - min)) * 100; const maxPos = ((maxPrice - min) / (max - min)) * 100; return ( <div className="flex gap-2 my-4 md:mx-2"> <div className="w-64 shadow"> <div className="flex itmes-center justify-between p-4 border-b mb-4"> <div className="text-xl">FILTER</div> <div> <button className="bg-orange-500 text-white border border-orange-400 rounded-md py-1 px-2 text-sm"> CLEAR </button> </div> </div> <div className="flex flex-col p-4 border-b"> <p className="text-sm">PRICE</p> <div className="wrapper"> <div className="input-wrapper"> <input className="input" type="range" value={minPrice} min={min} max={max} step={step} onChange={handleMinPriceRange} /> <input className="input" type="range" value={maxPrice} min={min} max={max} step={step} onChange={handleMaxPriceRange} /> </div> <div className="control-wrapper"> <div className="control" style={{ left: `${minPos}%` }} /> <div className="rail"> <div className="inner-rail" style={{ left: `${minPos}%`, right: `${100 - maxPos}%` }} /> </div> <div className="control" style={{ left: `${maxPos}%` }} /> </div> </div> <div className="flex justify-between items-cennter"> <p className="text-sm border p-2 font-light rounded-md"> Rs. {minPrice} </p> <p className="text-sm p-2 text-gray-500">to</p> <p className="text-sm border p-2 font-light rounded-md"> Rs. {maxPrice} </p> </div> </div> <div className=" p-4 mb-4 border-b"> <p className="text-sm">CATEGORIES</p> <div className="__categories"> <ul> {categories.map(({ _id, name }) => { return ( <li> <input type="radio" value={name} name="category" id={`${name}_${_id}`} className="w-4 h-4 border border-gray-300 rounded bg-gray-50" onChange={handleCategoryChange} /> <label htmlFor={`${name}_${_id}`} className="pl-2 text-sm"> {name} </label> </li> ); })} </ul> </div> </div> <div className=" p-4 mb-4"> <p className="text-sm">CUSTOMER RATINGS</p> <div className="__reviews"> <ul> {reviews.map((review) => { return ( <li className="flex"> <input type="checkbox" name="laptop" id={review} className="w-4 h-4 border border-gray-300 rounded bg-gray-50" /> <label htmlFor={review} className="pl-2 text-sm flex items-center" > <p>{review}</p> <StarIcon className="h-3 w-3" /> <p className="pl-1">& above</p> </label> </li> ); })} </ul> </div> </div> </div> <div className="w-full shadow"> <div className="flex flex-wrap px-2 pt-1 md:my-14"> {loading ? "Loading..." : products.map((product) => ( <ProuctContainer key={product._id} product={product} /> ))} </div> </div> </div> ); } export default ProductFilter;
<template> <!-- 付款方式 --> <div class="pay"> <h2>付款資訊</h2> <nav> <form> <section> <label for="phone">卡號:</label> <template v-for="(input, index) in cardNumberInputs" :key="index"> <input v-model="input.value" :placeholder="'XXXX'" type="text" :class="`card ${input.className}`" :maxlength="input.maxLength" :pattern="input.pattern" required v-next-input=" index < cardNumberInputs.length - 1 ? $refs[`cardInput${index + 1}`] : null " @input="handleCardInput(index)" @keydown.backspace="handleCardBackspace(index)" @keypress="handleCardKeyPress" :ref="`cardInput${index}`" /> <!-- v-next-input 可以自動跳下一格 cardNumberInputs.length - 1是否為最後一格 如果條件為假,也就是當前輸入框是最後一個輸入框,那麼執行結果為 null "-"只會出現在index小於cardNumberInputs.length-1之間,因為有4個,但是"-"只會出現在4組號碼中間。 handleCardBackspace 事件監聽按下退格鍵觸發該事件。handleCardKeyPress檢查使用者輸入的按鍵值, 並確定該按鍵是否為有效的卡號輸入--> <span v-if="index < cardNumberInputs.length - 1">-</span> </template> </section> <section class="name"> <label for="name">持卡人姓名:</label> <input class="inp_short" type="text" id="name" name="name" /><br /> </section> <section> <label for="date">有效期:</label> <input v-model="expiration" :ref="`expirationInput`" :placeholder="'MM/YY'" type="text" maxlength="5" class="card expiration-input" pattern="(0[1-9]|1[0-2])/(2[2-9]|[3-9][0-9])" required v-next-input="$refs.securityCodeInput" @input="handleExpirationInput" @keydown.backspace="handleExpirationBackspace" @keypress="handleExpirationKeyPress" /> <!--pattern限制使用者在輸入框中輸入的值必須符合指定的模式 [0-9]只能0~9 {4}為數字長度 required用於指定輸入框是否為必填項目 handleExpirationInput 事件監聽器,監聽日期輸入完2碼後加"/"並將焦點跳轉到下一個輸入框。 是在安全碼輸入框中使用 $refs.securityCodeInput 作為儲存點,以便在特定條件下跳到下一個輸入框。 --> </section> <section> <label for="password">安全碼:</label> <input v-model="securityCode" :placeholder="'XXX'" type="text" maxlength="3" class="card" pattern="[0-9]{3}" required ref="securityCodeInput" @keypress="handleSecurityCodeKeyPress" /> </section> </form> <section class="connect"> <h1>連接LINEPAY</h1> <h1>連接APPLEPAY</h1> </section> </nav> <section class="btn-wrap"> <btn class="btn" :style="{ width: '200px' }" button-text-color="white" button-color="#D1825B" >取消</btn > <btn class="btn" :style="{ width: '200px' }" button-text-color="white" button-color="#D1825B" >儲存</btn > </section> </div> </template> <script setup> import { ref, onMounted, watch } from 'vue'; const cardNumberInputs = [ { value: '', className: 'input1', maxLength: 4, pattern: '[0-9]{4}' }, { value: '', className: 'input2', maxLength: 4, pattern: '[0-9]{4}' }, { value: '', className: 'input3', maxLength: 4, pattern: '[0-9]{4}' }, { value: '', className: 'input4', maxLength: 4, pattern: '[0-9]{4}' }, ]; const expiration = ref(''); //預設值為空字串 const securityCode = ref(''); // 信用卡號輸入 const handleCardInput = index => { const input = cardNumberInputs[index]; // index進入陣列取值執行迴圈 if ( input.value.length === input.maxLength && index < cardNumberInputs.length - 1 ) { const nextInput = document.querySelector( `.card.${cardNumberInputs[index + 1].className}` // 打完一組卡號找下一個輸入框 ); if (nextInput) { nextInput.focus(); } } }; // 信用卡號退格鍵 const handleCardBackspace = index => { const input = cardNumberInputs[index]; // index進入陣列取值執行迴圈 if (input.value.length === 0 && index > 0) { const previousInput = document.querySelector( `.card.${cardNumberInputs[index - 1].className}` // 退格完一組卡號找上一個輸入框 ); if (previousInput) { previousInput.focus(); } } }; const handleCardKeyPress = event => { const keyCode = event.keyCode || event.which; const keyValue = String.fromCharCode(keyCode); const isValidKey = /^[0-9]+$/.test(keyValue); // 防止輸入非數字 if (!isValidKey) { event.preventDefault(); alert('請輸入正確卡號'); } }; // 信用有效期 const handleExpirationInput = () => { if (expiration.value.length === 2) { // 信用有效期寫完2格自動加"/" expiration.value += '/'; const expirationInput = document.querySelector('.expiration-input'); if (expirationInput) { expirationInput.focus(); } } }; // 信用有效期退格鍵 const handleExpirationBackspace = () => { if (expiration.value.length === 3 && expiration.value[2] === '/') { // 陣列 0、1、2,固定2寫"/" expiration.value = expiration.value.slice(0, 2); } }; // 信用安全碼 const handleSecurityCodeKeyPress = event => { const keyCode = event.keyCode || event.which; const keyValue = String.fromCharCode(keyCode); const isValidKey = /^[0-9]+$/.test(keyValue); if (!isValidKey) { event.preventDefault(); alert('請輸入正確安全碼'); } }; // 信用安全碼退格鍵 const handleExpirationKeyPress = event => { const keyCode = event.keyCode || event.which; const keyValue = String.fromCharCode(keyCode); const isValidKey = /^[0-9]+$/.test(keyValue); if (!isValidKey) { event.preventDefault(); alert('請輸入正確有效期'); } }; onMounted(() => { const firstInput = document.querySelector('.card.input1'); if (firstInput) { firstInput.focus(); } }); </script> <style lang="scss" scoped> input.card { width: 55px; } .connect h1{ font-size: 26px; color: #9c3401; } .btn-wrap { margin: 0 auto; width: 60%; display: flex; justify-content: space-between; align-items: center; padding-bottom: 40px; .btn { // width: 150px; height: 55px; font-size: 20px; // border-radius: 10px; } } h2 { color: #f9f3e4; background-color: #d1825b; text-align: center; line-height: 70px; height: 70px; } input { font-size: 16px; padding: 10px; border: 2px solid #000000; border-radius: 10px; } //付款方式 .pay { background-color: $maincolor1; width: 75%; font-size: 20px; margin-left: 40px; nav { margin: 40px; display: flex; justify-content: space-between; } form { display: flex; flex-direction: column; align-items: stretch; padding: 40px 50px; section { label { display: block; width: 200px; font-size: 20px; font-weight: bold; color: #90420a; margin-bottom: 10px; } } input { margin-bottom: 23px; } } #Submit { width: 170px; height: 55px; color: #f9f3e4; background-color: #d1825b; border: none; border-radius: 10px; margin: 30px auto; } } </style>
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule } from '@angular/router'; import { AgmCoreModule } from '@agm/core'; import { AppComponent } from './app.component'; import { LoginComponent } from './components/login/login.component'; import { LogoutComponent } from './components/logout/logout.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BasicAuthHttpInterceptorService } from './service/basic-auth-interceptor.service'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AngularMaterialModule } from './angular-material.module'; import { HttpClientModule } from '@angular/common/http'; import { RouterTestingModule } from "@angular/router/testing"; import { AppRoutingModule } from './app-routing.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { FooterComponent } from './components/footer/footer.component'; import { HeaderComponent } from './components/header/header.component'; import { FavoritesComponent } from './components/favorites/favorites.component'; import { RegisterComponent } from './components/register/register.component'; import { CarparksHomeComponent } from './components/carparks-home/carparks-home.component'; import { CarparkDetailComponent } from './components/carpark-detail/carpark-detail.component'; import { HomepageComponent } from './homepage/homepage.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, LogoutComponent, FooterComponent, HeaderComponent, FavoritesComponent, RegisterComponent, CarparksHomeComponent, CarparkDetailComponent, HomepageComponent, ], imports: [ BrowserModule, AngularMaterialModule, AppRoutingModule, BrowserAnimationsModule, RouterModule, HttpClientModule, RouterTestingModule, FormsModule, ReactiveFormsModule, AgmCoreModule.forRoot({ apiKey: 'AIzaSyC16z_Dinq2IKjGx-2XlIwvwbwOLQfydEA' }) ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: BasicAuthHttpInterceptorService, multi: true }], bootstrap: [AppComponent] }) export class AppModule { }
import { useContext, useEffect, useState } from "react"; import random from "../utils/random"; import { commitmentHash, nullifierHash } from "../utils/createHash"; import { approve, getDetails, getL2contract, get_token_name, toHex, fetchData, toDecimal, } from "../web3/web3"; import { CreateTicketQR } from "../utils/createTicketQR"; import { downloadTicket } from "../utils/downloadTicket"; import { useParams } from "react-router-dom"; import { toast } from "react-toastify"; import { storeContext } from "../useContext/storeContext"; import { Button, Card, Clipboard } from "flowbite-react"; import BeatLoader from "react-spinners/BeatLoader"; function BuyTicket(props) { const { account } = useContext(storeContext); const { event_index } = useParams(); const eventUrl = `${window.location.origin}/home/${event_index}`; const tName = props.tName; const name = props.name; const price = props.price; const [loading, setLoading] = useState(false); const override = { display: "block", marginTop: "250px", }; async function buy_ticket() { if (account == null) { toast.error("Connect Wallet first"); return; } const { event_price, event_name, token_address } = await getDetails( event_index ); const amount = event_price; setLoading(true); let status = await approve(account, amount, toHex(token_address)); if (status != true) { toast.error("failed to approve"); setLoading(false); return; } await new Promise((resolve) => setTimeout(resolve, 10000)); const secret = random(); const nullifier = random(); const commitment_hash = commitmentHash( parseInt(nullifier), parseInt(secret) ); const nullifier_hash = nullifierHash(parseInt(nullifier)); const hex_commitment_hash = toHex(commitment_hash); const contract = getL2contract(account); try { const tx2 = await contract.buyTicket( event_index, hex_commitment_hash, token_address ); const transactionHash = tx2.transaction_hash; let data = await fetchData(transactionHash, 3); let buyer = data[0].value; let ticketEventIndex = data[1].value; let creatorOfTicket = data[2].value; let commitment = data[3].value; let _nullifier = data[4].value; console.log( `buyer - ${buyer} ticketEventIndex - ${ticketEventIndex} creatorOfTicket - ${creatorOfTicket} commitment - ${commitment} nullifier - ${_nullifier}` ); // event emit values creator of the event and their event inde const noteString = `${nullifier},${secret},${nullifier_hash},${commitment_hash},${event_index},${amount},${token_address}`; const qrDataURL = await CreateTicketQR(noteString); const token_name = get_token_name(token_address); setLoading(false); downloadTicket( qrDataURL, amount, token_name, event_index, event_name, account.address ); toast.success("ticket bought successfully"); } catch (error) { setLoading(false); toast.error("transaction failed"); } } return ( <div> {loading ? ( <> <BeatLoader color="#ffffff" cssOverride={override} /> <p className="text-white">Fetching...</p> </> ) : ( <div className="flex flex-col justify-center items-center h-full"> <div className="grid w-full max-w-96 mb-3"> <div className="relative"> <label htmlFor="npm-install" className="sr-only"> Label </label> <input id="npm-install" type="text" className="col-span-6 block w-full rounded-lg border border-gray-300 bg-gray-50 px-2.5 py-4 text-sm text-gray-500 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-400 dark:placeholder:text-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500" value={eventUrl} disabled readOnly /> <Clipboard.WithIconText valueToCopy={eventUrl} /> </div> </div> <Card className="max-w-sm w-full"> <h5 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white"> Buy Ticket </h5> <p className="font-normal text-gray-700 dark:text-gray-400"> Event Id: {event_index} </p> <p className="font-normal text-gray-700 dark:text-gray-400"> Event Name : {name} </p> <p className="font-normal text-gray-700 dark:text-gray-400"> Price: {price} {tName} </p> <Button onClick={buy_ticket} color="yellow"> Buy Ticket </Button> </Card> </div> )} </div> ); } export default BuyTicket;
import React from 'react'; import PropTypes from 'prop-types'; import TodoItem from '../TodoItem/TodoItem'; const TodoListItems = ({ todos, handleRemoveTodo, handleCompleteTodo, handleEditTodo, }) => ( <ul className="listItems"> {todos.map((todo) => ( <TodoItem key={todo.id} todo={todo} handleRemoveTodo={handleRemoveTodo} handleCompleteTodo={handleCompleteTodo} handleEditTodo={handleEditTodo} /> ))} </ul> ); TodoListItems.propTypes = { todos: PropTypes.shape([]) }; TodoListItems.defaultProps = { todos: [] }; TodoListItems.propTypes = { handleRemoveTodo: PropTypes.func }; TodoListItems.defaultProps = { handleRemoveTodo: () => {} }; TodoListItems.propTypes = { handleCompleteTodo: PropTypes.func }; TodoListItems.defaultProps = { handleCompleteTodo: () => {} }; TodoListItems.propTypes = { handleEditTodo: PropTypes.func }; TodoListItems.defaultProps = { handleEditTodo: () => {} }; export default TodoListItems;
@Category({MasterTests.class,MediumTests.class}) public class TestHMasterRPCException { @ClassRule public static final HBaseClassTestRule CLASS_RULE=HBaseClassTestRule.forClass(TestHMasterRPCException.class); private static final Logger LOG=LoggerFactory.getLogger(TestHMasterRPCException.class); private final HBaseTestingUtility testUtil=HBaseTestingUtility.createLocalHTU(); private HMaster master; private RpcClient rpcClient; @Before public void setUp() throws Exception { Configuration conf=testUtil.getConfiguration(); conf.set(HConstants.MASTER_PORT,"0"); conf.setInt(HConstants.ZK_SESSION_TIMEOUT,2000); testUtil.startMiniZKCluster(); ZKWatcher watcher=testUtil.getZooKeeperWatcher(); ZKUtil.createWithParents(watcher,watcher.getZNodePaths().masterAddressZNode,Bytes.toBytes("fake:123")); master=new HMaster(conf); rpcClient=RpcClientFactory.createClient(conf,HConstants.CLUSTER_ID_DEFAULT); } @After public void tearDown() throws IOException { if (rpcClient != null) { rpcClient.close(); } if (master != null) { master.stopMaster(); } testUtil.shutdownMiniZKCluster(); } @Test public void testRPCException() throws IOException, InterruptedException, KeeperException { ServerName sm=master.getServerName(); boolean fakeZNodeDelete=false; for (int i=0; i < 20; i++) { try { BlockingRpcChannel channel=rpcClient.createBlockingRpcChannel(sm,User.getCurrent(),0); MasterProtos.MasterService.BlockingInterface stub=MasterProtos.MasterService.newBlockingStub(channel); assertTrue(stub.isMasterRunning(null,IsMasterRunningRequest.getDefaultInstance()).getIsMasterRunning()); return; } catch ( ServiceException ex) { IOException ie=ProtobufUtil.handleRemoteException(ex); assertTrue(ie.getMessage().startsWith("org.apache.hadoop.hbase.ipc.ServerNotRunningYetException: Server is not running yet")); LOG.info("Expected exception: ",ie); if (!fakeZNodeDelete) { testUtil.getZooKeeperWatcher().getRecoverableZooKeeper().delete(testUtil.getZooKeeperWatcher().getZNodePaths().masterAddressZNode,-1); fakeZNodeDelete=true; } } Thread.sleep(1000); } } }
import functions_framework import firebase_admin from firebase_admin import firestore import datetime #initialize app app = firebase_admin.initialize_app() @functions_framework.http def viewcount_http(request): """HTTP Cloud Function. Args: request (flask.Request): The request object. <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data> Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>. """ # Set CORS headers for the preflight request if request.method == "OPTIONS": # Allows GET requests from any origin with the Content-Type # header and caches preflight response for an 3600s headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Max-Age": "3600", } return ("", 204, headers) # Set CORS headers for the main request headers = {"Access-Control-Allow-Origin": "*"} #initialize db db = firestore.client() #update + acquire current visit number visits_ref = db.collection("visits") visits = visits_ref.document('0').get(field_paths={'views'}).to_dict().get('views') visits += 1 visits_ref.document("0").set({'views':visits}) #acquire data for fields ip = request.remote_addr timeAccessed = datetime.datetime.now() #initialize new document with data doc_ref = visits_ref.document(str(visits)) doc_ref.set({'visitID': visits, 'ip' : ip, 'timeAccessed' : timeAccessed}) #return current visit number for counter return ("{}".format(visits), 200, headers)
<script setup> import { ref, watch, onMounted } from 'vue'; import { createPopper } from '@popperjs/core' import Svg from '@components/Svg.vue'; // HTML Elements const button = ref(null) const tooltip = ref(null) const popperInstance = ref(null) const list = ref(null) const listwrap = ref(null) const listHeight = ref(null) const liwrap = ref(null) const popperContainer = ref(null) const overlayElement = ref(null) // Parameters const isVisible = ref(false) let listItems = [10, 25, 50 , 100, 'all'] const currentValue = ref(listItems[0]) async function selectItem(item){ toggleVisible() currentValue.value = item overlayElement.value.remove() } // *** Popper *** \\ function show() { createOverlay() // Make the tooltip visible tooltip.value.setAttribute('data-show', ''); // Enable the event listeners popperInstance.value.setOptions((options) => ({ ...options, modifiers: [ ...options.modifiers, { name: 'eventListeners', enabled: true }, ], })); popperInstance.value.update() list.value.style.opacity = '1' liwrap.value.style.height = listHeight.value // for down-up transition when placement top list.value.style.height = listHeight.value // await new Promise(resolve => setTimeout(resolve, 1000)) // await max-size transition // setTimeout(() => { // }) } // async function hide() { function hide() { liwrap.value.style.height = '0px' list.value.style.opacity = '0' setTimeout(() => { tooltip.value.removeAttribute('data-show'); // Disable the event listeners popperInstance.value.setOptions((options) => ({ ...options, modifiers: [ ...options.modifiers, { name: 'eventListeners', enabled: false }, ], })); }, 200) } function toggleVisible(){ isVisible.value = !isVisible.value isVisible.value ? show() : hide() } //\\ *** Popper *** //\\ // create overlay async function createOverlay() { // overlay overlayElement.value = document.createElement('div'); overlayElement.value.classList.add('overlay'); document.body.appendChild(overlayElement.value); // tooltip overlayElement.value.appendChild(tooltip.value) popperInstance.value.update() // destroy overlay overlayElement.value.addEventListener('click', async function(e){ if(e.target == e.currentTarget){ toggleVisible() await new Promise(resolve => setTimeout(resolve, 200)) // await max-size transition popperContainer.value.appendChild(tooltip.value) overlayElement.value.remove() } }); } onMounted(()=>{ popperInstance.value = createPopper(button.value, tooltip.value, { placement: 'bottom', }); // get listHeight tooltip.value.setAttribute('data-show', ''); listHeight.value = list.value.getBoundingClientRect().height + 'px' tooltip.value.removeAttribute('data-show'); // set listHeight 0px and fix listwrap for correct popper placement liwrap.value.style.height = '0px' listwrap.value.style.height = listHeight.value }) const emits = defineEmits(['callback']) watch( () => currentValue.value, (newValue) => { emits('callback', newValue) } ) </script> <template> <div ref="popperContainer" class="popperContainer"> <div ref="button" class="popper-btn" @click="toggleVisible"> <span> {{currentValue}} </span> <Svg class="drop-menu__icon" name="chevron-down" :opened="isVisible"></Svg> </div> <div id="tooltip" ref="tooltip" class="tooltip"> <div ref="listwrap" class="listwrap"> <ul ref="list" id="list" class="list"> <div ref="liwrap" class = "liwrap"> <template v-for="item in listItems"> <li @click="selectItem(item)"> {{ item }} </li> </template> </div> </ul> </div> </div> </div> </template> <style lang="sass"> .overlay position: fixed z-index: 50 top: 0 left: 0 width: 100% height: 100% .liwrap height: max-content width: 5rem transition: height .2s ease overflow-y: hidden background: #cbe0ff box-sizing: border-box padding: 0.25rem 0 li padding-left: .5rem height: 1.5rem &:hover background: #aecef2 .list opacity: 0 transition: opacity .4s .tooltip width: 5rem display: none cursor: pointer z-index: 1000 &[data-show] display: block &[data-popper-placement^='top'] // for down->up height transition when placement top .list display: flex align-items: end .popper-btn cursor: pointer width: 5rem padding: 0 border: 1px solid border-color: #b0b0b0 background: #ccdde9 box-sizing: border-box padding-left: .5rem display: flex align-items: center &:hover background: #a5c5dc .drop-menu__icon margin-left: auto width: 1.75rem transition: transform .2s transform: rotate(0deg) &[opened=true] transform: rotate(-180deg) </style>
//{ Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends //User function Template for C++ class Solution { public: int largestIsland(vector<vector<int>>& grid) { int n = grid.size(); vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; auto is_valid = [&](int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; }; function<int(int, int, int)> dfs = [&](int x, int y, int color) { if (!is_valid(x, y) || grid[x][y] != 1) { return 0; } grid[x][y] = color; int size = 1; for (auto& dir : directions) { int nx = x + dir.first; int ny = y + dir.second; size += dfs(nx, ny, color); } return size; }; unordered_map<int, int> island_sizes; // {color: size} int color = 2; // Start from color 2 (1 is already used for '1's) int max_island_size = 0; for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (grid[x][y] == 1) { int size = dfs(x, y, color); island_sizes[color] = size; max_island_size = max(max_island_size, size); color++; } } } for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (grid[x][y] == 0) { set<int> neighbor_colors; int potential_size = 1; // Change the '0' to '1' for (auto& dir : directions) { int nx = x + dir.first; int ny = y + dir.second; if (is_valid(nx, ny)) { int neighbor_color = grid[nx][ny]; if (neighbor_color != 0 && neighbor_colors.find(neighbor_color) == neighbor_colors.end()) { neighbor_colors.insert(neighbor_color); potential_size += island_sizes[neighbor_color]; } } } max_island_size = max(max_island_size, potential_size); } } } return max_island_size; } }; //{ Driver Code Starts. int main(){ int t; cin >> t; while(t--){ int n; cin>>n; vector<vector<int>>grid(n,vector<int>(n)); for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>grid[i][j]; Solution ob; cout<<ob.largestIsland(grid)<<endl; } return 0; } // } Driver Code Ends
#ifndef RAY_H #define RAY_H #include "Point.h" #include "Vector.h" #include<iostream> #include<ostream> // Represents a ray with an origin point and a direction class Ray { private: // Object variables Point orig; Vector dir; public: // Constructor to make a ray with a given point and direction Ray(Point p, Vector d); // Constructor to make a ray going from p1 in the direction of p2 Ray(Point p1, Point p2); // Get methods for object variables Point origin() const; Vector direction() const; // Returns the point on the ray that is t distance from its origin Point point(float t); }; // Overloaded output operator for printing the ray's information std::ostream& operator<<(std::ostream& os, Ray r); #endif /* Ray_H */
# Google Search API 概要 このドキュメントでは、Google Search API の導入方法について説明します。 Google Search API は、Google 検索エンジンの機能を利用するための API です。この API を使用することで、検索結果の取得や検索クエリの実行などを行うことができます。 ## 導入手順 以下の手順に従って、Google Search API を導入してください。 1. Google Cloud Platform にアクセスし、プロジェクトを作成します。 2. プロジェクトのダッシュボードから、Google Search API を有効化します。 3. API キーを生成し、プロジェクトに紐付けます。 4. API キーを使用して、Google Search API を呼び出すコードを実装します。 以上が Google Search API の導入手順です。詳細な手順やサンプルコードについては、公式ドキュメントを参照してください。 ### API 設定 <https://programmablesearchengine.google.com/controlpanel/all> ![Alt text](96972.png) ![Alt text](33560.png) ### Code ```json <https://www.googleapis.com/customsearch/v1?key={APIキー}&cx={検索エンジンID}&q={任意の検索クエリ}> ```
using Application.Core; using Application.Interfaces; using Domain; using FluentValidation; using MediatR; using Microsoft.EntityFrameworkCore; using Persistence; namespace Application.Activities { public class Create { /* This class is used to create a new activity The Command class is used to send data to the server in order to create a new activity. It is a common practice in software development to use the term "command" to represent an action or request that needs to be executed. In this case, the Command class serves as a container for the data that will be sent to the server to create the activity. By implementing the IRequest interface, the Command class indicates that it is a request object that can be handled by the server. */ public class Command : IRequest<Result<Unit>> { public Activity Activity { get; set; } } public class CommandValidator : AbstractValidator<Command> { public CommandValidator() { // The RuleFor method is used to specify the property that we want to validate. // In this case, we want to validate the Title property. // The NotEmpty method is used to specify that the Title property cannot be empty. // The WithMessage method is used to specify the error message that will be returned // if the validation fails. RuleFor(x => x.Activity).SetValidator(new ActivityValidator()); } } public class Handler : IRequestHandler<Command, Result<Unit>> { private readonly DataContext _context; private readonly IUserAccessor _userAccessor; public Handler(DataContext context, IUserAccessor userAccessor) { _userAccessor = userAccessor; _context = context; } public async Task<Result<Unit>> Handle(Command request, CancellationToken cancellationToken) { var user = await _context.Users.FirstOrDefaultAsync( x => x.UserName == _userAccessor.GetUsername()); var attendee = new ActivityAttendee { AppUser = user, Activity = request.Activity, IsHost = true }; request.Activity.Attendees.Add(attendee); _context.Activities.Add(request.Activity); var result = await _context.SaveChangesAsync() > 0; if(!result) { return Result<Unit>.Failure("Failed to create activity"); } return Result<Unit>.Success(Unit.Value); } } } }
using Lib9c.GraphQL.Types; using Mimir.GraphQL.Objects; using Nekoyume.Model.Elemental; using Nekoyume.Model.Item; using Nekoyume.Model.Stat; namespace Mimir.GraphQL.Types; public class ItemType : ObjectType<ItemObject> { protected override void Configure(IObjectTypeDescriptor<ItemObject> descriptor) { descriptor .Field(f => f.ItemSheetId) .Description("The ItemSheet ID of the item.") .Type<NonNullType<IntType>>(); descriptor .Field(f => f.Grade) .Description("The grade of the item.") .Type<NonNullType<IntType>>(); descriptor .Field(f => f.ItemType) .Description("The ItemType of the item.") .Type<NonNullType<EnumType<Nekoyume.Model.Item.ItemType>>>(); descriptor .Field(f => f.ItemSubType) .Description("The ItemSubType of the item.") .Type<NonNullType<EnumType<ItemSubType>>>(); descriptor .Field(f => f.ElementalType) .Description("The ElementalType of the item.") .Type<NonNullType<EnumType<ElementalType>>>(); descriptor .Field(f => f.Count) .Description("The count of the item.") .Type<NonNullType<IntType>>(); descriptor .Field(f => f.Locked) .Description("The locked status of the item.") .Type<NonNullType<BooleanType>>(); descriptor .Field(f => f.Level) .Description("The level of the item.") .Type<IntType>(); descriptor .Field(f => f.Exp) .Description("The exp of the item.") .Type<LongType>(); descriptor .Field(f => f.RequiredBlockIndex) .Description("The required block index of the item.") .Type<IntType>(); descriptor .Field(f => f.FungibleId) .Description("The Fungible ID of the item.") .Type<HashDigestSHA256Type>(); descriptor .Field(f => f.NonFungibleId) .Description("The Non-Fungible ID of the item.") .Type<GuidType>(); descriptor .Field(f => f.TradableId) .Description("The Tradable ID of the item.") .Type<GuidType>(); descriptor .Field(f => f.Equipped) .Description("The equipped status of the item.") .Type<BooleanType>(); descriptor .Field(f => f.MainStatType) .Description("The main stat type of the item.") .Type<EnumType<StatType>>(); descriptor .Field(f => f.StatsMap) .Description("The stats map of the item.") .Type<StatMapType>(); descriptor .Field(f => f.Skills) .Description("The skills of the item.") .Type<ListType<SkillType>>(); descriptor .Field(f => f.BuffSkills) .Description("The buff skills of the item.") .Type<ListType<SkillType>>(); } }
import { CardWrapper } from "@/components/card-wrapper"; import { FormInput } from "@/components/form-components/form-input"; import { Icons } from "@/components/icons"; import { Button } from "@/components/ui/button"; import { Form } from "@/components/ui/form"; import { NextChatAppForm } from "@/types/form-interface"; import { z } from "zod"; const passwordValidation = new RegExp( /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/ ); export const resetPasswordViewFormSchema = z .object({ newPassword: z .string() .min(1, { message: "Password is required", }) .regex(passwordValidation, { message: "Your password is not valid", }), confirmPassword: z .string() .min(1, { message: "Confirm password is required" }), }) .refine((data) => data.confirmPassword === data.newPassword, { message: "The passwords do not match.", path: ["confirmPassword"], }); export interface ResetPasswordViewProps extends NextChatAppForm<z.infer<typeof resetPasswordViewFormSchema>> {} const ResetPasswordView = (props: ResetPasswordViewProps) => { return ( <CardWrapper backButtonLabel="Back to login" backButtonHref="/login"> <div className="grid gap-5"> <div className="flex flex-col space-y-2"> <p className="text-sm text-muted-foreground text-center"> Please enter a new password </p> <Form {...props.form}> <form onSubmit={props.form.handleSubmit(props.formSubmitHandler)}> <div className="grid gap-2"> <FormInput form={props.form} label="New Password" name="newPassword" disabled={props.form.formState.isSubmitting} type="password" tooltip /> <FormInput form={props.form} label="Confirm Password" name="confirmPassword" disabled={props.form.formState.isSubmitting} type="password" /> <Button disabled={props.form.formState.isSubmitting}> {props.form.formState.isSubmitting && ( <Icons.spinner className="w-4 h-4 mr-2 animate-spin" /> )} Reset password </Button> </div> </form> </Form> </div> </div> </CardWrapper> ); }; export default ResetPasswordView;
#include <iostream> #include <string> class Quote { public: Quote() = default; Quote(const std::string& bn, const double p): bookNo(bn), price(p) {} virtual ~Quote() = default; std::string isbn() const {return bookNo;} virtual double net_price(const size_t n) const {return n * price;} private: std::string bookNo; protected: double price = 0.0; }; class Bulk_quote: public Quote { public: Bulk_quote() = default; Bulk_quote(const std::string& bn, const double p, const size_t min_qty, const double discount): Quote(bn,p), min_qty(min_qty), discount(discount) {} ~Bulk_quote() = default; double net_price(const size_t n) const override; private: size_t min_qty; double discount; }; double Bulk_quote::net_price(const size_t n) const { if (n >= min_qty) return n * (1 - discount) * price; else return n * price; } double print_total(std::ostream& os, const Quote& item, size_t n) { double ret = item.net_price(n); os << "ISBN: " << item.isbn() << "# sold: " << n << "total due: " << ret << std::endl; return ret; } int main() { Quote q("textbook", 10.60); Bulk_quote bq("textbook", 10.60, 10, 0.3); print_total(std::cout, q, 12); print_total(std::cout, bq, 12); return 0; }
import numpy as np import pandas as pd from auxiliary import enumerate_actions class Game: def __init__(self,S,N,nr_steps,multiple): assert S > N self.actions = enumerate_actions(S,N) self.nr_actions = len(self.actions) self.utilities = self.precompute_utilities() self.nr_steps = nr_steps self.multiple = multiple self.history = None def get_utility(self,action1_index, action2_index): soldiers = self.actions[action1_index] - self.actions[action2_index] positions_won = (soldiers>0).sum() positions_lost = (soldiers<0).sum() return np.sign(positions_won - positions_lost) def precompute_utilities(self): utilities = np.empty([self.nr_actions,self.nr_actions]) for i in range(self.nr_actions): for j in range(self.nr_actions): utilities[i,j] = self.get_utility(i,j) return utilities def train_unconditional_regret(self): p1 = Player(self.nr_actions) p2 = Player(self.nr_actions) p1.last_regret = [1000] * self.nr_actions p2.last_regret = [1000] * self.nr_actions history_regrets = [] history_prob = [] history_actions = [] history_max_regrets = [] for i in range(0,self.nr_steps+1): [action1_index,proportions_1] = p1.choose_strategy_unconditional() [action2_index,proportions_2] = p2.choose_strategy_unconditional() utility1 = self.utilities[action1_index,action2_index] utility2 = self.utilities[action2_index,action1_index] regret1 = self.utilities[:,action2_index] - utility1 regret2 = self.utilities[:,action1_index] - utility2 p1.update_unconditional(regret1,action1_index) p2.update_unconditional(regret2,action2_index) ###### add the history #### if i% self.multiple == 0 and i > 1 : #add regrets and probabilities, computing them from regrets history_regrets.append(list(p1.last_regret)+['A',i]) history_regrets.append(list(p2.last_regret)+['B',i]) history_max_regrets.append([p1.last_regret.max() / (i+1),'A',i]) history_max_regrets.append([p2.last_regret.max() / (i+1),'B',i]) history_prob.append(list(proportions_1)+['A',i]) history_prob.append(list(proportions_2)+['B',i]) #add action counts history_actions.append(list(p1.action_count / (i+1))+['A',i]) history_actions.append(list(p2.action_count / (i+1))+['B',i]) #save a history of probabilities, action played counts in a list columns = [str(tuple(i)) for i in self.actions] + ['player','iteration'] df_regrets = pd.DataFrame(history_regrets ,columns = columns) df_prop = pd.DataFrame(history_prob ,columns = columns) df_count = pd.DataFrame(history_actions ,columns = columns) df_max_regrets = pd.DataFrame(history_max_regrets, columns = ['max_regrets','player','iteration'] ) self.history = [df_regrets,df_prop,df_count,df_max_regrets] def train_conditional_regret(self,mu1,mu2,type_): p1 = Player(self.nr_actions) p2 = Player(self.nr_actions) p1.mu,p2.mu = mu1,mu2 p1.last_regret = np.zeros([self.nr_actions,self.nr_actions]) p2.last_regret = np.zeros([self.nr_actions,self.nr_actions]) history_regrets = [] history_prob = [] history_actions = [] history_swaps = [0,0] for i in range(0,self.nr_steps+1): history_regrets.append(list(p1.last_regret)+['A',i]) history_regrets.append(list(p2.last_regret)+['B',i]) [action1_index,proportions_1] = p1.choose_strategy_conditional(type_) [action2_index,proportions_2] = p2.choose_strategy_conditional(type_) if action1_index != p1.last_action : history_swaps[0] += 1 if action2_index != p2.last_action : history_swaps[1] += 1 utility1 = self.utilities[action1_index,action2_index] utility2 = self.utilities[action2_index,action1_index] regret1 = self.utilities[:,action2_index] - utility1 regret2 = self.utilities[:,action1_index] - utility2 p1.update_conditional(regret1,action1_index,utility1,i+1) p2.update_conditional(regret2,action2_index,utility2,i+1) if i % self.multiple == 0: print(p1.last_regret.max() / (i+1),p1.last_regret.max() / (i+1)) history_prob.append(list(proportions_1 / proportions_1.sum())+['A',i]) history_prob.append(list(proportions_2 / proportions_2.sum())+['B',i]) #add action counts history_actions.append(list(p1.action_count / (i+1))+['A',i]) history_actions.append(list(p2.action_count / (i+1))+['B',i]) #save a history of probabilities, action played counts in a list columns = [str(tuple(i)) for i in self.actions] + ['player','iteration'] df_regrets = pd.DataFrame(history_regrets ,columns = columns) df_prop = pd.DataFrame(history_prob ,columns = columns) df_count = pd.DataFrame(history_actions ,columns = columns) self.history = [df_regrets,df_prop,df_count,history_swaps] class Player: def __init__(self, nr_actions): self.action_count = np.zeros(nr_actions) self.nr_actions = nr_actions #this will be sett to vector [0] *nr_actions or matrix [0] *nr_actions depending on which training method we choose self.last_regret = None #needed only for collel conditional training self.last_action = None self.mu = None def choose_strategy_unconditional(self): proportions = np.array([i if i > 0 else 0 for i in self.last_regret]) if proportions.sum() > 0: proportions = proportions / proportions.sum() elif proportions.sum() == 0: proportions = [1/self.nr_actions] * self.nr_actions strategy_index = np.random.choice(self.nr_actions, p=proportions) return [strategy_index,np.array(proportions)] def update_unconditional(self,regret,action_index): self.last_regret += regret self.action_count[action_index] += 1 def choose_strategy_conditional(self,type_): if self.action_count.sum() == 0: proportions = [1/self.nr_actions] * self.nr_actions else: if type_ == 'stationary': A = np.array([[i if i>0 else 0 for i in arr] for arr in self.last_regret]) / self.mu() for i in self.nr_actions: A[i,i] = 0 A[i,i] = 1 - A[i,:].sum() # A is a stochastic matrix (row sums =1 ) proportions = evec_with_eval1(A) elif type_ == 'collel': proportions = np.array([i if i >0 else 0 for i in self.last_regret[self.last_action,:]]) / self.mu proportions[self.last_action] = 0 proportions[self.last_action] = 1 - proportions.sum() strategy_index = np.argmax(np.random.multinomial(1,proportions) > 0) return [strategy_index,np.array(proportions)] #update the last action in update method def update_conditional(self,regret,action_index,iteration): self.last_regret[action_index,:] = (self.last_regret[action_index,:] * iteration + regret) / (iteration + 1) self.action_count[action_index] += 1 #update the last action with the new action played self.last_action = action_index
<template> <div> <main> <h1>Result</h1> <img :src="resultDesc[mbti].img" :alt="resultDesc[mbti].title" /> <h1>{{ resultDesc[mbti].title }}</h1> <p v-html="resultDesc[mbti].description"></p> <Button text="Restart" :clickEvent="reset" /> </main> </div> </template> <script> import { mapState, mapActions } from "vuex"; export default { data() { return { mbti: null, resultDesc: { intj: { img: "/intj.png", title: "Stephen Strange 'Doctor Strange'", description: `Stephen Vincent Strange M.D., Ph.D is a powerful sorcerer and Master of the Mystic Arts. Originally a brilliant, although arrogant, neurosurgeon, Strange got into a car accident which resulted with his hands becoming crippled. When all Western medicine failed him, Strange embarked on a journey that led him into Kamar-Taj where Strange had made the discovery of magic and alternate dimensions, being trained by the Ancient One.`, }, intp: { img: "/intp.png", title: "Bruce Banner 'Hulk'", description: `Bruce Banner is a character portrayed in the Marvel Cinematic Universe (MCU) film franchise first by Edward Norton and currently by Mark Ruffalo, based on the Marvel Comics character of the same name and known commonly by his alter ego, Hulk. In the films, Dr. Banner, is a renowned physicist who subjected himself to a gamma radiation experiment designed to replicate a World War II-era "super soldier" program.`, }, entj: { img: "/entj.png", title: "Nick Fury", description: `Nick Fury is the head of the meta-human regulation organization known as S.H.I.E.L.D. in Marvel and often a go between for the Avengers. He also has a brother who is his exact opposite named Jake who is a villain named Scorpio. While Fury has his superiors, S.H.I.E.L.D.`, }, entp: { img: "/entp.png", title: "Tony Stark “Iron Man”", description: `Tony Stark is a character portrayed by #RobertDowneyJr. in the Marvel Cinematic Universe (MCU) film franchise, based on the Marvel Comics character of the same name and known commonly by his alter ego, Iron Man. In the films, Stark is an industrialist, genius inventor, hero and former playboy who is the CEO of Stark Industries.`, }, infj: { img: "/infj.png", title: "Loki Laufeyson", description: `Loki was born on Jotunheim as the son of the Frost Giant King, Laufey. Small and weak for a Frost Giant, Loki was abandoned by his father in a temple, being left to die. In 965 A.D., not long after the war between the Giants and the Asgardians, Loki was found by King Odin. Adopting Loki and using sorcery to alter his appearance to make him appear to be an Asgardian, Odin raised Loki and his biological son, Thor, with his wife Frigga.`, }, infp: { img: "/infp.png", title: "Wanda Maximoff 'Scarlet Witch'", description: `Wanda Maximoff (February 10th, 1989), also known as The Scarlet Witch, is a native of Sokovia who grew up with her fraternal twin brother, Pietro. In an effort to help purge their country of strife, the twins joined HYDRA and agreed to undergo experiments with the Scepter under the supervision of Wolfgang von Strucker. While her brother developed super-speed, Wanda attained various psionic abilities. When HYDRA fell, the twins joined Ultron to get their revenge on Tony Stark over his weapons killing their family in a bombing, but eventually abandoned him when they discovered Ultron's true intentions to destroy Earth. Wanda and Pietro fought with the Avengers during the Battle of Sokovia to stop Ultron; Pietro was killed during the battle but Wanda survived, and shortly after Ultron's destruction, became a member of the Avengers.`, }, enfj: { img: "/enfj.png", title: "Frigga", description: `Frigga was the Queen of Asgard and wife of Odin, mother of Thor, and adoptive mother of Loki. She attempted to keep the peace between the family even when Loki discovered he was the true son of Laufey and became vengeful towards her and her husband.`, }, enfp: { img: "/enfp.png", title: "Peter Parker 'Spider-Man'", description: `The fictional character Spider-Man, has currently appeared in ten live-action films since his inception, not including fan made shorts and guest appearances in other Marvel Cinematic Universe (MCU) films. Spider-Man is the alter-ego of Peter Parker, a talented young freelance photographer and aspiring scientist imbued with superhuman abilities after being bitten by a radioactive/genetically-altered spider.The first live-action film based on Spider-Man was the unauthorized short Spider-Man by Donald F. Glut in 1969.`, }, istj: { img: "/istj.png", title: "Gamora", description: `Gamora Zen Whoberi Ben Titan was a former Zehoberei assassin and a former member of the Guardians of the Galaxy. She became the adopted daughter of Thanos and adopted sister of Nebula after he killed half of her race.`, }, isfj: { img: "/isfj.png", title: "Steve Rogers 'Captain America'", description: `Steve Rogers (Captain America) is a fictional character portrayed by Chris Evans in the Marvel Cinematic Universe (MCU) film franchise, based on the Marvel Comics character of the same name. In the films, Steve Rogers is a World War II-era U.S. Army soldier who was given enhanced physical and mental capabilities with a "super soldier" serum developed by the military, and who was later frozen in ice for 70 years. As of 2019, the character is one of the central figures of the Marvel Cinematic Universe, having played a major role in seven films of the series, and having a brief cameo in three.`, }, estj: { img: "/estj.png", title: "Xu Wenwu 'Mandarin'", description: `Wenwu (portrayed by #TonyLeung), also known as the Mandarin, is the legendary and nearly mythical leader of the criminal/terrorist organization the Ten Rings. He is also the father of Shang-Chi and Xialing.`, }, esfj: { img: "/esfj.png", title: "May Parker", description: `Maybelle "May" Parker was the aunt of Peter Parker and the widow of the late Ben Parker. She took on the responsibility of raising Peter alone, as she stood by him during Tony Stark's mentorship, while unaware of how he became an intern at Stark Industries.`, }, istp: { img: "/istp.png", title: "Natasha Romanoff 'Black Widow'", description: `Natalia Alianovna "Natasha" Romanoff (Russian: Наталья Альяновна "Наташа" Романов) was one of the most talented spies and assassins in the entire world and a founding member of the Avengers. As a child, she was indoctrinated into the Red Room by General Dreykov, and briefly lived as the surrogate daughter of Alexei Shostakov and Melina Vostokoff while they were undercover in the United States of America. After the Destruction of the North Institute, she underwent extensive psychological conditioning, before graduating from the Red Room as a Widow. Working as an operative for the KGB, she was targeted by S.H.I.E.L.D., before given the chance to ultimately defect to the organization by Clint Barton by assassinating Dreykov. Romanoff succeeded, although having to use his daughter Antonia Dreykov's life as collateral damage would haunt her for the rest of her life.`, }, isfp: { img: "/isfp.png", title: "Xu Shang-Chi", description: `Shang-Chi (Chinese: 尚氣) is the son of Wenwu, the leader of the Ten Rings. Having been trained by the organization since childhood, he has become a master martial artist with skills that are unsurpassed by many.`, }, estp: { img: "/estp.png", title: "Rocket Raccoon", description: `89P13, mainly known as Rocket, is a genetically enhanced creature and a member of the Guardians of the Galaxy. Alongside his friend and partner Groot, Rocket traveled the galaxy, committing crimes and picking up bounties until they met Star-Lord, who convinced them to assist him in selling the Orb for a massive profit. However, as it was discovered that the Orb being sought by Ronan the Accuser was one of the Infinity Stones, Rocket was convinced to risk everything to stop Ronan's plans to destroy Xandar. During the ensuing conflict, Rocket managed to assist his friends in destroying Ronan, despite Groot being killed. Rocket then became a member of the Guardians of the Galaxy alongside the newly planted baby Groot.`, }, esfp: { img: "/esfp.png", title: "Peter Quill “Star-Lord”", description: `Peter Jason Quill is a Celestial-Human hybrid who was abducted from Earth in 1988 by the Yondu Ravager Clan and afterward began building a reputation as the notorious intergalactic outlaw Star-Lord. In 2014, he decided to leave the Ravagers and operate individually, unintentionally becoming a key player in the quest for a precious artifact known as the Orb after stealing it from Morag. Following his arrest, he forged an uneasy alliance with fellow inmates Gamora, Drax the Destroyer, Rocket Raccoon, and Groot, who together formed the Guardians of the Galaxy. They first rallied as a team by stopping Ronan the Accuser from destroying Xandar with the Power Stone.`, }, }, }; }, created() { this.mbti = this.$route.params.mbti; // todo 예외 처리 if (!this.resultDesc[this.$route.params.mbti]) { this.reset(); this.$router.push({ name: "index", }); } }, computed: { ...mapState(["result"]), ...mapActions(["clickReset"]), }, methods: { reset() { this.clickReset; this.$router.push({ name: "index", }); }, }, }; </script> <style> img { width: 300px; } p { margin-bottom: 60px; text-align: left; width: 400px; } </style>
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { IPokemon } from '../pokemon/Pokemon'; @Injectable({ providedIn: 'root', }) export class PokemonService { pokemonList: IPokemon[] = []; private url: string = 'https://pokeapi.co/api/v2/pokemon/'; typeList: any[] = [ { type: 'bug', value: 0, }, { type: 'dragon', value: 0, }, { type: 'electric', value: 0, }, { type: 'fairy', value: 0, }, { type: 'fighting', value: 0, }, { type: 'fire', value: 0, }, { type: 'ghost', value: 0, }, { type: 'grass', value: 0, }, { type: 'ground', value: 0, }, { type: 'ice', value: 0, }, { type: 'normal', value: 0, }, { type: 'poison', value: 0, }, { type: 'psychic', value: 0, }, { type: 'rock', value: 0, }, { type: 'water', value: 0, }, ]; heightList: any[] = []; statsList: any[] = [ { name: 'HP', firstPokemonComparisonSlot: 0, secondPokemonComparisonSlot: 0, }, { name: 'Attack', firstPokemonComparisonSlot: 0, secondPokemonComparisonSlot: 0, }, { name: 'Defense', firstPokemonComparisonSlot: 0, secondPokemonComparisonSlot: 0, }, { name: 'Special Attack', firstPokemonComparisonSlot: 0, secondPokemonComparisonSlot: 0, }, { name: 'Special Defense', firstPokemonComparisonSlot: 0, secondPokemonComparisonSlot: 0, }, { name: 'Speed', firstPokemonComparisonSlot: 0, secondPokemonComparisonSlot: 0, }, ]; constructor(private httpClient: HttpClient) { this.initPokemon(); } initPokemon() { for (let i = 1; i < 152; i++) { let pokemon: IPokemon = { sprite: [], id: undefined, name: '', height: 0, type: '', hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, }; this.httpClient.get(this.url + i).subscribe((data: any) => { pokemon.sprite[0] = data.sprites.front_default; pokemon.sprite[1] = data.sprites.back_default; pokemon.sprite[2] = data.sprites.front_shiny; pokemon.sprite[3] = data.sprites.back_shiny; pokemon.id = data.id; pokemon.name = data.name; pokemon.height = data.height; pokemon.type = data.types[0].type.name; pokemon.hp = data.stats[0].base_stat; pokemon.attack = data.stats[1].base_stat; pokemon.defense = data.stats[2].base_stat; pokemon.specialAttack = data.stats[3].base_stat; pokemon.specialDefense = data.stats[4].base_stat; pokemon.speed = data.stats[5].base_stat; this.calculateTypeCount(pokemon.type); this.buildHeightMap(data.height); }); this.pokemonList.push(pokemon); } } public getPokemon(): IPokemon[] { return this.pokemonList; } initStatList(pokemon: IPokemon) { let statObject = { pokemonName: '', hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, }; statObject.pokemonName = pokemon.name; statObject.hp = pokemon.hp; statObject.attack = pokemon.attack; statObject.defense = pokemon.defense; statObject.specialDefense = pokemon.specialDefense; statObject.specialAttack = pokemon.specialAttack; statObject.speed = pokemon.speed; } buildHeightMap(height: number) { let heightObj = { height: '', value: 1, }; // if(this.heightList.has(height)) { // this.heightList.set(height, this.heightList.get(++height) ); // } // else { // this.heightList.set(height, 1); // } if (this.heightList.some((e) => e.height === height.toString())) { const index = this.heightList.findIndex( (item) => item.height === height.toString() ); ++this.heightList[index].value; } else { heightObj.height = height.toString(); this.heightList.push(heightObj); } } calculateTypeCount(type: string) { switch (type) { case 'bug': { ++this.typeList[0].value; break; } case 'dragon': { this.typeList[1].value++; break; } case 'electric': { this.typeList[2].value++; break; } case 'fairy': { this.typeList[3].value++; break; } case 'fighting': { this.typeList[4].value++; break; } case 'fire': { this.typeList[5].value++; break; } case 'ghost': { this.typeList[6].value++; break; } case 'grass': { this.typeList[7].value++; break; } case 'ground': { this.typeList[8].value++; break; } case 'ice': { this.typeList[9].value++; break; } case 'normal': { this.typeList[10].value++; break; } case 'poison': { this.typeList[11].value++; break; } case 'psychic': { this.typeList[12].value++; break; } case 'rock': { this.typeList[13].value++; break; } case 'water': { this.typeList[14].value++; break; } } } getStatsList() { return this.statsList; } getTypeCount() { return this.typeList; } getHeightCount() { this.heightList.sort((a, b) => parseInt(a.height) < parseInt(b.height) ? -1 : 1 ); return this.heightList; } }
require(rstan) require(cmdstanr) require(here) ###################################################### b = rnorm(10,4,0.5) a = runif(10,1,2) t <- rnorm(150,0,.5) d <- matrix(nrow=150,ncol=10) for(i in 1:150){ for(j in 1:10){ d[i,j]=rnorm(1,b[j]-t[i],1/a[j]) } } ####################################################### data_rt <- list(I = 150, J = 10, Y = d) mod <- cmdstan_model(here('test/lnrt2.stan')) fit <- mod$sample( data = data_rt, seed = 1234, chains = 4, parallel_chains = 4, iter_warmup = 500, iter_sampling = 2000, refresh = 10, adapt_delta = 0.99, max_treedepth = 15 ) fit$cmdstan_summary() stanfit <- rstan::read_stan_csv(fit$output_files()) summary(stanfit, pars = c("mua","sigmaa","mub","sigmab","sigmat"), probs = c(0.025, 0.975))$summary betas <- summary(stanfit, pars = c("b"), probs = c(0.025, 0.975))$summary betas cbind(b,betas[,1]) alphas <- summary(stanfit, pars = c("a"), probs = c(0.025, 0.975))$summary alphas cbind(a,alphas[,1]) tau <- summary(stanfit, pars = c("t"), probs = c(0.025, 0.975))$summary plot(cbind(t,tau[,1])) cor(cbind(t,tau[,1]))